diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml new file mode 100644 index 0000000000..81b7576b9b --- /dev/null +++ b/.github/workflows/main.yml @@ -0,0 +1,33 @@ +name: Run Tests + +on: + pull_request: + branches: + - main + push: + branches: + -main + +jobs: + test: + runs-on: ubuntu-latest + + steps: + - name: Checkout repository + uses: actions/checkout@v4 + + - name: Setup Node.js + uses: actions/setup-node@v4 + with: + node-version: '23' + + - name: Install dependencies + run: npm install + + - name: Install client dependencies + run: | + cd client + npm install + + - name: Run Jest tests + run: npm test diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000000..d7d72bc721 --- /dev/null +++ b/.gitignore @@ -0,0 +1,10 @@ +.env +node_modules/ +backend/*/dist/ +backend/*/coverage/ +**/.DS_Store +kubernetes/matching/matching-configmap.yaml +kubernetes/question/question-configmap.yaml +kubernetes/user/user-configmap.yaml +kubernetes/collaboration/collaboration-configmap.yaml +**/venv/ diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000000..c5f3f6b9c7 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,3 @@ +{ + "java.configuration.updateBuildConfiguration": "interactive" +} \ No newline at end of file diff --git a/README.md b/README.md index 259f7bba2e..3eee55087e 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,9 @@ +[![Review Assignment Due Date](https://classroom.github.com/assets/deadline-readme-button-22041afd0340ce965d47ae6ef1cefeee28c7c493a6346c4f15d667ab976d596c.svg)](https://classroom.github.com/a/bzPrOe11) # CS3219 Project (PeerPrep) - AY2425S1 -## Group: Gxx +## Group: G15 -### Note: -- You can choose to develop individual microservices within separate folders within this repository **OR** use individual repositories (all public) for each microservice. -- In the latter scenario, you should enable sub-modules on this GitHub classroom repository to manage the development/deployment **AND** add your mentor to the individual repositories as a collaborator. -- The teaching team should be given access to the repositories as we may require viewing the history of the repository in case of any disputes or disagreements. +Demo Video [here](https://drive.google.com/file/d/1AD_-VyF5Hrjq25TqJw52XQbbI62O-JG7/view)! + +Access our PeerPrep [here](http://35.202.162.147/)! + +Access our API gateway [here](http://34.54.37.142)! diff --git a/backend/chatlog/Dockerfile b/backend/chatlog/Dockerfile new file mode 100644 index 0000000000..c4248b78ff --- /dev/null +++ b/backend/chatlog/Dockerfile @@ -0,0 +1,12 @@ +FROM node + +WORKDIR /usr/src/app + +COPY package*.json ./ + +RUN npm install + +COPY . . + +EXPOSE 3008 +CMD ["npm", "start"] diff --git a/backend/chatlog/package-lock.json b/backend/chatlog/package-lock.json new file mode 100644 index 0000000000..dddb0b2597 --- /dev/null +++ b/backend/chatlog/package-lock.json @@ -0,0 +1,2581 @@ +{ + "name": "express-kafka-mongo", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "express-kafka-mongo", + "version": "1.0.0", + "dependencies": { + "@types/cors": "^2.8.17", + "@types/express": "^4.17.21", + "@types/express-validator": "^3.0.2", + "@types/mongoose": "^5.11.97", + "@types/node": "^22.8.5", + "cors": "^2.8.5", + "dotenv": "^16.4.5", + "express": "^4.21.0", + "express-validator": "^7.2.0", + "kafkajs": "^2.2.4", + "mongoose": "^8.7.2", + "nodemon": "^3.1.4", + "rimraf": "^6.0.1", + "typescript": "^5.6.2" + }, + "devDependencies": { + "@types/express": "^4.17.11", + "@types/node": "^14.14.37", + "ts-node": "^10.4.0", + "ts-node-dev": "^1.1.8", + "typescript": "^4.2.3" + } + }, + "node_modules/@cspotcode/source-map-support": { + "version": "0.8.1", + "resolved": "https://registry.npmjs.org/@cspotcode/source-map-support/-/source-map-support-0.8.1.tgz", + "integrity": "sha512-IchNf6dN4tHoMFIn/7OE8LWZ19Y6q/67Bmf6vnGREv8RSbBVb9LPJxEcnwrcwX6ixSvaiGoomAUvu4YSxXrVgw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/trace-mapping": "0.3.9" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/@isaacs/cliui": { + "version": "8.0.2", + "resolved": "https://registry.npmjs.org/@isaacs/cliui/-/cliui-8.0.2.tgz", + "integrity": "sha512-O8jcjabXaleOG9DQ0+ARXWZBTfnP4WNAqzuiJK7ll44AmxGKv/J2M4TPjxjY3znBCfvBXFzucm1twdyFybFqEA==", + "license": "ISC", + "dependencies": { + "string-width": "^5.1.2", + "string-width-cjs": "npm:string-width@^4.2.0", + "strip-ansi": "^7.0.1", + "strip-ansi-cjs": "npm:strip-ansi@^6.0.1", + "wrap-ansi": "^8.1.0", + "wrap-ansi-cjs": "npm:wrap-ansi@^7.0.0" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", + "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.0.tgz", + "integrity": "sha512-gv3ZRaISU3fjPAgNsriBRqGWQL6quFx04YMPW/zD8XMLsU32mhCCbfbO6KZFLjvYpCZ8zyDEgqsgf+PwPaM7GQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.9", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.9.tgz", + "integrity": "sha512-3Belt6tdc8bPgAtbcmdtNJlirVoTmEb5e2gC94PnkwEW9jI6CAHUeoG85tjWP5WquqfavoMtMwiG4P926ZKKuQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.0.3", + "@jridgewell/sourcemap-codec": "^1.4.10" + } + }, + "node_modules/@mongodb-js/saslprep": { + "version": "1.1.9", + "resolved": "https://registry.npmjs.org/@mongodb-js/saslprep/-/saslprep-1.1.9.tgz", + "integrity": "sha512-tVkljjeEaAhCqTzajSdgbQ6gE6f3oneVwa3iXR6csiEwXXOFsiC6Uh9iAjAhXPtqa/XMDHWjjeNH/77m/Yq2dw==", + "license": "MIT", + "dependencies": { + "sparse-bitfield": "^3.0.3" + } + }, + "node_modules/@tsconfig/node10": { + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/@tsconfig/node10/-/node10-1.0.11.tgz", + "integrity": "sha512-DcRjDCujK/kCk/cUe8Xz8ZSpm8mS3mNNpta+jGCA6USEDfktlNvm1+IuZ9eTcDbNk41BHwpHHeW+N1lKCz4zOw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@tsconfig/node12": { + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/@tsconfig/node12/-/node12-1.0.11.tgz", + "integrity": "sha512-cqefuRsh12pWyGsIoBKJA9luFu3mRxCA+ORZvA4ktLSzIuCUtWVxGIuXigEwO5/ywWFMZ2QEGKWvkZG1zDMTag==", + "dev": true, + "license": "MIT" + }, + "node_modules/@tsconfig/node14": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/@tsconfig/node14/-/node14-1.0.3.tgz", + "integrity": "sha512-ysT8mhdixWK6Hw3i1V2AeRqZ5WfXg1G43mqoYlM2nc6388Fq5jcXyr5mRsqViLx/GJYdoL0bfXD8nmF+Zn/Iow==", + "dev": true, + "license": "MIT" + }, + "node_modules/@tsconfig/node16": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/@tsconfig/node16/-/node16-1.0.4.tgz", + "integrity": "sha512-vxhUy4J8lyeyinH7Azl1pdd43GJhZH/tP2weN8TntQblOY+A0XbT8DJk1/oCPuOOyg/Ja757rG0CgHcWC8OfMA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/body-parser": { + "version": "1.19.5", + "resolved": "https://registry.npmjs.org/@types/body-parser/-/body-parser-1.19.5.tgz", + "integrity": "sha512-fB3Zu92ucau0iQ0JMCFQE7b/dv8Ot07NI3KaZIkIUNXq82k4eBAqUaneXfleGY9JWskeS9y+u0nXMyspcuQrCg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/connect": "*", + "@types/node": "*" + } + }, + "node_modules/@types/connect": { + "version": "3.4.38", + "resolved": "https://registry.npmjs.org/@types/connect/-/connect-3.4.38.tgz", + "integrity": "sha512-K6uROf1LD88uDQqJCktA4yzL1YYAK6NgfsI0v/mTgyPKWsX1CnJ0XPSDhViejru1GcRkLWb8RlzFYJRqGUbaug==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/cors": { + "version": "2.8.17", + "resolved": "https://registry.npmjs.org/@types/cors/-/cors-2.8.17.tgz", + "integrity": "sha512-8CGDvrBj1zgo2qE+oS3pOCyYNqCPryMWY2bGfwA0dcfopWGgxs+78df0Rs3rc9THP4JkOhLsAa+15VdpAqkcUA==", + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/express": { + "version": "4.17.21", + "resolved": "https://registry.npmjs.org/@types/express/-/express-4.17.21.tgz", + "integrity": "sha512-ejlPM315qwLpaQlQDTjPdsUFSc6ZsP4AN6AlWnogPjQ7CVi7PYF3YVz+CY3jE2pwYf7E/7HlDAN0rV2GxTG0HQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/body-parser": "*", + "@types/express-serve-static-core": "^4.17.33", + "@types/qs": "*", + "@types/serve-static": "*" + } + }, + "node_modules/@types/express-serve-static-core": { + "version": "4.19.6", + "resolved": "https://registry.npmjs.org/@types/express-serve-static-core/-/express-serve-static-core-4.19.6.tgz", + "integrity": "sha512-N4LZ2xG7DatVqhCZzOGb1Yi5lMbXSZcmdLDe9EzSndPV2HpWYWzRbaerl2n27irrm94EPpprqa8KpskPT085+A==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*", + "@types/qs": "*", + "@types/range-parser": "*", + "@types/send": "*" + } + }, + "node_modules/@types/express-validator": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/@types/express-validator/-/express-validator-3.0.2.tgz", + "integrity": "sha512-dV+1u6absDDEIVe5jd5ID1XYvPPvOSvggMWh09VYM3TeBjAjBDtwJWyJg/5PnK7s8FRgbOtHgD6oX3N2MKWwDw==", + "deprecated": "This is a stub types definition. express-validator provides its own type definitions, so you do not need this installed.", + "license": "MIT", + "dependencies": { + "express-validator": "*" + } + }, + "node_modules/@types/http-errors": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/@types/http-errors/-/http-errors-2.0.4.tgz", + "integrity": "sha512-D0CFMMtydbJAegzOyHjtiKPLlvnm3iTZyZRSZoLq2mRhDdmLfIWOCYPfQJ4cu2erKghU++QvjcUjp/5h7hESpA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/mime": { + "version": "1.3.5", + "resolved": "https://registry.npmjs.org/@types/mime/-/mime-1.3.5.tgz", + "integrity": "sha512-/pyBZWSLD2n0dcHE3hq8s8ZvcETHtEuF+3E7XVt0Ig2nvsVQXdghHVcEkIWjy9A0wKfTn97a/PSDYohKIlnP/w==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/mongoose": { + "version": "5.11.97", + "resolved": "https://registry.npmjs.org/@types/mongoose/-/mongoose-5.11.97.tgz", + "integrity": "sha512-cqwOVYT3qXyLiGw7ueU2kX9noE8DPGRY6z8eUxudhXY8NZ7DMKYAxyZkLSevGfhCX3dO/AoX5/SO9lAzfjon0Q==", + "deprecated": "Mongoose publishes its own types, so you do not need to install this package.", + "license": "MIT", + "dependencies": { + "mongoose": "*" + } + }, + "node_modules/@types/node": { + "version": "14.18.63", + "resolved": "https://registry.npmjs.org/@types/node/-/node-14.18.63.tgz", + "integrity": "sha512-fAtCfv4jJg+ExtXhvCkCqUKZ+4ok/JQk01qDKhL5BDDoS3AxKXhV5/MAVUZyQnSEd2GT92fkgZl0pz0Q0AzcIQ==", + "license": "MIT" + }, + "node_modules/@types/qs": { + "version": "6.9.17", + "resolved": "https://registry.npmjs.org/@types/qs/-/qs-6.9.17.tgz", + "integrity": "sha512-rX4/bPcfmvxHDv0XjfJELTTr+iB+tn032nPILqHm5wbthUUUuVtNGGqzhya9XUxjTP8Fpr0qYgSZZKxGY++svQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/range-parser": { + "version": "1.2.7", + "resolved": "https://registry.npmjs.org/@types/range-parser/-/range-parser-1.2.7.tgz", + "integrity": "sha512-hKormJbkJqzQGhziax5PItDUTMAM9uE2XXQmM37dyd4hVM+5aVl7oVxMVUiVQn2oCQFN/LKCZdvSM0pFRqbSmQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/send": { + "version": "0.17.4", + "resolved": "https://registry.npmjs.org/@types/send/-/send-0.17.4.tgz", + "integrity": "sha512-x2EM6TJOybec7c52BX0ZspPodMsQUd5L6PRwOunVyVUhXiBSKf3AezDL8Dgvgt5o0UfKNfuA0eMLr2wLT4AiBA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/mime": "^1", + "@types/node": "*" + } + }, + "node_modules/@types/serve-static": { + "version": "1.15.7", + "resolved": "https://registry.npmjs.org/@types/serve-static/-/serve-static-1.15.7.tgz", + "integrity": "sha512-W8Ym+h8nhuRwaKPaDw34QUkwsGi6Rc4yYqvKFo5rm2FUEhCFbzVWrxXUxuKK8TASjWsysJY0nsmNCGhCOIsrOw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/http-errors": "*", + "@types/node": "*", + "@types/send": "*" + } + }, + "node_modules/@types/strip-bom": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@types/strip-bom/-/strip-bom-3.0.0.tgz", + "integrity": "sha512-xevGOReSYGM7g/kUBZzPqCrR/KYAo+F0yiPc85WFTJa0MSLtyFTVTU6cJu/aV4mid7IffDIWqo69THF2o4JiEQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/strip-json-comments": { + "version": "0.0.30", + "resolved": "https://registry.npmjs.org/@types/strip-json-comments/-/strip-json-comments-0.0.30.tgz", + "integrity": "sha512-7NQmHra/JILCd1QqpSzl8+mJRc8ZHz3uDm8YV1Ks9IhK0epEiTw8aIErbvH9PI+6XbqhyIQy3462nEsn7UVzjQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/webidl-conversions": { + "version": "7.0.3", + "resolved": "https://registry.npmjs.org/@types/webidl-conversions/-/webidl-conversions-7.0.3.tgz", + "integrity": "sha512-CiJJvcRtIgzadHCYXw7dqEnMNRjhGZlYK05Mj9OyktqV8uVT8fD2BFOB7S1uwBE3Kj2Z+4UyPmFw/Ixgw/LAlA==", + "license": "MIT" + }, + "node_modules/@types/whatwg-url": { + "version": "11.0.5", + "resolved": "https://registry.npmjs.org/@types/whatwg-url/-/whatwg-url-11.0.5.tgz", + "integrity": "sha512-coYR071JRaHa+xoEvvYqvnIHaVqaYrLPbsufM9BF63HkwI5Lgmy2QR8Q5K/lYDYo5AK82wOvSOS0UsLTpTG7uQ==", + "license": "MIT", + "dependencies": { + "@types/webidl-conversions": "*" + } + }, + "node_modules/accepts": { + "version": "1.3.8", + "resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.8.tgz", + "integrity": "sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw==", + "license": "MIT", + "dependencies": { + "mime-types": "~2.1.34", + "negotiator": "0.6.3" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/acorn": { + "version": "8.14.0", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.14.0.tgz", + "integrity": "sha512-cl669nCJTZBsL97OF4kUQm5g5hC2uihk0NxY3WENAC0TYdILVkAyHymAntgxGkl7K+t0cXIrH5siy5S4XkFycA==", + "dev": true, + "license": "MIT", + "bin": { + "acorn": "bin/acorn" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/acorn-walk": { + "version": "8.3.4", + "resolved": "https://registry.npmjs.org/acorn-walk/-/acorn-walk-8.3.4.tgz", + "integrity": "sha512-ueEepnujpqee2o5aIYnvHU6C0A42MNdsIDeqy5BydrkuC5R1ZuUFnm27EeFJGoEHJQgn3uleRvmTXaJgfXbt4g==", + "dev": true, + "license": "MIT", + "dependencies": { + "acorn": "^8.11.0" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/ansi-regex": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.1.0.tgz", + "integrity": "sha512-7HSX4QQb4CspciLpVFwyRe79O3xsIZDDLER21kERQ71oaPodF8jL725AgJMFAYbooIqolJoRLuM81SpeUkpkvA==", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-regex?sponsor=1" + } + }, + "node_modules/ansi-styles": { + "version": "6.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.1.tgz", + "integrity": "sha512-bN798gFfQX+viw3R7yrGWRqnrN2oRkEkUjjl4JNn4E8GxxbjtG3FbrEIIY3l8/hrwUwIeCZvi4QuOTP4MErVug==", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/anymatch": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.3.tgz", + "integrity": "sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw==", + "license": "ISC", + "dependencies": { + "normalize-path": "^3.0.0", + "picomatch": "^2.0.4" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/arg": { + "version": "4.1.3", + "resolved": "https://registry.npmjs.org/arg/-/arg-4.1.3.tgz", + "integrity": "sha512-58S9QDqG0Xx27YwPSt9fJxivjYl432YCwfDMfZ+71RAqUrZef7LrKQZ3LHLOwCS4FLNBplP533Zx895SeOCHvA==", + "dev": true, + "license": "MIT" + }, + "node_modules/array-flatten": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz", + "integrity": "sha512-PCVAQswWemu6UdxsDFFX/+gVeYqKAod3D3UVm91jHwynguOwAvYPhx8nNlM++NqRcK6CxxpUafjmhIdKiHibqg==", + "license": "MIT" + }, + "node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", + "license": "MIT" + }, + "node_modules/binary-extensions": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.3.0.tgz", + "integrity": "sha512-Ceh+7ox5qe7LJuLHoY0feh3pHuUDHAcRUeyL2VYghZwfpkNIy/+8Ocg0a3UuSoYzavmylwuLWQOf3hl0jjMMIw==", + "license": "MIT", + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/body-parser": { + "version": "1.20.3", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.3.tgz", + "integrity": "sha512-7rAxByjUMqQ3/bHJy7D6OGXvx/MMc4IqBn/X0fcM1QUcAItpZrBEYhWGem+tzXH90c+G01ypMcYJBO9Y30203g==", + "license": "MIT", + "dependencies": { + "bytes": "3.1.2", + "content-type": "~1.0.5", + "debug": "2.6.9", + "depd": "2.0.0", + "destroy": "1.2.0", + "http-errors": "2.0.0", + "iconv-lite": "0.4.24", + "on-finished": "2.4.1", + "qs": "6.13.0", + "raw-body": "2.5.2", + "type-is": "~1.6.18", + "unpipe": "1.0.0" + }, + "engines": { + "node": ">= 0.8", + "npm": "1.2.8000 || >= 1.4.16" + } + }, + "node_modules/brace-expansion": { + "version": "1.1.11", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", + "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "node_modules/braces": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.3.tgz", + "integrity": "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==", + "license": "MIT", + "dependencies": { + "fill-range": "^7.1.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/bson": { + "version": "6.9.0", + "resolved": "https://registry.npmjs.org/bson/-/bson-6.9.0.tgz", + "integrity": "sha512-X9hJeyeM0//Fus+0pc5dSUMhhrrmWwQUtdavaQeF3Ta6m69matZkGWV/MrBcnwUeLC8W9kwwc2hfkZgUuCX3Ig==", + "license": "Apache-2.0", + "engines": { + "node": ">=16.20.1" + } + }, + "node_modules/buffer-from": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz", + "integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/bytes": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", + "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/call-bind": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.7.tgz", + "integrity": "sha512-GHTSNSYICQ7scH7sZ+M2rFopRoLh8t2bLSW6BbgrtLsahOIB5iyAVJf9GjWK3cYTDaMj4XdBpM1cA6pIS0Kv2w==", + "license": "MIT", + "dependencies": { + "es-define-property": "^1.0.0", + "es-errors": "^1.3.0", + "function-bind": "^1.1.2", + "get-intrinsic": "^1.2.4", + "set-function-length": "^1.2.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/chokidar": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.6.0.tgz", + "integrity": "sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw==", + "license": "MIT", + "dependencies": { + "anymatch": "~3.1.2", + "braces": "~3.0.2", + "glob-parent": "~5.1.2", + "is-binary-path": "~2.1.0", + "is-glob": "~4.0.1", + "normalize-path": "~3.0.0", + "readdirp": "~3.6.0" + }, + "engines": { + "node": ">= 8.10.0" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + }, + "optionalDependencies": { + "fsevents": "~2.3.2" + } + }, + "node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "license": "MIT", + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "license": "MIT" + }, + "node_modules/concat-map": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", + "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==", + "license": "MIT" + }, + "node_modules/content-disposition": { + "version": "0.5.4", + "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.4.tgz", + "integrity": "sha512-FveZTNuGw04cxlAiWbzi6zTAL/lhehaWbTtgluJh4/E95DqMwTmha3KZN1aAWA8cFIhHzMZUvLevkw5Rqk+tSQ==", + "license": "MIT", + "dependencies": { + "safe-buffer": "5.2.1" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/content-type": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz", + "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie": { + "version": "0.7.1", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.1.tgz", + "integrity": "sha512-6DnInpx7SJ2AK3+CTUE/ZM0vWTUboZCegxhC2xiIydHR9jNuTAASBrfEpHhiGOZw/nX51bHt6YQl8jsGo4y/0w==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie-signature": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.6.tgz", + "integrity": "sha512-QADzlaHc8icV8I7vbaJXJwod9HWYp8uCqf1xa4OfNu1T7JVxQIrUgOWtHdNDtPiywmFbiS12VjotIXLrKM3orQ==", + "license": "MIT" + }, + "node_modules/cors": { + "version": "2.8.5", + "resolved": "https://registry.npmjs.org/cors/-/cors-2.8.5.tgz", + "integrity": "sha512-KIHbLJqu73RGr/hnbrO9uBeixNGuvSQjul/jdFvS/KFSIH1hWVd1ng7zOHx+YrEfInLG7q4n6GHQ9cDtxv/P6g==", + "license": "MIT", + "dependencies": { + "object-assign": "^4", + "vary": "^1" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/create-require": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/create-require/-/create-require-1.1.1.tgz", + "integrity": "sha512-dcKFX3jn0MpIaXjisoRvexIJVEKzaq7z2rZKxf+MSr9TkdmHmsU4m2lcLojrj/FHl8mk5VxMmYA+ftRkP/3oKQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/cross-spawn": { + "version": "7.0.5", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.5.tgz", + "integrity": "sha512-ZVJrKKYunU38/76t0RMOulHOnUcbU9GbpWKAOZ0mhjr7CX6FVrH+4FrAapSOekrgFQ3f/8gwMEuIft0aKq6Hug==", + "license": "MIT", + "dependencies": { + "path-key": "^3.1.0", + "shebang-command": "^2.0.0", + "which": "^2.0.1" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "license": "MIT", + "dependencies": { + "ms": "2.0.0" + } + }, + "node_modules/define-data-property": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/define-data-property/-/define-data-property-1.1.4.tgz", + "integrity": "sha512-rBMvIzlpA8v6E+SJZoo++HAYqsLrkg7MSfIinMPFhmkorw7X+dOXVJQs+QT69zGkzMyfDnIMN2Wid1+NbL3T+A==", + "license": "MIT", + "dependencies": { + "es-define-property": "^1.0.0", + "es-errors": "^1.3.0", + "gopd": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/depd": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", + "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/destroy": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/destroy/-/destroy-1.2.0.tgz", + "integrity": "sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg==", + "license": "MIT", + "engines": { + "node": ">= 0.8", + "npm": "1.2.8000 || >= 1.4.16" + } + }, + "node_modules/diff": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/diff/-/diff-4.0.2.tgz", + "integrity": "sha512-58lmxKSA4BNyLz+HHMUzlOEpg09FV+ev6ZMe3vJihgdxzgcwZ8VoEEPmALCZG9LmqfVoNMMKpttIYTVG6uDY7A==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.3.1" + } + }, + "node_modules/dotenv": { + "version": "16.4.5", + "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.4.5.tgz", + "integrity": "sha512-ZmdL2rui+eB2YwhsWzjInR8LldtZHGDoQ1ugH85ppHKwpUHL7j7rN0Ti9NCnGiQbhaZ11FpR+7ao1dNsmduNUg==", + "license": "BSD-2-Clause", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://dotenvx.com" + } + }, + "node_modules/dynamic-dedupe": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/dynamic-dedupe/-/dynamic-dedupe-0.3.0.tgz", + "integrity": "sha512-ssuANeD+z97meYOqd50e04Ze5qp4bPqo8cCkI4TRjZkzAUgIDTrXV1R8QCdINpiI+hw14+rYazvTRdQrz0/rFQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "xtend": "^4.0.0" + } + }, + "node_modules/eastasianwidth": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/eastasianwidth/-/eastasianwidth-0.2.0.tgz", + "integrity": "sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA==", + "license": "MIT" + }, + "node_modules/ee-first": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", + "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==", + "license": "MIT" + }, + "node_modules/emoji-regex": { + "version": "9.2.2", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-9.2.2.tgz", + "integrity": "sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg==", + "license": "MIT" + }, + "node_modules/encodeurl": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz", + "integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/es-define-property": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.0.tgz", + "integrity": "sha512-jxayLKShrEqqzJ0eumQbVhTYQM27CfT1T35+gCgDFoL82JLsXqTJ76zv6A0YLOgEnLUMvLzsDsGIrl8NFpT2gQ==", + "license": "MIT", + "dependencies": { + "get-intrinsic": "^1.2.4" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/escape-html": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", + "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==", + "license": "MIT" + }, + "node_modules/etag": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", + "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/express": { + "version": "4.21.1", + "resolved": "https://registry.npmjs.org/express/-/express-4.21.1.tgz", + "integrity": "sha512-YSFlK1Ee0/GC8QaO91tHcDxJiE/X4FbpAyQWkxAvG6AXCuR65YzK8ua6D9hvi/TzUfZMpc+BwuM1IPw8fmQBiQ==", + "license": "MIT", + "dependencies": { + "accepts": "~1.3.8", + "array-flatten": "1.1.1", + "body-parser": "1.20.3", + "content-disposition": "0.5.4", + "content-type": "~1.0.4", + "cookie": "0.7.1", + "cookie-signature": "1.0.6", + "debug": "2.6.9", + "depd": "2.0.0", + "encodeurl": "~2.0.0", + "escape-html": "~1.0.3", + "etag": "~1.8.1", + "finalhandler": "1.3.1", + "fresh": "0.5.2", + "http-errors": "2.0.0", + "merge-descriptors": "1.0.3", + "methods": "~1.1.2", + "on-finished": "2.4.1", + "parseurl": "~1.3.3", + "path-to-regexp": "0.1.10", + "proxy-addr": "~2.0.7", + "qs": "6.13.0", + "range-parser": "~1.2.1", + "safe-buffer": "5.2.1", + "send": "0.19.0", + "serve-static": "1.16.2", + "setprototypeof": "1.2.0", + "statuses": "2.0.1", + "type-is": "~1.6.18", + "utils-merge": "1.0.1", + "vary": "~1.1.2" + }, + "engines": { + "node": ">= 0.10.0" + } + }, + "node_modules/express-validator": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/express-validator/-/express-validator-7.2.0.tgz", + "integrity": "sha512-I2ByKD8panjtr8Y05l21Wph9xk7kk64UMyvJCl/fFM/3CTJq8isXYPLeKW/aZBCdb/LYNv63PwhY8khw8VWocA==", + "license": "MIT", + "dependencies": { + "lodash": "^4.17.21", + "validator": "~13.12.0" + }, + "engines": { + "node": ">= 8.0.0" + } + }, + "node_modules/fill-range": { + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz", + "integrity": "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==", + "license": "MIT", + "dependencies": { + "to-regex-range": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/finalhandler": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.3.1.tgz", + "integrity": "sha512-6BN9trH7bp3qvnrRyzsBz+g3lZxTNZTbVO2EV1CS0WIcDbawYVdYvGflME/9QP0h0pYlCDBCTjYa9nZzMDpyxQ==", + "license": "MIT", + "dependencies": { + "debug": "2.6.9", + "encodeurl": "~2.0.0", + "escape-html": "~1.0.3", + "on-finished": "2.4.1", + "parseurl": "~1.3.3", + "statuses": "2.0.1", + "unpipe": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/foreground-child": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/foreground-child/-/foreground-child-3.3.0.tgz", + "integrity": "sha512-Ld2g8rrAyMYFXBhEqMz8ZAHBi4J4uS1i/CxGMDnjyFWddMXLVcDp051DZfu+t7+ab7Wv6SMqpWmyFIj5UbfFvg==", + "license": "ISC", + "dependencies": { + "cross-spawn": "^7.0.0", + "signal-exit": "^4.0.1" + }, + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/forwarded": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz", + "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/fresh": { + "version": "0.5.2", + "resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz", + "integrity": "sha512-zJ2mQYM18rEFOudeV4GShTGIQ7RbzA7ozbU9I/XBpm7kqgMywgmylMwXHxZJmkVoYkna9d2pVXVXPdYTP9ej8Q==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/fs.realpath": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", + "integrity": "sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==", + "dev": true, + "license": "ISC" + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-intrinsic": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.2.4.tgz", + "integrity": "sha512-5uYhsJH8VJBTv7oslg4BznJYhDoRI6waYCxMmCdnTrcCrHA/fCFKoTFz2JKKE0HdDFUF7/oQuhzumXJK7paBRQ==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2", + "has-proto": "^1.0.1", + "has-symbols": "^1.0.3", + "hasown": "^2.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/glob": { + "version": "11.0.0", + "resolved": "https://registry.npmjs.org/glob/-/glob-11.0.0.tgz", + "integrity": "sha512-9UiX/Bl6J2yaBbxKoEBRm4Cipxgok8kQYcOPEhScPwebu2I0HoQOuYdIO6S3hLuWoZgpDpwQZMzTFxgpkyT76g==", + "license": "ISC", + "dependencies": { + "foreground-child": "^3.1.0", + "jackspeak": "^4.0.1", + "minimatch": "^10.0.0", + "minipass": "^7.1.2", + "package-json-from-dist": "^1.0.0", + "path-scurry": "^2.0.0" + }, + "bin": { + "glob": "dist/esm/bin.mjs" + }, + "engines": { + "node": "20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/glob-parent": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz", + "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==", + "license": "ISC", + "dependencies": { + "is-glob": "^4.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/glob/node_modules/brace-expansion": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.1.tgz", + "integrity": "sha512-XnAIvQ8eM+kC6aULx6wuQiwVsnzsi9d3WxzV3FpWTGA19F621kwdbsAcFKXgKUHZWsy+mY6iL1sHTxWEFCytDA==", + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0" + } + }, + "node_modules/glob/node_modules/minimatch": { + "version": "10.0.1", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.0.1.tgz", + "integrity": "sha512-ethXTt3SGGR+95gudmqJ1eNhRO7eGEGIgYA9vnPatK4/etz2MEVDno5GMCibdMTuBMyElzIlgxMna3K94XDIDQ==", + "license": "ISC", + "dependencies": { + "brace-expansion": "^2.0.1" + }, + "engines": { + "node": "20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/gopd": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.0.1.tgz", + "integrity": "sha512-d65bNlIadxvpb/A2abVdlqKqV563juRnZ1Wtk6s1sIR8uNsXR70xqIzVqxVf1eTqDunwT2MkczEeaezCKTZhwA==", + "license": "MIT", + "dependencies": { + "get-intrinsic": "^1.1.3" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-flag": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", + "integrity": "sha512-sKJf1+ceQBr4SMkvQnBDNDtf4TXpVhVGateu0t918bl30FnbE2m4vNLX+VWe/dpjlb+HugGYzW7uQXH98HPEYw==", + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/has-property-descriptors": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-property-descriptors/-/has-property-descriptors-1.0.2.tgz", + "integrity": "sha512-55JNKuIW+vq4Ke1BjOTjM2YctQIvCT7GFzHwmfZPGo5wnrgkid0YQtnAleFSqumZm4az3n2BS+erby5ipJdgrg==", + "license": "MIT", + "dependencies": { + "es-define-property": "^1.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-proto": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/has-proto/-/has-proto-1.0.3.tgz", + "integrity": "sha512-SJ1amZAJUiZS+PhsVLf5tGydlaVB8EdFpaSO4gmiUKUOxk8qzn5AIy4ZeJUmh22znIdk/uMAUT2pl3FxzVUH+Q==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-symbols": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.3.tgz", + "integrity": "sha512-l3LCuF6MgDNwTDKkdYGEihYjt5pRPbEg46rtlmnSPlUbgmB8LOIrKJbYYFBSbnPaJexMKtiPO8hmeRjRz2Td+A==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/hasown": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz", + "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==", + "license": "MIT", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/http-errors": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.0.tgz", + "integrity": "sha512-FtwrG/euBzaEjYeRqOgly7G0qviiXoJWnvEH2Z1plBdXgbyjv34pHTSb9zoeHMyDy33+DWy5Wt9Wo+TURtOYSQ==", + "license": "MIT", + "dependencies": { + "depd": "2.0.0", + "inherits": "2.0.4", + "setprototypeof": "1.2.0", + "statuses": "2.0.1", + "toidentifier": "1.0.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/iconv-lite": { + "version": "0.4.24", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz", + "integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==", + "license": "MIT", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/ignore-by-default": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/ignore-by-default/-/ignore-by-default-1.0.1.tgz", + "integrity": "sha512-Ius2VYcGNk7T90CppJqcIkS5ooHUZyIQK+ClZfMfMNFEF9VSE73Fq+906u/CWu92x4gzZMWOwfFYckPObzdEbA==", + "license": "ISC" + }, + "node_modules/inflight": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", + "integrity": "sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA==", + "deprecated": "This module is not supported, and leaks memory. Do not use it. Check out lru-cache if you want a good and tested way to coalesce async requests by a key value, which is much more comprehensive and powerful.", + "dev": true, + "license": "ISC", + "dependencies": { + "once": "^1.3.0", + "wrappy": "1" + } + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "license": "ISC" + }, + "node_modules/ipaddr.js": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz", + "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==", + "license": "MIT", + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/is-binary-path": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/is-binary-path/-/is-binary-path-2.1.0.tgz", + "integrity": "sha512-ZMERYes6pDydyuGidse7OsHxtbI7WVeUEozgR/g7rd0xUimYNlvZRE/K2MgZTjWy725IfelLeVcEM97mmtRGXw==", + "license": "MIT", + "dependencies": { + "binary-extensions": "^2.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/is-core-module": { + "version": "2.15.1", + "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.15.1.tgz", + "integrity": "sha512-z0vtXSwucUJtANQWldhbtbt7BnL0vxiFjIdDLAatwhDYty2bad6s+rijD6Ri4YuYJubLzIJLUidCh09e1djEVQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "hasown": "^2.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-extglob": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", + "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-fullwidth-code-point": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/is-glob": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", + "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", + "license": "MIT", + "dependencies": { + "is-extglob": "^2.1.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-number": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", + "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", + "license": "MIT", + "engines": { + "node": ">=0.12.0" + } + }, + "node_modules/isexe": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", + "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==", + "license": "ISC" + }, + "node_modules/jackspeak": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/jackspeak/-/jackspeak-4.0.2.tgz", + "integrity": "sha512-bZsjR/iRjl1Nk1UkjGpAzLNfQtzuijhn2g+pbZb98HQ1Gk8vM9hfbxeMBP+M2/UUdwj0RqGG3mlvk2MsAqwvEw==", + "license": "BlueOak-1.0.0", + "dependencies": { + "@isaacs/cliui": "^8.0.2" + }, + "engines": { + "node": "20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/kafkajs": { + "version": "2.2.4", + "resolved": "https://registry.npmjs.org/kafkajs/-/kafkajs-2.2.4.tgz", + "integrity": "sha512-j/YeapB1vfPT2iOIUn/vxdyKEuhuY2PxMBvf5JWux6iSaukAccrMtXEY/Lb7OvavDhOWME589bpLrEdnVHjfjA==", + "license": "MIT", + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/kareem": { + "version": "2.6.3", + "resolved": "https://registry.npmjs.org/kareem/-/kareem-2.6.3.tgz", + "integrity": "sha512-C3iHfuGUXK2u8/ipq9LfjFfXFxAZMQJJq7vLS45r3D9Y2xQ/m4S8zaR4zMLFWh9AsNPXmcFfUDhTEO8UIC/V6Q==", + "license": "Apache-2.0", + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/lodash": { + "version": "4.17.21", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz", + "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==", + "license": "MIT" + }, + "node_modules/lru-cache": { + "version": "11.0.2", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.0.2.tgz", + "integrity": "sha512-123qHRfJBmo2jXDbo/a5YOQrJoHF/GNQTLzQ5+IdK5pWpceK17yRc6ozlWd25FxvGKQbIUs91fDFkXmDHTKcyA==", + "license": "ISC", + "engines": { + "node": "20 || >=22" + } + }, + "node_modules/make-error": { + "version": "1.3.6", + "resolved": "https://registry.npmjs.org/make-error/-/make-error-1.3.6.tgz", + "integrity": "sha512-s8UhlNe7vPKomQhC1qFelMokr/Sc3AgNbso3n74mVPA5LTZwkB9NlXf4XPamLxJE8h0gh73rM94xvwRT2CVInw==", + "dev": true, + "license": "ISC" + }, + "node_modules/media-typer": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz", + "integrity": "sha512-dq+qelQ9akHpcOl/gUVRTxVIOkAJ1wR3QAvb4RsVjS8oVoFjDGTc679wJYmUmknUF5HwMLOgb5O+a3KxfWapPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/memory-pager": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/memory-pager/-/memory-pager-1.5.0.tgz", + "integrity": "sha512-ZS4Bp4r/Zoeq6+NLJpP+0Zzm0pR8whtGPf1XExKLJBAczGMnSi3It14OiNCStjQjM6NU1okjQGSxgEZN8eBYKg==", + "license": "MIT" + }, + "node_modules/merge-descriptors": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.3.tgz", + "integrity": "sha512-gaNvAS7TZ897/rVaZ0nMtAyxNyi/pdbjbAwUpFQpN70GqnVfOiXpeUUMKRBmzXaSQ8DdTX4/0ms62r2K+hE6mQ==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/methods": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/methods/-/methods-1.1.2.tgz", + "integrity": "sha512-iclAHeNqNm68zFtnZ0e+1L2yUIdvzNoauKU4WBA3VvH/vPFieF7qfRlwUZU+DA9P9bPXIS90ulxoUoCH23sV2w==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/mime/-/mime-1.6.0.tgz", + "integrity": "sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg==", + "license": "MIT", + "bin": { + "mime": "cli.js" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/mime-db": { + "version": "1.52.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", + "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "2.1.35", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", + "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", + "license": "MIT", + "dependencies": { + "mime-db": "1.52.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/minimatch": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", + "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", + "license": "ISC", + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, + "node_modules/minimist": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz", + "integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/minipass": { + "version": "7.1.2", + "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.2.tgz", + "integrity": "sha512-qOOzS1cBTWYF4BH8fVePDBOO9iptMnGUEZwNc/cMWnTV2nVLZ7VoNWEPHkYczZA0pdoA7dl6e7FL659nX9S2aw==", + "license": "ISC", + "engines": { + "node": ">=16 || 14 >=14.17" + } + }, + "node_modules/mkdirp": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-1.0.4.tgz", + "integrity": "sha512-vVqVZQyf3WLx2Shd0qJ9xuvqgAyKPLAiqITEtqW0oIUjzo3PePDd6fW9iFz30ef7Ysp/oiWqbhszeGWW2T6Gzw==", + "dev": true, + "license": "MIT", + "bin": { + "mkdirp": "bin/cmd.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/mongodb": { + "version": "6.10.0", + "resolved": "https://registry.npmjs.org/mongodb/-/mongodb-6.10.0.tgz", + "integrity": "sha512-gP9vduuYWb9ZkDM546M+MP2qKVk5ZG2wPF63OvSRuUbqCR+11ZCAE1mOfllhlAG0wcoJY5yDL/rV3OmYEwXIzg==", + "license": "Apache-2.0", + "dependencies": { + "@mongodb-js/saslprep": "^1.1.5", + "bson": "^6.7.0", + "mongodb-connection-string-url": "^3.0.0" + }, + "engines": { + "node": ">=16.20.1" + }, + "peerDependencies": { + "@aws-sdk/credential-providers": "^3.188.0", + "@mongodb-js/zstd": "^1.1.0", + "gcp-metadata": "^5.2.0", + "kerberos": "^2.0.1", + "mongodb-client-encryption": ">=6.0.0 <7", + "snappy": "^7.2.2", + "socks": "^2.7.1" + }, + "peerDependenciesMeta": { + "@aws-sdk/credential-providers": { + "optional": true + }, + "@mongodb-js/zstd": { + "optional": true + }, + "gcp-metadata": { + "optional": true + }, + "kerberos": { + "optional": true + }, + "mongodb-client-encryption": { + "optional": true + }, + "snappy": { + "optional": true + }, + "socks": { + "optional": true + } + } + }, + "node_modules/mongodb-connection-string-url": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/mongodb-connection-string-url/-/mongodb-connection-string-url-3.0.1.tgz", + "integrity": "sha512-XqMGwRX0Lgn05TDB4PyG2h2kKO/FfWJyCzYQbIhXUxz7ETt0I/FqHjUeqj37irJ+Dl1ZtU82uYyj14u2XsZKfg==", + "license": "Apache-2.0", + "dependencies": { + "@types/whatwg-url": "^11.0.2", + "whatwg-url": "^13.0.0" + } + }, + "node_modules/mongoose": { + "version": "8.8.1", + "resolved": "https://registry.npmjs.org/mongoose/-/mongoose-8.8.1.tgz", + "integrity": "sha512-l7DgeY1szT98+EKU8GYnga5WnyatAu+kOQ2VlVX1Mxif6A0Umt0YkSiksCiyGxzx8SPhGe9a53ND1GD4yVDrPA==", + "license": "MIT", + "dependencies": { + "bson": "^6.7.0", + "kareem": "2.6.3", + "mongodb": "~6.10.0", + "mpath": "0.9.0", + "mquery": "5.0.0", + "ms": "2.1.3", + "sift": "17.1.3" + }, + "engines": { + "node": ">=16.20.1" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/mongoose" + } + }, + "node_modules/mongoose/node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "license": "MIT" + }, + "node_modules/mpath": { + "version": "0.9.0", + "resolved": "https://registry.npmjs.org/mpath/-/mpath-0.9.0.tgz", + "integrity": "sha512-ikJRQTk8hw5DEoFVxHG1Gn9T/xcjtdnOKIU1JTmGjZZlg9LST2mBLmcX3/ICIbgJydT2GOc15RnNy5mHmzfSew==", + "license": "MIT", + "engines": { + "node": ">=4.0.0" + } + }, + "node_modules/mquery": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/mquery/-/mquery-5.0.0.tgz", + "integrity": "sha512-iQMncpmEK8R8ncT8HJGsGc9Dsp8xcgYMVSbs5jgnm1lFHTZqMJTUWTDx1LBO8+mK3tPNZWFLBghQEIOULSTHZg==", + "license": "MIT", + "dependencies": { + "debug": "4.x" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/mquery/node_modules/debug": { + "version": "4.3.7", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.7.tgz", + "integrity": "sha512-Er2nc/H7RrMXZBFCEim6TCmMk02Z8vLC2Rbi1KEBggpo0fS6l0S1nnapwmIi3yW/+GOJap1Krg4w0Hg80oCqgQ==", + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/mquery/node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "license": "MIT" + }, + "node_modules/ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==", + "license": "MIT" + }, + "node_modules/negotiator": { + "version": "0.6.3", + "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.3.tgz", + "integrity": "sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/nodemon": { + "version": "3.1.7", + "resolved": "https://registry.npmjs.org/nodemon/-/nodemon-3.1.7.tgz", + "integrity": "sha512-hLj7fuMow6f0lbB0cD14Lz2xNjwsyruH251Pk4t/yIitCFJbmY1myuLlHm/q06aST4jg6EgAh74PIBBrRqpVAQ==", + "license": "MIT", + "dependencies": { + "chokidar": "^3.5.2", + "debug": "^4", + "ignore-by-default": "^1.0.1", + "minimatch": "^3.1.2", + "pstree.remy": "^1.1.8", + "semver": "^7.5.3", + "simple-update-notifier": "^2.0.0", + "supports-color": "^5.5.0", + "touch": "^3.1.0", + "undefsafe": "^2.0.5" + }, + "bin": { + "nodemon": "bin/nodemon.js" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/nodemon" + } + }, + "node_modules/nodemon/node_modules/debug": { + "version": "4.3.7", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.7.tgz", + "integrity": "sha512-Er2nc/H7RrMXZBFCEim6TCmMk02Z8vLC2Rbi1KEBggpo0fS6l0S1nnapwmIi3yW/+GOJap1Krg4w0Hg80oCqgQ==", + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/nodemon/node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "license": "MIT" + }, + "node_modules/normalize-path": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz", + "integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/object-assign": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", + "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/object-inspect": { + "version": "1.13.3", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.3.tgz", + "integrity": "sha512-kDCGIbxkDSXE3euJZZXzc6to7fCrKHNI/hSRQnRuQ+BWjFNzZwiFF8fj/6o2t2G9/jTj8PSIYTfCLelLZEeRpA==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/on-finished": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz", + "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==", + "license": "MIT", + "dependencies": { + "ee-first": "1.1.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", + "dev": true, + "license": "ISC", + "dependencies": { + "wrappy": "1" + } + }, + "node_modules/package-json-from-dist": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/package-json-from-dist/-/package-json-from-dist-1.0.1.tgz", + "integrity": "sha512-UEZIS3/by4OC8vL3P2dTXRETpebLI2NiI5vIrjaD/5UtrkFX/tNbwjTSRAGC/+7CAo2pIcBaRgWmcBBHcsaCIw==", + "license": "BlueOak-1.0.0" + }, + "node_modules/parseurl": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", + "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/path-is-absolute": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", + "integrity": "sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/path-key": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", + "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/path-parse": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz", + "integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==", + "dev": true, + "license": "MIT" + }, + "node_modules/path-scurry": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-2.0.0.tgz", + "integrity": "sha512-ypGJsmGtdXUOeM5u93TyeIEfEhM6s+ljAhrk5vAvSx8uyY/02OvrZnA0YNGUrPXfpJMgI1ODd3nwz8Npx4O4cg==", + "license": "BlueOak-1.0.0", + "dependencies": { + "lru-cache": "^11.0.0", + "minipass": "^7.1.2" + }, + "engines": { + "node": "20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/path-to-regexp": { + "version": "0.1.10", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.10.tgz", + "integrity": "sha512-7lf7qcQidTku0Gu3YDPc8DJ1q7OOucfa/BSsIwjuh56VU7katFvuM8hULfkwB3Fns/rsVF7PwPKVw1sl5KQS9w==", + "license": "MIT" + }, + "node_modules/picomatch": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz", + "integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==", + "license": "MIT", + "engines": { + "node": ">=8.6" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/proxy-addr": { + "version": "2.0.7", + "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz", + "integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==", + "license": "MIT", + "dependencies": { + "forwarded": "0.2.0", + "ipaddr.js": "1.9.1" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/pstree.remy": { + "version": "1.1.8", + "resolved": "https://registry.npmjs.org/pstree.remy/-/pstree.remy-1.1.8.tgz", + "integrity": "sha512-77DZwxQmxKnu3aR542U+X8FypNzbfJ+C5XQDk3uWjWxn6151aIMGthWYRXTqT1E5oJvg+ljaa2OJi+VfvCOQ8w==", + "license": "MIT" + }, + "node_modules/punycode": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", + "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/qs": { + "version": "6.13.0", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.13.0.tgz", + "integrity": "sha512-+38qI9SOr8tfZ4QmJNplMUxqjbe7LKvvZgWdExBOmd+egZTtjLB67Gu0HRX3u/XOq7UU2Nx6nsjvS16Z9uwfpg==", + "license": "BSD-3-Clause", + "dependencies": { + "side-channel": "^1.0.6" + }, + "engines": { + "node": ">=0.6" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/range-parser": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz", + "integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/raw-body": { + "version": "2.5.2", + "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.5.2.tgz", + "integrity": "sha512-8zGqypfENjCIqGhgXToC8aB2r7YrBX+AQAfIPs/Mlk+BtPTztOvTS01NRW/3Eh60J+a48lt8qsCzirQ6loCVfA==", + "license": "MIT", + "dependencies": { + "bytes": "3.1.2", + "http-errors": "2.0.0", + "iconv-lite": "0.4.24", + "unpipe": "1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/readdirp": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.6.0.tgz", + "integrity": "sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==", + "license": "MIT", + "dependencies": { + "picomatch": "^2.2.1" + }, + "engines": { + "node": ">=8.10.0" + } + }, + "node_modules/resolve": { + "version": "1.22.8", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.8.tgz", + "integrity": "sha512-oKWePCxqpd6FlLvGV1VU0x7bkPmmCNolxzjMf4NczoDnQcIWrAF+cPtZn5i6n+RfD2d9i0tzpKnG6Yk168yIyw==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-core-module": "^2.13.0", + "path-parse": "^1.0.7", + "supports-preserve-symlinks-flag": "^1.0.0" + }, + "bin": { + "resolve": "bin/resolve" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/rimraf": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-6.0.1.tgz", + "integrity": "sha512-9dkvaxAsk/xNXSJzMgFqqMCuFgt2+KsOFek3TMLfo8NCPfWpBmqwyNn5Y+NX56QUYfCtsyhF3ayiboEoUmJk/A==", + "license": "ISC", + "dependencies": { + "glob": "^11.0.0", + "package-json-from-dist": "^1.0.0" + }, + "bin": { + "rimraf": "dist/esm/bin.mjs" + }, + "engines": { + "node": "20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "license": "MIT" + }, + "node_modules/semver": { + "version": "7.6.3", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.6.3.tgz", + "integrity": "sha512-oVekP1cKtI+CTDvHWYFUcMtsK/00wmAEfyqKfNdARm8u1wNVhSgaX7A8d4UuIlUI5e84iEwOhs7ZPYRmzU9U6A==", + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/send": { + "version": "0.19.0", + "resolved": "https://registry.npmjs.org/send/-/send-0.19.0.tgz", + "integrity": "sha512-dW41u5VfLXu8SJh5bwRmyYUbAoSB3c9uQh6L8h/KtsFREPWpbX1lrljJo186Jc4nmci/sGUZ9a0a0J2zgfq2hw==", + "license": "MIT", + "dependencies": { + "debug": "2.6.9", + "depd": "2.0.0", + "destroy": "1.2.0", + "encodeurl": "~1.0.2", + "escape-html": "~1.0.3", + "etag": "~1.8.1", + "fresh": "0.5.2", + "http-errors": "2.0.0", + "mime": "1.6.0", + "ms": "2.1.3", + "on-finished": "2.4.1", + "range-parser": "~1.2.1", + "statuses": "2.0.1" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/send/node_modules/encodeurl": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-1.0.2.tgz", + "integrity": "sha512-TPJXq8JqFaVYm2CWmPvnP2Iyo4ZSM7/QKcSmuMLDObfpH5fi7RUGmd/rTDf+rut/saiDiQEeVTNgAmJEdAOx0w==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/send/node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "license": "MIT" + }, + "node_modules/serve-static": { + "version": "1.16.2", + "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.16.2.tgz", + "integrity": "sha512-VqpjJZKadQB/PEbEwvFdO43Ax5dFBZ2UECszz8bQ7pi7wt//PWe1P6MN7eCnjsatYtBT6EuiClbjSWP2WrIoTw==", + "license": "MIT", + "dependencies": { + "encodeurl": "~2.0.0", + "escape-html": "~1.0.3", + "parseurl": "~1.3.3", + "send": "0.19.0" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/set-function-length": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/set-function-length/-/set-function-length-1.2.2.tgz", + "integrity": "sha512-pgRc4hJ4/sNjWCSS9AmnS40x3bNMDTknHgL5UaMBTMyJnU90EgWh1Rz+MC9eFu4BuN/UwZjKQuY/1v3rM7HMfg==", + "license": "MIT", + "dependencies": { + "define-data-property": "^1.1.4", + "es-errors": "^1.3.0", + "function-bind": "^1.1.2", + "get-intrinsic": "^1.2.4", + "gopd": "^1.0.1", + "has-property-descriptors": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/setprototypeof": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", + "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==", + "license": "ISC" + }, + "node_modules/shebang-command": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", + "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", + "license": "MIT", + "dependencies": { + "shebang-regex": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/shebang-regex": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", + "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/side-channel": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.0.6.tgz", + "integrity": "sha512-fDW/EZ6Q9RiO8eFG8Hj+7u/oW+XrPTIChwCOM2+th2A6OblDtYYIpve9m+KvI9Z4C9qSEXlaGR6bTEYHReuglA==", + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.7", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.4", + "object-inspect": "^1.13.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/sift": { + "version": "17.1.3", + "resolved": "https://registry.npmjs.org/sift/-/sift-17.1.3.tgz", + "integrity": "sha512-Rtlj66/b0ICeFzYTuNvX/EF1igRbbnGSvEyT79McoZa/DeGhMyC5pWKOEsZKnpkqtSeovd5FL/bjHWC3CIIvCQ==", + "license": "MIT" + }, + "node_modules/signal-exit": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz", + "integrity": "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==", + "license": "ISC", + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/simple-update-notifier": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/simple-update-notifier/-/simple-update-notifier-2.0.0.tgz", + "integrity": "sha512-a2B9Y0KlNXl9u/vsW6sTIu9vGEpfKu2wRV6l1H3XEas/0gUIzGzBoP/IouTcUQbm9JWZLH3COxyn03TYlFax6w==", + "license": "MIT", + "dependencies": { + "semver": "^7.5.3" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/source-map-support": { + "version": "0.5.21", + "resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.21.tgz", + "integrity": "sha512-uBHU3L3czsIyYXKX88fdrGovxdSCoTGDRZ6SYXtSRxLZUzHg5P/66Ht6uoUlHu9EZod+inXhKo3qQgwXUT/y1w==", + "dev": true, + "license": "MIT", + "dependencies": { + "buffer-from": "^1.0.0", + "source-map": "^0.6.0" + } + }, + "node_modules/sparse-bitfield": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/sparse-bitfield/-/sparse-bitfield-3.0.3.tgz", + "integrity": "sha512-kvzhi7vqKTfkh0PZU+2D2PIllw2ymqJKujUcyPMd9Y75Nv4nPbGJZXNhxsgdQab2BmlDct1YnfQCguEvHr7VsQ==", + "license": "MIT", + "dependencies": { + "memory-pager": "^1.0.2" + } + }, + "node_modules/statuses": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.1.tgz", + "integrity": "sha512-RwNA9Z/7PrK06rYLIzFMlaF+l73iwpzsqRIFgbMLbTcLD6cOao82TaWefPXQvB2fOC4AjuYSEndS7N/mTCbkdQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/string-width": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-5.1.2.tgz", + "integrity": "sha512-HnLOCR3vjcY8beoNLtcjZ5/nxn2afmME6lhrDrebokqMap+XbeW8n9TXpPDOqdGK5qcI3oT0GKTW6wC7EMiVqA==", + "license": "MIT", + "dependencies": { + "eastasianwidth": "^0.2.0", + "emoji-regex": "^9.2.2", + "strip-ansi": "^7.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/string-width-cjs": { + "name": "string-width", + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "license": "MIT", + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/string-width-cjs/node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/string-width-cjs/node_modules/emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", + "license": "MIT" + }, + "node_modules/string-width-cjs/node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "license": "MIT", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-ansi": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.1.0.tgz", + "integrity": "sha512-iq6eVVI64nQQTRYq2KtEg2d2uU7LElhTJwsH4YzIHZshxlgZms/wIc4VoDQTlG/IvVIrBKG06CrZnp0qv7hkcQ==", + "license": "MIT", + "dependencies": { + "ansi-regex": "^6.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/strip-ansi?sponsor=1" + } + }, + "node_modules/strip-ansi-cjs": { + "name": "strip-ansi", + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "license": "MIT", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-ansi-cjs/node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-bom": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-3.0.0.tgz", + "integrity": "sha512-vavAMRXOgBVNF6nyEEmL3DBK19iRpDcoIwW+swQ+CbGiu7lju6t+JklA1MHweoWtadgt4ISVUsXLyDq34ddcwA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/strip-json-comments": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-2.0.1.tgz", + "integrity": "sha512-4gB8na07fecVVkOI6Rs4e7T6NOTki5EmL7TUduTs6bu3EdnSycntVJ4re8kgZA+wx9IueI2Y11bfbgwtzuE0KQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/supports-color": { + "version": "5.5.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", + "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", + "license": "MIT", + "dependencies": { + "has-flag": "^3.0.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/supports-preserve-symlinks-flag": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz", + "integrity": "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/to-regex-range": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", + "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", + "license": "MIT", + "dependencies": { + "is-number": "^7.0.0" + }, + "engines": { + "node": ">=8.0" + } + }, + "node_modules/toidentifier": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz", + "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==", + "license": "MIT", + "engines": { + "node": ">=0.6" + } + }, + "node_modules/touch": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/touch/-/touch-3.1.1.tgz", + "integrity": "sha512-r0eojU4bI8MnHr8c5bNo7lJDdI2qXlWWJk6a9EAFG7vbhTjElYhBVS3/miuE0uOuoLdb8Mc/rVfsmm6eo5o9GA==", + "license": "ISC", + "bin": { + "nodetouch": "bin/nodetouch.js" + } + }, + "node_modules/tr46": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-4.1.1.tgz", + "integrity": "sha512-2lv/66T7e5yNyhAAC4NaKe5nVavzuGJQVVtRYLyQ2OI8tsJ61PMLlelehb0wi2Hx6+hT/OJUWZcw8MjlSRnxvw==", + "license": "MIT", + "dependencies": { + "punycode": "^2.3.0" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/tree-kill": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/tree-kill/-/tree-kill-1.2.2.tgz", + "integrity": "sha512-L0Orpi8qGpRG//Nd+H90vFB+3iHnue1zSSGmNOOCh1GLJ7rUKVwV2HvijphGQS2UmhUZewS9VgvxYIdgr+fG1A==", + "dev": true, + "license": "MIT", + "bin": { + "tree-kill": "cli.js" + } + }, + "node_modules/ts-node": { + "version": "10.9.2", + "resolved": "https://registry.npmjs.org/ts-node/-/ts-node-10.9.2.tgz", + "integrity": "sha512-f0FFpIdcHgn8zcPSbf1dRevwt047YMnaiJM3u2w2RewrB+fob/zePZcrOyQoLMMO7aBIddLcQIEK5dYjkLnGrQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@cspotcode/source-map-support": "^0.8.0", + "@tsconfig/node10": "^1.0.7", + "@tsconfig/node12": "^1.0.7", + "@tsconfig/node14": "^1.0.0", + "@tsconfig/node16": "^1.0.2", + "acorn": "^8.4.1", + "acorn-walk": "^8.1.1", + "arg": "^4.1.0", + "create-require": "^1.1.0", + "diff": "^4.0.1", + "make-error": "^1.1.1", + "v8-compile-cache-lib": "^3.0.1", + "yn": "3.1.1" + }, + "bin": { + "ts-node": "dist/bin.js", + "ts-node-cwd": "dist/bin-cwd.js", + "ts-node-esm": "dist/bin-esm.js", + "ts-node-script": "dist/bin-script.js", + "ts-node-transpile-only": "dist/bin-transpile.js", + "ts-script": "dist/bin-script-deprecated.js" + }, + "peerDependencies": { + "@swc/core": ">=1.2.50", + "@swc/wasm": ">=1.2.50", + "@types/node": "*", + "typescript": ">=2.7" + }, + "peerDependenciesMeta": { + "@swc/core": { + "optional": true + }, + "@swc/wasm": { + "optional": true + } + } + }, + "node_modules/ts-node-dev": { + "version": "1.1.8", + "resolved": "https://registry.npmjs.org/ts-node-dev/-/ts-node-dev-1.1.8.tgz", + "integrity": "sha512-Q/m3vEwzYwLZKmV6/0VlFxcZzVV/xcgOt+Tx/VjaaRHyiBcFlV0541yrT09QjzzCxlDZ34OzKjrFAynlmtflEg==", + "dev": true, + "license": "MIT", + "dependencies": { + "chokidar": "^3.5.1", + "dynamic-dedupe": "^0.3.0", + "minimist": "^1.2.5", + "mkdirp": "^1.0.4", + "resolve": "^1.0.0", + "rimraf": "^2.6.1", + "source-map-support": "^0.5.12", + "tree-kill": "^1.2.2", + "ts-node": "^9.0.0", + "tsconfig": "^7.0.0" + }, + "bin": { + "ts-node-dev": "lib/bin.js", + "tsnd": "lib/bin.js" + }, + "engines": { + "node": ">=0.8.0" + }, + "peerDependencies": { + "node-notifier": "*", + "typescript": "*" + }, + "peerDependenciesMeta": { + "node-notifier": { + "optional": true + } + } + }, + "node_modules/ts-node-dev/node_modules/glob": { + "version": "7.2.3", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz", + "integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==", + "deprecated": "Glob versions prior to v9 are no longer supported", + "dev": true, + "license": "ISC", + "dependencies": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.1.1", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + }, + "engines": { + "node": "*" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/ts-node-dev/node_modules/rimraf": { + "version": "2.7.1", + "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-2.7.1.tgz", + "integrity": "sha512-uWjbaKIK3T1OSVptzX7Nl6PvQ3qAGtKEtVRjRuazjfL3Bx5eI409VZSqgND+4UNnmzLVdPj9FqFJNPqBZFve4w==", + "deprecated": "Rimraf versions prior to v4 are no longer supported", + "dev": true, + "license": "ISC", + "dependencies": { + "glob": "^7.1.3" + }, + "bin": { + "rimraf": "bin.js" + } + }, + "node_modules/ts-node-dev/node_modules/ts-node": { + "version": "9.1.1", + "resolved": "https://registry.npmjs.org/ts-node/-/ts-node-9.1.1.tgz", + "integrity": "sha512-hPlt7ZACERQGf03M253ytLY3dHbGNGrAq9qIHWUY9XHYl1z7wYngSr3OQ5xmui8o2AaxsONxIzjafLUiWBo1Fg==", + "dev": true, + "license": "MIT", + "dependencies": { + "arg": "^4.1.0", + "create-require": "^1.1.0", + "diff": "^4.0.1", + "make-error": "^1.1.1", + "source-map-support": "^0.5.17", + "yn": "3.1.1" + }, + "bin": { + "ts-node": "dist/bin.js", + "ts-node-script": "dist/bin-script.js", + "ts-node-transpile-only": "dist/bin-transpile.js", + "ts-script": "dist/bin-script-deprecated.js" + }, + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "typescript": ">=2.7" + } + }, + "node_modules/tsconfig": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/tsconfig/-/tsconfig-7.0.0.tgz", + "integrity": "sha512-vZXmzPrL+EmC4T/4rVlT2jNVMWCi/O4DIiSj3UHg1OE5kCKbk4mfrXc6dZksLgRM/TZlKnousKH9bbTazUWRRw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/strip-bom": "^3.0.0", + "@types/strip-json-comments": "0.0.30", + "strip-bom": "^3.0.0", + "strip-json-comments": "^2.0.0" + } + }, + "node_modules/type-is": { + "version": "1.6.18", + "resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz", + "integrity": "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==", + "license": "MIT", + "dependencies": { + "media-typer": "0.3.0", + "mime-types": "~2.1.24" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/typescript": { + "version": "4.9.5", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-4.9.5.tgz", + "integrity": "sha512-1FXk9E2Hm+QzZQ7z+McJiHL4NW1F2EzMu9Nq9i3zAaGqibafqYwCVU6WyWAuyQRRzOlxou8xZSyXLEN8oKj24g==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=4.2.0" + } + }, + "node_modules/undefsafe": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/undefsafe/-/undefsafe-2.0.5.tgz", + "integrity": "sha512-WxONCrssBM8TSPRqN5EmsjVrsv4A8X12J4ArBiiayv3DyyG3ZlIg6yysuuSYdZsVz3TKcTg2fd//Ujd4CHV1iA==", + "license": "MIT" + }, + "node_modules/unpipe": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", + "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/utils-merge": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz", + "integrity": "sha512-pMZTvIkT1d+TFGvDOqodOclx0QWkkgi6Tdoa8gC8ffGAAqz9pzPTZWAybbsHHoED/ztMtkv/VoYTYyShUn81hA==", + "license": "MIT", + "engines": { + "node": ">= 0.4.0" + } + }, + "node_modules/v8-compile-cache-lib": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/v8-compile-cache-lib/-/v8-compile-cache-lib-3.0.1.tgz", + "integrity": "sha512-wa7YjyUGfNZngI/vtK0UHAN+lgDCxBPCylVXGp0zu59Fz5aiGtNXaq3DhIov063MorB+VfufLh3JlF2KdTK3xg==", + "dev": true, + "license": "MIT" + }, + "node_modules/validator": { + "version": "13.12.0", + "resolved": "https://registry.npmjs.org/validator/-/validator-13.12.0.tgz", + "integrity": "sha512-c1Q0mCiPlgdTVVVIJIrBuxNicYE+t/7oKeI9MWLj3fh/uq2Pxh/3eeWbVZ4OcGW1TUf53At0njHw5SMdA3tmMg==", + "license": "MIT", + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/vary": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", + "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/webidl-conversions": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-7.0.0.tgz", + "integrity": "sha512-VwddBukDzu71offAQR975unBIGqfKZpM+8ZX6ySk8nYhVoo5CYaZyzt3YBvYtRtO+aoGlqxPg/B87NGVZ/fu6g==", + "license": "BSD-2-Clause", + "engines": { + "node": ">=12" + } + }, + "node_modules/whatwg-url": { + "version": "13.0.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-13.0.0.tgz", + "integrity": "sha512-9WWbymnqj57+XEuqADHrCJ2eSXzn8WXIW/YSGaZtb2WKAInQ6CHfaUUcTyyver0p8BDg5StLQq8h1vtZuwmOig==", + "license": "MIT", + "dependencies": { + "tr46": "^4.1.1", + "webidl-conversions": "^7.0.0" + }, + "engines": { + "node": ">=16" + } + }, + "node_modules/which": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", + "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", + "license": "ISC", + "dependencies": { + "isexe": "^2.0.0" + }, + "bin": { + "node-which": "bin/node-which" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/wrap-ansi": { + "version": "8.1.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-8.1.0.tgz", + "integrity": "sha512-si7QWI6zUMq56bESFvagtmzMdGOtoxfR+Sez11Mobfc7tm+VkUckk9bW2UeffTGVUbOksxmSw0AA2gs8g71NCQ==", + "license": "MIT", + "dependencies": { + "ansi-styles": "^6.1.0", + "string-width": "^5.0.1", + "strip-ansi": "^7.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, + "node_modules/wrap-ansi-cjs": { + "name": "wrap-ansi", + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", + "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, + "node_modules/wrap-ansi-cjs/node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/wrap-ansi-cjs/node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "license": "MIT", + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/wrap-ansi-cjs/node_modules/emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", + "license": "MIT" + }, + "node_modules/wrap-ansi-cjs/node_modules/string-width": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "license": "MIT", + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/wrap-ansi-cjs/node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "license": "MIT", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", + "dev": true, + "license": "ISC" + }, + "node_modules/xtend": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz", + "integrity": "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.4" + } + }, + "node_modules/yn": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/yn/-/yn-3.1.1.tgz", + "integrity": "sha512-Ux4ygGWsu2c7isFWe8Yu1YluJmqVhxqK2cLXNQA5AcC3QfbGNpM7fu0Y8b/z16pXLnFxZYvWhd3fhBY9DLmC6Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + } + } +} diff --git a/backend/chatlog/package.json b/backend/chatlog/package.json new file mode 100644 index 0000000000..51e70a97cc --- /dev/null +++ b/backend/chatlog/package.json @@ -0,0 +1,26 @@ +{ + "name": "express-kafka-mongo", + "version": "1.0.0", + "main": "dist/app.js", + "scripts": { + "build": "rimraf dist && npx tsc", + "prestart": "npm run build", + "start": "npx tsc -w & nodemon dist/app.js" + }, + "dependencies": { + "@types/cors": "^2.8.17", + "@types/express": "^4.17.21", + "@types/express-validator": "^3.0.2", + "@types/mongoose": "^5.11.97", + "@types/node": "^22.8.5", + "cors": "^2.8.5", + "dotenv": "^16.4.5", + "express": "^4.21.0", + "express-validator": "^7.2.0", + "kafkajs": "^2.2.4", + "mongoose": "^8.7.2", + "nodemon": "^3.1.4", + "rimraf": "^6.0.1", + "typescript": "^5.6.2" + } +} \ No newline at end of file diff --git a/backend/chatlog/src/app.ts b/backend/chatlog/src/app.ts new file mode 100644 index 0000000000..ff25dab8e9 --- /dev/null +++ b/backend/chatlog/src/app.ts @@ -0,0 +1,29 @@ +import express, { Request, Response } from 'express'; +import mongoose from 'mongoose'; +import startConsumer from './kafkaConsumer'; + +const app = express(); +app.use(express.json()); +const PORT = process.env.PORT || "3008"; +const MONGODB_URI = process.env.MONGODB_URI || 'mongodb://localhost:27017/chatlogs'; + +// Connect to MongoDB +mongoose.connect(MONGODB_URI) +.then(() => { + console.log('Connected to MongoDB'); +}) +.catch((err) => { + console.error('MongoDB connection error:', err); +}); + +// Start Kafka Consumer +startConsumer().catch(console.error); + +// Basic route to verify server is running +app.get('/', (req: Request, res: Response) => { + res.send('ExpressJS Kafka-MongoDB Server is Running'); +}); + +app.listen(PORT, () => { + console.log(`Server is listening on port ${PORT}`); +}); diff --git a/backend/chatlog/src/kafkaConsumer.ts b/backend/chatlog/src/kafkaConsumer.ts new file mode 100644 index 0000000000..c832cae4a3 --- /dev/null +++ b/backend/chatlog/src/kafkaConsumer.ts @@ -0,0 +1,49 @@ +// // src/kafkaConsumer.ts +import { EachMessagePayload, Kafka } from 'kafkajs'; +import ChatLog, { IChatLog } from './models/ChatLog'; + +// // Kafka Configuration +const kafka = new Kafka({ + clientId: 'my-id', + brokers: ['kafka:9092'] +}); + +const consumer = kafka.consumer({ groupId: 'chat-logs-group' }); + +async function startConsumer(): Promise { + console.log("Starting Chatlog Kafka Consumer"); + + while (true) { + try { + await consumer.connect(); + console.log("Kafka consumer connected successfully"); + break; // Exit loop on successful connection + } catch (error) { + console.error("Failed to connect to Kafka, retrying in 5 seconds...", error); + await new Promise((resolve) => setTimeout(resolve, 5000)); // Wait 5 seconds before retrying + } + } + + await consumer.subscribe({ topic: 'CHATLOGS'}); + + await consumer.run({ + eachMessage: async ({ message }: EachMessagePayload) => { + const chatLog = JSON.parse(message.value?.toString() || '{}'); + console.log("Message consumed: " + chatLog) + + // Save message to MongoDB + const newChatLog: IChatLog = new ChatLog({ + senderId: chatLog.senderId, + collabId: chatLog.collabId, + recipientId: chatLog.recipientId, + message: chatLog.message, + timestamp: new Date(chatLog.timestamp * 1000) + }); + + await newChatLog.save(); + console.log('Chat log saved to MongoDB:', newChatLog); + }, + }); +} + +export default startConsumer; diff --git a/backend/chatlog/src/models/ChatLog.ts b/backend/chatlog/src/models/ChatLog.ts new file mode 100644 index 0000000000..6ea7f76340 --- /dev/null +++ b/backend/chatlog/src/models/ChatLog.ts @@ -0,0 +1,21 @@ +import mongoose, { Document, Schema } from 'mongoose'; + +interface IChatLog extends Document { + senderId: string; + message: string; + collabId: string; + recipientId: string; + timestamp: Date; +} + +const chatLogSchema = new Schema({ + senderId: { type: String, required: true }, + message: { type: String, required: true }, + timestamp: { type: Date, required: true }, + collabId: { type: String, required: true }, + recipientId: { type: String, required: true } +}); + +const ChatLogDB = mongoose.connection.useDb("Chatlogs"); +export default ChatLogDB.model('ChatLog', chatLogSchema, "chatlogs"); +export { IChatLog }; diff --git a/backend/chatlog/tsconfig.json b/backend/chatlog/tsconfig.json new file mode 100644 index 0000000000..a453635adb --- /dev/null +++ b/backend/chatlog/tsconfig.json @@ -0,0 +1,13 @@ +{ + "compilerOptions": { + "target": "ES6", + "module": "commonjs", + "outDir": "./dist", + "rootDir": "./src", + "strict": true, + "esModuleInterop": true, + "skipLibCheck": true + }, + "include": ["src"] + } + \ No newline at end of file diff --git a/backend/collaboration/.dockerignore b/backend/collaboration/.dockerignore new file mode 100644 index 0000000000..e99e0ccc55 --- /dev/null +++ b/backend/collaboration/.dockerignore @@ -0,0 +1,4 @@ +.env +node_modules/ +dist/ +sample.env \ No newline at end of file diff --git a/backend/collaboration/Dockerfile b/backend/collaboration/Dockerfile new file mode 100644 index 0000000000..c667f6ff8f --- /dev/null +++ b/backend/collaboration/Dockerfile @@ -0,0 +1,13 @@ +FROM node + +WORKDIR /app + +COPY package*.json ./ + +RUN npm install + +COPY . . + +EXPOSE 3001 + +CMD ["npm", "start"] \ No newline at end of file diff --git a/backend/collaboration/package-lock.json b/backend/collaboration/package-lock.json new file mode 100644 index 0000000000..b391087cc0 --- /dev/null +++ b/backend/collaboration/package-lock.json @@ -0,0 +1,3230 @@ +{ + "name": "collaboration", + "version": "1.0.0", + "lockfileVersion": 2, + "requires": true, + "packages": { + "": { + "name": "collaboration", + "version": "1.0.0", + "license": "ISC", + "dependencies": { + "@types/cors": "^2.8.17", + "@types/express": "^4.17.21", + "@types/express-validator": "^3.0.2", + "@types/mongoose": "^5.11.97", + "@types/node": "^22.8.5", + "cors": "^2.8.5", + "dotenv": "^16.4.5", + "express": "^4.21.0", + "express-validator": "^7.2.0", + "mongoose": "^8.7.2", + "nodemon": "^3.1.4", + "rimraf": "^6.0.1", + "typescript": "^5.6.2" + } + }, + "node_modules/@isaacs/cliui": { + "version": "8.0.2", + "resolved": "https://registry.npmjs.org/@isaacs/cliui/-/cliui-8.0.2.tgz", + "integrity": "sha512-O8jcjabXaleOG9DQ0+ARXWZBTfnP4WNAqzuiJK7ll44AmxGKv/J2M4TPjxjY3znBCfvBXFzucm1twdyFybFqEA==", + "dependencies": { + "string-width": "^5.1.2", + "string-width-cjs": "npm:string-width@^4.2.0", + "strip-ansi": "^7.0.1", + "strip-ansi-cjs": "npm:strip-ansi@^6.0.1", + "wrap-ansi": "^8.1.0", + "wrap-ansi-cjs": "npm:wrap-ansi@^7.0.0" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/@mongodb-js/saslprep": { + "version": "1.1.9", + "resolved": "https://registry.npmjs.org/@mongodb-js/saslprep/-/saslprep-1.1.9.tgz", + "integrity": "sha512-tVkljjeEaAhCqTzajSdgbQ6gE6f3oneVwa3iXR6csiEwXXOFsiC6Uh9iAjAhXPtqa/XMDHWjjeNH/77m/Yq2dw==", + "dependencies": { + "sparse-bitfield": "^3.0.3" + } + }, + "node_modules/@pkgjs/parseargs": { + "version": "0.11.0", + "resolved": "https://registry.npmjs.org/@pkgjs/parseargs/-/parseargs-0.11.0.tgz", + "integrity": "sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg==", + "optional": true, + "engines": { + "node": ">=14" + } + }, + "node_modules/@types/body-parser": { + "version": "1.19.5", + "resolved": "https://registry.npmjs.org/@types/body-parser/-/body-parser-1.19.5.tgz", + "integrity": "sha512-fB3Zu92ucau0iQ0JMCFQE7b/dv8Ot07NI3KaZIkIUNXq82k4eBAqUaneXfleGY9JWskeS9y+u0nXMyspcuQrCg==", + "dependencies": { + "@types/connect": "*", + "@types/node": "*" + } + }, + "node_modules/@types/connect": { + "version": "3.4.38", + "resolved": "https://registry.npmjs.org/@types/connect/-/connect-3.4.38.tgz", + "integrity": "sha512-K6uROf1LD88uDQqJCktA4yzL1YYAK6NgfsI0v/mTgyPKWsX1CnJ0XPSDhViejru1GcRkLWb8RlzFYJRqGUbaug==", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/cors": { + "version": "2.8.17", + "resolved": "https://registry.npmjs.org/@types/cors/-/cors-2.8.17.tgz", + "integrity": "sha512-8CGDvrBj1zgo2qE+oS3pOCyYNqCPryMWY2bGfwA0dcfopWGgxs+78df0Rs3rc9THP4JkOhLsAa+15VdpAqkcUA==", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/express": { + "version": "4.17.21", + "resolved": "https://registry.npmjs.org/@types/express/-/express-4.17.21.tgz", + "integrity": "sha512-ejlPM315qwLpaQlQDTjPdsUFSc6ZsP4AN6AlWnogPjQ7CVi7PYF3YVz+CY3jE2pwYf7E/7HlDAN0rV2GxTG0HQ==", + "dependencies": { + "@types/body-parser": "*", + "@types/express-serve-static-core": "^4.17.33", + "@types/qs": "*", + "@types/serve-static": "*" + } + }, + "node_modules/@types/express-serve-static-core": { + "version": "4.19.5", + "resolved": "https://registry.npmjs.org/@types/express-serve-static-core/-/express-serve-static-core-4.19.5.tgz", + "integrity": "sha512-y6W03tvrACO72aijJ5uF02FRq5cgDR9lUxddQ8vyF+GvmjJQqbzDcJngEjURc+ZsG31VI3hODNZJ2URj86pzmg==", + "dependencies": { + "@types/node": "*", + "@types/qs": "*", + "@types/range-parser": "*", + "@types/send": "*" + } + }, + "node_modules/@types/express-validator": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/@types/express-validator/-/express-validator-3.0.2.tgz", + "integrity": "sha512-dV+1u6absDDEIVe5jd5ID1XYvPPvOSvggMWh09VYM3TeBjAjBDtwJWyJg/5PnK7s8FRgbOtHgD6oX3N2MKWwDw==", + "deprecated": "This is a stub types definition. express-validator provides its own type definitions, so you do not need this installed.", + "dependencies": { + "express-validator": "*" + } + }, + "node_modules/@types/http-errors": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/@types/http-errors/-/http-errors-2.0.4.tgz", + "integrity": "sha512-D0CFMMtydbJAegzOyHjtiKPLlvnm3iTZyZRSZoLq2mRhDdmLfIWOCYPfQJ4cu2erKghU++QvjcUjp/5h7hESpA==" + }, + "node_modules/@types/mime": { + "version": "1.3.5", + "resolved": "https://registry.npmjs.org/@types/mime/-/mime-1.3.5.tgz", + "integrity": "sha512-/pyBZWSLD2n0dcHE3hq8s8ZvcETHtEuF+3E7XVt0Ig2nvsVQXdghHVcEkIWjy9A0wKfTn97a/PSDYohKIlnP/w==" + }, + "node_modules/@types/mongoose": { + "version": "5.11.97", + "resolved": "https://registry.npmjs.org/@types/mongoose/-/mongoose-5.11.97.tgz", + "integrity": "sha512-cqwOVYT3qXyLiGw7ueU2kX9noE8DPGRY6z8eUxudhXY8NZ7DMKYAxyZkLSevGfhCX3dO/AoX5/SO9lAzfjon0Q==", + "deprecated": "Mongoose publishes its own types, so you do not need to install this package.", + "dependencies": { + "mongoose": "*" + } + }, + "node_modules/@types/node": { + "version": "22.8.5", + "resolved": "https://registry.npmjs.org/@types/node/-/node-22.8.5.tgz", + "integrity": "sha512-5iYk6AMPtsMbkZqCO1UGF9W5L38twq11S2pYWkybGHH2ogPUvXWNlQqJBzuEZWKj/WRH+QTeiv6ySWqJtvIEgA==", + "license": "MIT", + "dependencies": { + "undici-types": "~6.19.8" + } + }, + "node_modules/@types/qs": { + "version": "6.9.16", + "resolved": "https://registry.npmjs.org/@types/qs/-/qs-6.9.16.tgz", + "integrity": "sha512-7i+zxXdPD0T4cKDuxCUXJ4wHcsJLwENa6Z3dCu8cfCK743OGy5Nu1RmAGqDPsoTDINVEcdXKRvR/zre+P2Ku1A==" + }, + "node_modules/@types/range-parser": { + "version": "1.2.7", + "resolved": "https://registry.npmjs.org/@types/range-parser/-/range-parser-1.2.7.tgz", + "integrity": "sha512-hKormJbkJqzQGhziax5PItDUTMAM9uE2XXQmM37dyd4hVM+5aVl7oVxMVUiVQn2oCQFN/LKCZdvSM0pFRqbSmQ==" + }, + "node_modules/@types/send": { + "version": "0.17.4", + "resolved": "https://registry.npmjs.org/@types/send/-/send-0.17.4.tgz", + "integrity": "sha512-x2EM6TJOybec7c52BX0ZspPodMsQUd5L6PRwOunVyVUhXiBSKf3AezDL8Dgvgt5o0UfKNfuA0eMLr2wLT4AiBA==", + "dependencies": { + "@types/mime": "^1", + "@types/node": "*" + } + }, + "node_modules/@types/serve-static": { + "version": "1.15.7", + "resolved": "https://registry.npmjs.org/@types/serve-static/-/serve-static-1.15.7.tgz", + "integrity": "sha512-W8Ym+h8nhuRwaKPaDw34QUkwsGi6Rc4yYqvKFo5rm2FUEhCFbzVWrxXUxuKK8TASjWsysJY0nsmNCGhCOIsrOw==", + "dependencies": { + "@types/http-errors": "*", + "@types/node": "*", + "@types/send": "*" + } + }, + "node_modules/@types/webidl-conversions": { + "version": "7.0.3", + "resolved": "https://registry.npmjs.org/@types/webidl-conversions/-/webidl-conversions-7.0.3.tgz", + "integrity": "sha512-CiJJvcRtIgzadHCYXw7dqEnMNRjhGZlYK05Mj9OyktqV8uVT8fD2BFOB7S1uwBE3Kj2Z+4UyPmFw/Ixgw/LAlA==" + }, + "node_modules/@types/whatwg-url": { + "version": "11.0.5", + "resolved": "https://registry.npmjs.org/@types/whatwg-url/-/whatwg-url-11.0.5.tgz", + "integrity": "sha512-coYR071JRaHa+xoEvvYqvnIHaVqaYrLPbsufM9BF63HkwI5Lgmy2QR8Q5K/lYDYo5AK82wOvSOS0UsLTpTG7uQ==", + "dependencies": { + "@types/webidl-conversions": "*" + } + }, + "node_modules/accepts": { + "version": "1.3.8", + "resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.8.tgz", + "integrity": "sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw==", + "dependencies": { + "mime-types": "~2.1.34", + "negotiator": "0.6.3" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/ansi-regex": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.1.0.tgz", + "integrity": "sha512-7HSX4QQb4CspciLpVFwyRe79O3xsIZDDLER21kERQ71oaPodF8jL725AgJMFAYbooIqolJoRLuM81SpeUkpkvA==", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-regex?sponsor=1" + } + }, + "node_modules/ansi-styles": { + "version": "6.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.1.tgz", + "integrity": "sha512-bN798gFfQX+viw3R7yrGWRqnrN2oRkEkUjjl4JNn4E8GxxbjtG3FbrEIIY3l8/hrwUwIeCZvi4QuOTP4MErVug==", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/anymatch": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.3.tgz", + "integrity": "sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw==", + "dependencies": { + "normalize-path": "^3.0.0", + "picomatch": "^2.0.4" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/array-flatten": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz", + "integrity": "sha512-PCVAQswWemu6UdxsDFFX/+gVeYqKAod3D3UVm91jHwynguOwAvYPhx8nNlM++NqRcK6CxxpUafjmhIdKiHibqg==" + }, + "node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==" + }, + "node_modules/binary-extensions": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.3.0.tgz", + "integrity": "sha512-Ceh+7ox5qe7LJuLHoY0feh3pHuUDHAcRUeyL2VYghZwfpkNIy/+8Ocg0a3UuSoYzavmylwuLWQOf3hl0jjMMIw==", + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/body-parser": { + "version": "1.20.3", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.3.tgz", + "integrity": "sha512-7rAxByjUMqQ3/bHJy7D6OGXvx/MMc4IqBn/X0fcM1QUcAItpZrBEYhWGem+tzXH90c+G01ypMcYJBO9Y30203g==", + "dependencies": { + "bytes": "3.1.2", + "content-type": "~1.0.5", + "debug": "2.6.9", + "depd": "2.0.0", + "destroy": "1.2.0", + "http-errors": "2.0.0", + "iconv-lite": "0.4.24", + "on-finished": "2.4.1", + "qs": "6.13.0", + "raw-body": "2.5.2", + "type-is": "~1.6.18", + "unpipe": "1.0.0" + }, + "engines": { + "node": ">= 0.8", + "npm": "1.2.8000 || >= 1.4.16" + } + }, + "node_modules/body-parser/node_modules/debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "dependencies": { + "ms": "2.0.0" + } + }, + "node_modules/body-parser/node_modules/ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==" + }, + "node_modules/brace-expansion": { + "version": "1.1.11", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", + "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "node_modules/braces": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.3.tgz", + "integrity": "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==", + "dependencies": { + "fill-range": "^7.1.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/bson": { + "version": "6.8.0", + "resolved": "https://registry.npmjs.org/bson/-/bson-6.8.0.tgz", + "integrity": "sha512-iOJg8pr7wq2tg/zSlCCHMi3hMm5JTOxLTagf3zxhcenHsFp+c6uOs6K7W5UE7A4QIJGtqh/ZovFNMP4mOPJynQ==", + "engines": { + "node": ">=16.20.1" + } + }, + "node_modules/bytes": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", + "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/call-bind": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.7.tgz", + "integrity": "sha512-GHTSNSYICQ7scH7sZ+M2rFopRoLh8t2bLSW6BbgrtLsahOIB5iyAVJf9GjWK3cYTDaMj4XdBpM1cA6pIS0Kv2w==", + "dependencies": { + "es-define-property": "^1.0.0", + "es-errors": "^1.3.0", + "function-bind": "^1.1.2", + "get-intrinsic": "^1.2.4", + "set-function-length": "^1.2.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/chokidar": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.6.0.tgz", + "integrity": "sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw==", + "dependencies": { + "anymatch": "~3.1.2", + "braces": "~3.0.2", + "glob-parent": "~5.1.2", + "is-binary-path": "~2.1.0", + "is-glob": "~4.0.1", + "normalize-path": "~3.0.0", + "readdirp": "~3.6.0" + }, + "engines": { + "node": ">= 8.10.0" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + }, + "optionalDependencies": { + "fsevents": "~2.3.2" + } + }, + "node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==" + }, + "node_modules/concat-map": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", + "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==" + }, + "node_modules/content-disposition": { + "version": "0.5.4", + "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.4.tgz", + "integrity": "sha512-FveZTNuGw04cxlAiWbzi6zTAL/lhehaWbTtgluJh4/E95DqMwTmha3KZN1aAWA8cFIhHzMZUvLevkw5Rqk+tSQ==", + "dependencies": { + "safe-buffer": "5.2.1" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/content-type": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz", + "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.6.0.tgz", + "integrity": "sha512-U71cyTamuh1CRNCfpGY6to28lxvNwPG4Guz/EVjgf3Jmzv0vlDp1atT9eS5dDjMYHucpHbWns6Lwf3BKz6svdw==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie-signature": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.6.tgz", + "integrity": "sha512-QADzlaHc8icV8I7vbaJXJwod9HWYp8uCqf1xa4OfNu1T7JVxQIrUgOWtHdNDtPiywmFbiS12VjotIXLrKM3orQ==" + }, + "node_modules/cors": { + "version": "2.8.5", + "resolved": "https://registry.npmjs.org/cors/-/cors-2.8.5.tgz", + "integrity": "sha512-KIHbLJqu73RGr/hnbrO9uBeixNGuvSQjul/jdFvS/KFSIH1hWVd1ng7zOHx+YrEfInLG7q4n6GHQ9cDtxv/P6g==", + "dependencies": { + "object-assign": "^4", + "vary": "^1" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/cross-spawn": { + "version": "7.0.3", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.3.tgz", + "integrity": "sha512-iRDPJKUPVEND7dHPO8rkbOnPpyDygcDFtWjpeWNCgy8WP2rXcxXL8TskReQl6OrB2G7+UJrags1q15Fudc7G6w==", + "dependencies": { + "path-key": "^3.1.0", + "shebang-command": "^2.0.0", + "which": "^2.0.1" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/debug": { + "version": "4.3.7", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.7.tgz", + "integrity": "sha512-Er2nc/H7RrMXZBFCEim6TCmMk02Z8vLC2Rbi1KEBggpo0fS6l0S1nnapwmIi3yW/+GOJap1Krg4w0Hg80oCqgQ==", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/define-data-property": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/define-data-property/-/define-data-property-1.1.4.tgz", + "integrity": "sha512-rBMvIzlpA8v6E+SJZoo++HAYqsLrkg7MSfIinMPFhmkorw7X+dOXVJQs+QT69zGkzMyfDnIMN2Wid1+NbL3T+A==", + "dependencies": { + "es-define-property": "^1.0.0", + "es-errors": "^1.3.0", + "gopd": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/depd": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", + "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/destroy": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/destroy/-/destroy-1.2.0.tgz", + "integrity": "sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg==", + "engines": { + "node": ">= 0.8", + "npm": "1.2.8000 || >= 1.4.16" + } + }, + "node_modules/dotenv": { + "version": "16.4.5", + "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.4.5.tgz", + "integrity": "sha512-ZmdL2rui+eB2YwhsWzjInR8LldtZHGDoQ1ugH85ppHKwpUHL7j7rN0Ti9NCnGiQbhaZ11FpR+7ao1dNsmduNUg==", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://dotenvx.com" + } + }, + "node_modules/eastasianwidth": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/eastasianwidth/-/eastasianwidth-0.2.0.tgz", + "integrity": "sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA==" + }, + "node_modules/ee-first": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", + "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==" + }, + "node_modules/emoji-regex": { + "version": "9.2.2", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-9.2.2.tgz", + "integrity": "sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg==" + }, + "node_modules/encodeurl": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz", + "integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/es-define-property": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.0.tgz", + "integrity": "sha512-jxayLKShrEqqzJ0eumQbVhTYQM27CfT1T35+gCgDFoL82JLsXqTJ76zv6A0YLOgEnLUMvLzsDsGIrl8NFpT2gQ==", + "dependencies": { + "get-intrinsic": "^1.2.4" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/escape-html": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", + "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==" + }, + "node_modules/etag": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", + "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/express": { + "version": "4.21.0", + "resolved": "https://registry.npmjs.org/express/-/express-4.21.0.tgz", + "integrity": "sha512-VqcNGcj/Id5ZT1LZ/cfihi3ttTn+NJmkli2eZADigjq29qTlWi/hAQ43t/VLPq8+UX06FCEx3ByOYet6ZFblng==", + "dependencies": { + "accepts": "~1.3.8", + "array-flatten": "1.1.1", + "body-parser": "1.20.3", + "content-disposition": "0.5.4", + "content-type": "~1.0.4", + "cookie": "0.6.0", + "cookie-signature": "1.0.6", + "debug": "2.6.9", + "depd": "2.0.0", + "encodeurl": "~2.0.0", + "escape-html": "~1.0.3", + "etag": "~1.8.1", + "finalhandler": "1.3.1", + "fresh": "0.5.2", + "http-errors": "2.0.0", + "merge-descriptors": "1.0.3", + "methods": "~1.1.2", + "on-finished": "2.4.1", + "parseurl": "~1.3.3", + "path-to-regexp": "0.1.10", + "proxy-addr": "~2.0.7", + "qs": "6.13.0", + "range-parser": "~1.2.1", + "safe-buffer": "5.2.1", + "send": "0.19.0", + "serve-static": "1.16.2", + "setprototypeof": "1.2.0", + "statuses": "2.0.1", + "type-is": "~1.6.18", + "utils-merge": "1.0.1", + "vary": "~1.1.2" + }, + "engines": { + "node": ">= 0.10.0" + } + }, + "node_modules/express-validator": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/express-validator/-/express-validator-7.2.0.tgz", + "integrity": "sha512-I2ByKD8panjtr8Y05l21Wph9xk7kk64UMyvJCl/fFM/3CTJq8isXYPLeKW/aZBCdb/LYNv63PwhY8khw8VWocA==", + "dependencies": { + "lodash": "^4.17.21", + "validator": "~13.12.0" + }, + "engines": { + "node": ">= 8.0.0" + } + }, + "node_modules/express/node_modules/debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "dependencies": { + "ms": "2.0.0" + } + }, + "node_modules/express/node_modules/ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==" + }, + "node_modules/fill-range": { + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz", + "integrity": "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==", + "dependencies": { + "to-regex-range": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/finalhandler": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.3.1.tgz", + "integrity": "sha512-6BN9trH7bp3qvnrRyzsBz+g3lZxTNZTbVO2EV1CS0WIcDbawYVdYvGflME/9QP0h0pYlCDBCTjYa9nZzMDpyxQ==", + "dependencies": { + "debug": "2.6.9", + "encodeurl": "~2.0.0", + "escape-html": "~1.0.3", + "on-finished": "2.4.1", + "parseurl": "~1.3.3", + "statuses": "2.0.1", + "unpipe": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/finalhandler/node_modules/debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "dependencies": { + "ms": "2.0.0" + } + }, + "node_modules/finalhandler/node_modules/ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==" + }, + "node_modules/foreground-child": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/foreground-child/-/foreground-child-3.3.0.tgz", + "integrity": "sha512-Ld2g8rrAyMYFXBhEqMz8ZAHBi4J4uS1i/CxGMDnjyFWddMXLVcDp051DZfu+t7+ab7Wv6SMqpWmyFIj5UbfFvg==", + "dependencies": { + "cross-spawn": "^7.0.0", + "signal-exit": "^4.0.1" + }, + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/forwarded": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz", + "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/fresh": { + "version": "0.5.2", + "resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz", + "integrity": "sha512-zJ2mQYM18rEFOudeV4GShTGIQ7RbzA7ozbU9I/XBpm7kqgMywgmylMwXHxZJmkVoYkna9d2pVXVXPdYTP9ej8Q==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "hasInstallScript": true, + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-intrinsic": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.2.4.tgz", + "integrity": "sha512-5uYhsJH8VJBTv7oslg4BznJYhDoRI6waYCxMmCdnTrcCrHA/fCFKoTFz2JKKE0HdDFUF7/oQuhzumXJK7paBRQ==", + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2", + "has-proto": "^1.0.1", + "has-symbols": "^1.0.3", + "hasown": "^2.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/glob": { + "version": "11.0.0", + "resolved": "https://registry.npmjs.org/glob/-/glob-11.0.0.tgz", + "integrity": "sha512-9UiX/Bl6J2yaBbxKoEBRm4Cipxgok8kQYcOPEhScPwebu2I0HoQOuYdIO6S3hLuWoZgpDpwQZMzTFxgpkyT76g==", + "dependencies": { + "foreground-child": "^3.1.0", + "jackspeak": "^4.0.1", + "minimatch": "^10.0.0", + "minipass": "^7.1.2", + "package-json-from-dist": "^1.0.0", + "path-scurry": "^2.0.0" + }, + "bin": { + "glob": "dist/esm/bin.mjs" + }, + "engines": { + "node": "20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/glob-parent": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz", + "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==", + "dependencies": { + "is-glob": "^4.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/glob/node_modules/brace-expansion": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.1.tgz", + "integrity": "sha512-XnAIvQ8eM+kC6aULx6wuQiwVsnzsi9d3WxzV3FpWTGA19F621kwdbsAcFKXgKUHZWsy+mY6iL1sHTxWEFCytDA==", + "dependencies": { + "balanced-match": "^1.0.0" + } + }, + "node_modules/glob/node_modules/minimatch": { + "version": "10.0.1", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.0.1.tgz", + "integrity": "sha512-ethXTt3SGGR+95gudmqJ1eNhRO7eGEGIgYA9vnPatK4/etz2MEVDno5GMCibdMTuBMyElzIlgxMna3K94XDIDQ==", + "dependencies": { + "brace-expansion": "^2.0.1" + }, + "engines": { + "node": "20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/gopd": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.0.1.tgz", + "integrity": "sha512-d65bNlIadxvpb/A2abVdlqKqV563juRnZ1Wtk6s1sIR8uNsXR70xqIzVqxVf1eTqDunwT2MkczEeaezCKTZhwA==", + "dependencies": { + "get-intrinsic": "^1.1.3" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-flag": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", + "integrity": "sha512-sKJf1+ceQBr4SMkvQnBDNDtf4TXpVhVGateu0t918bl30FnbE2m4vNLX+VWe/dpjlb+HugGYzW7uQXH98HPEYw==", + "engines": { + "node": ">=4" + } + }, + "node_modules/has-property-descriptors": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-property-descriptors/-/has-property-descriptors-1.0.2.tgz", + "integrity": "sha512-55JNKuIW+vq4Ke1BjOTjM2YctQIvCT7GFzHwmfZPGo5wnrgkid0YQtnAleFSqumZm4az3n2BS+erby5ipJdgrg==", + "dependencies": { + "es-define-property": "^1.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-proto": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/has-proto/-/has-proto-1.0.3.tgz", + "integrity": "sha512-SJ1amZAJUiZS+PhsVLf5tGydlaVB8EdFpaSO4gmiUKUOxk8qzn5AIy4ZeJUmh22znIdk/uMAUT2pl3FxzVUH+Q==", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-symbols": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.3.tgz", + "integrity": "sha512-l3LCuF6MgDNwTDKkdYGEihYjt5pRPbEg46rtlmnSPlUbgmB8LOIrKJbYYFBSbnPaJexMKtiPO8hmeRjRz2Td+A==", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/hasown": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz", + "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/http-errors": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.0.tgz", + "integrity": "sha512-FtwrG/euBzaEjYeRqOgly7G0qviiXoJWnvEH2Z1plBdXgbyjv34pHTSb9zoeHMyDy33+DWy5Wt9Wo+TURtOYSQ==", + "dependencies": { + "depd": "2.0.0", + "inherits": "2.0.4", + "setprototypeof": "1.2.0", + "statuses": "2.0.1", + "toidentifier": "1.0.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/iconv-lite": { + "version": "0.4.24", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz", + "integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/ignore-by-default": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/ignore-by-default/-/ignore-by-default-1.0.1.tgz", + "integrity": "sha512-Ius2VYcGNk7T90CppJqcIkS5ooHUZyIQK+ClZfMfMNFEF9VSE73Fq+906u/CWu92x4gzZMWOwfFYckPObzdEbA==" + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==" + }, + "node_modules/ipaddr.js": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz", + "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==", + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/is-binary-path": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/is-binary-path/-/is-binary-path-2.1.0.tgz", + "integrity": "sha512-ZMERYes6pDydyuGidse7OsHxtbI7WVeUEozgR/g7rd0xUimYNlvZRE/K2MgZTjWy725IfelLeVcEM97mmtRGXw==", + "dependencies": { + "binary-extensions": "^2.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/is-extglob": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", + "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-fullwidth-code-point": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", + "engines": { + "node": ">=8" + } + }, + "node_modules/is-glob": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", + "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", + "dependencies": { + "is-extglob": "^2.1.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-number": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", + "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", + "engines": { + "node": ">=0.12.0" + } + }, + "node_modules/isexe": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", + "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==" + }, + "node_modules/jackspeak": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/jackspeak/-/jackspeak-4.0.1.tgz", + "integrity": "sha512-cub8rahkh0Q/bw1+GxP7aeSe29hHHn2V4m29nnDlvCdlgU+3UGxkZp7Z53jLUdpX3jdTO0nJZUDl3xvbWc2Xog==", + "dependencies": { + "@isaacs/cliui": "^8.0.2" + }, + "engines": { + "node": "20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + }, + "optionalDependencies": { + "@pkgjs/parseargs": "^0.11.0" + } + }, + "node_modules/kareem": { + "version": "2.6.3", + "resolved": "https://registry.npmjs.org/kareem/-/kareem-2.6.3.tgz", + "integrity": "sha512-C3iHfuGUXK2u8/ipq9LfjFfXFxAZMQJJq7vLS45r3D9Y2xQ/m4S8zaR4zMLFWh9AsNPXmcFfUDhTEO8UIC/V6Q==", + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/lodash": { + "version": "4.17.21", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz", + "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==" + }, + "node_modules/lru-cache": { + "version": "11.0.1", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.0.1.tgz", + "integrity": "sha512-CgeuL5uom6j/ZVrg7G/+1IXqRY8JXX4Hghfy5YE0EhoYQWvndP1kufu58cmZLNIDKnRhZrXfdS9urVWx98AipQ==", + "engines": { + "node": "20 || >=22" + } + }, + "node_modules/media-typer": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz", + "integrity": "sha512-dq+qelQ9akHpcOl/gUVRTxVIOkAJ1wR3QAvb4RsVjS8oVoFjDGTc679wJYmUmknUF5HwMLOgb5O+a3KxfWapPQ==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/memory-pager": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/memory-pager/-/memory-pager-1.5.0.tgz", + "integrity": "sha512-ZS4Bp4r/Zoeq6+NLJpP+0Zzm0pR8whtGPf1XExKLJBAczGMnSi3It14OiNCStjQjM6NU1okjQGSxgEZN8eBYKg==" + }, + "node_modules/merge-descriptors": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.3.tgz", + "integrity": "sha512-gaNvAS7TZ897/rVaZ0nMtAyxNyi/pdbjbAwUpFQpN70GqnVfOiXpeUUMKRBmzXaSQ8DdTX4/0ms62r2K+hE6mQ==", + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/methods": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/methods/-/methods-1.1.2.tgz", + "integrity": "sha512-iclAHeNqNm68zFtnZ0e+1L2yUIdvzNoauKU4WBA3VvH/vPFieF7qfRlwUZU+DA9P9bPXIS90ulxoUoCH23sV2w==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/mime/-/mime-1.6.0.tgz", + "integrity": "sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg==", + "bin": { + "mime": "cli.js" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/mime-db": { + "version": "1.52.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", + "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "2.1.35", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", + "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", + "dependencies": { + "mime-db": "1.52.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/minimatch": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", + "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, + "node_modules/minipass": { + "version": "7.1.2", + "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.2.tgz", + "integrity": "sha512-qOOzS1cBTWYF4BH8fVePDBOO9iptMnGUEZwNc/cMWnTV2nVLZ7VoNWEPHkYczZA0pdoA7dl6e7FL659nX9S2aw==", + "engines": { + "node": ">=16 || 14 >=14.17" + } + }, + "node_modules/mongodb": { + "version": "6.9.0", + "resolved": "https://registry.npmjs.org/mongodb/-/mongodb-6.9.0.tgz", + "integrity": "sha512-UMopBVx1LmEUbW/QE0Hw18u583PEDVQmUmVzzBRH0o/xtE9DBRA5ZYLOjpLIa03i8FXjzvQECJcqoMvCXftTUA==", + "dependencies": { + "@mongodb-js/saslprep": "^1.1.5", + "bson": "^6.7.0", + "mongodb-connection-string-url": "^3.0.0" + }, + "engines": { + "node": ">=16.20.1" + }, + "peerDependencies": { + "@aws-sdk/credential-providers": "^3.188.0", + "@mongodb-js/zstd": "^1.1.0", + "gcp-metadata": "^5.2.0", + "kerberos": "^2.0.1", + "mongodb-client-encryption": ">=6.0.0 <7", + "snappy": "^7.2.2", + "socks": "^2.7.1" + }, + "peerDependenciesMeta": { + "@aws-sdk/credential-providers": { + "optional": true + }, + "@mongodb-js/zstd": { + "optional": true + }, + "gcp-metadata": { + "optional": true + }, + "kerberos": { + "optional": true + }, + "mongodb-client-encryption": { + "optional": true + }, + "snappy": { + "optional": true + }, + "socks": { + "optional": true + } + } + }, + "node_modules/mongodb-connection-string-url": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/mongodb-connection-string-url/-/mongodb-connection-string-url-3.0.1.tgz", + "integrity": "sha512-XqMGwRX0Lgn05TDB4PyG2h2kKO/FfWJyCzYQbIhXUxz7ETt0I/FqHjUeqj37irJ+Dl1ZtU82uYyj14u2XsZKfg==", + "dependencies": { + "@types/whatwg-url": "^11.0.2", + "whatwg-url": "^13.0.0" + } + }, + "node_modules/mongoose": { + "version": "8.7.2", + "resolved": "https://registry.npmjs.org/mongoose/-/mongoose-8.7.2.tgz", + "integrity": "sha512-Ok4VzMds9p5G3ZSUhmvBm1GdxanbzhS29jpSn02SPj+IXEVFnIdfwAlHHXWkyNscZKlcn8GuMi68FH++jo0flg==", + "dependencies": { + "bson": "^6.7.0", + "kareem": "2.6.3", + "mongodb": "6.9.0", + "mpath": "0.9.0", + "mquery": "5.0.0", + "ms": "2.1.3", + "sift": "17.1.3" + }, + "engines": { + "node": ">=16.20.1" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/mongoose" + } + }, + "node_modules/mpath": { + "version": "0.9.0", + "resolved": "https://registry.npmjs.org/mpath/-/mpath-0.9.0.tgz", + "integrity": "sha512-ikJRQTk8hw5DEoFVxHG1Gn9T/xcjtdnOKIU1JTmGjZZlg9LST2mBLmcX3/ICIbgJydT2GOc15RnNy5mHmzfSew==", + "engines": { + "node": ">=4.0.0" + } + }, + "node_modules/mquery": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/mquery/-/mquery-5.0.0.tgz", + "integrity": "sha512-iQMncpmEK8R8ncT8HJGsGc9Dsp8xcgYMVSbs5jgnm1lFHTZqMJTUWTDx1LBO8+mK3tPNZWFLBghQEIOULSTHZg==", + "dependencies": { + "debug": "4.x" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==" + }, + "node_modules/negotiator": { + "version": "0.6.3", + "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.3.tgz", + "integrity": "sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/nodemon": { + "version": "3.1.4", + "resolved": "https://registry.npmjs.org/nodemon/-/nodemon-3.1.4.tgz", + "integrity": "sha512-wjPBbFhtpJwmIeY2yP7QF+UKzPfltVGtfce1g/bB15/8vCGZj8uxD62b/b9M9/WVgme0NZudpownKN+c0plXlQ==", + "dependencies": { + "chokidar": "^3.5.2", + "debug": "^4", + "ignore-by-default": "^1.0.1", + "minimatch": "^3.1.2", + "pstree.remy": "^1.1.8", + "semver": "^7.5.3", + "simple-update-notifier": "^2.0.0", + "supports-color": "^5.5.0", + "touch": "^3.1.0", + "undefsafe": "^2.0.5" + }, + "bin": { + "nodemon": "bin/nodemon.js" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/nodemon" + } + }, + "node_modules/normalize-path": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz", + "integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/object-assign": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", + "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/object-inspect": { + "version": "1.13.2", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.2.tgz", + "integrity": "sha512-IRZSRuzJiynemAXPYtPe5BoI/RESNYR7TYm50MC5Mqbd3Jmw5y790sErYw3V6SryFJD64b74qQQs9wn5Bg/k3g==", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/on-finished": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz", + "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==", + "dependencies": { + "ee-first": "1.1.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/package-json-from-dist": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/package-json-from-dist/-/package-json-from-dist-1.0.0.tgz", + "integrity": "sha512-dATvCeZN/8wQsGywez1mzHtTlP22H8OEfPrVMLNr4/eGa+ijtLn/6M5f0dY8UKNrC2O9UCU6SSoG3qRKnt7STw==" + }, + "node_modules/parseurl": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", + "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/path-key": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", + "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", + "engines": { + "node": ">=8" + } + }, + "node_modules/path-scurry": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-2.0.0.tgz", + "integrity": "sha512-ypGJsmGtdXUOeM5u93TyeIEfEhM6s+ljAhrk5vAvSx8uyY/02OvrZnA0YNGUrPXfpJMgI1ODd3nwz8Npx4O4cg==", + "dependencies": { + "lru-cache": "^11.0.0", + "minipass": "^7.1.2" + }, + "engines": { + "node": "20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/path-to-regexp": { + "version": "0.1.10", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.10.tgz", + "integrity": "sha512-7lf7qcQidTku0Gu3YDPc8DJ1q7OOucfa/BSsIwjuh56VU7katFvuM8hULfkwB3Fns/rsVF7PwPKVw1sl5KQS9w==" + }, + "node_modules/picomatch": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz", + "integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==", + "engines": { + "node": ">=8.6" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/proxy-addr": { + "version": "2.0.7", + "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz", + "integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==", + "dependencies": { + "forwarded": "0.2.0", + "ipaddr.js": "1.9.1" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/pstree.remy": { + "version": "1.1.8", + "resolved": "https://registry.npmjs.org/pstree.remy/-/pstree.remy-1.1.8.tgz", + "integrity": "sha512-77DZwxQmxKnu3aR542U+X8FypNzbfJ+C5XQDk3uWjWxn6151aIMGthWYRXTqT1E5oJvg+ljaa2OJi+VfvCOQ8w==" + }, + "node_modules/punycode": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", + "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==", + "engines": { + "node": ">=6" + } + }, + "node_modules/qs": { + "version": "6.13.0", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.13.0.tgz", + "integrity": "sha512-+38qI9SOr8tfZ4QmJNplMUxqjbe7LKvvZgWdExBOmd+egZTtjLB67Gu0HRX3u/XOq7UU2Nx6nsjvS16Z9uwfpg==", + "dependencies": { + "side-channel": "^1.0.6" + }, + "engines": { + "node": ">=0.6" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/range-parser": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz", + "integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/raw-body": { + "version": "2.5.2", + "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.5.2.tgz", + "integrity": "sha512-8zGqypfENjCIqGhgXToC8aB2r7YrBX+AQAfIPs/Mlk+BtPTztOvTS01NRW/3Eh60J+a48lt8qsCzirQ6loCVfA==", + "dependencies": { + "bytes": "3.1.2", + "http-errors": "2.0.0", + "iconv-lite": "0.4.24", + "unpipe": "1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/readdirp": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.6.0.tgz", + "integrity": "sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==", + "dependencies": { + "picomatch": "^2.2.1" + }, + "engines": { + "node": ">=8.10.0" + } + }, + "node_modules/rimraf": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-6.0.1.tgz", + "integrity": "sha512-9dkvaxAsk/xNXSJzMgFqqMCuFgt2+KsOFek3TMLfo8NCPfWpBmqwyNn5Y+NX56QUYfCtsyhF3ayiboEoUmJk/A==", + "dependencies": { + "glob": "^11.0.0", + "package-json-from-dist": "^1.0.0" + }, + "bin": { + "rimraf": "dist/esm/bin.mjs" + }, + "engines": { + "node": "20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] + }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==" + }, + "node_modules/semver": { + "version": "7.6.3", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.6.3.tgz", + "integrity": "sha512-oVekP1cKtI+CTDvHWYFUcMtsK/00wmAEfyqKfNdARm8u1wNVhSgaX7A8d4UuIlUI5e84iEwOhs7ZPYRmzU9U6A==", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/send": { + "version": "0.19.0", + "resolved": "https://registry.npmjs.org/send/-/send-0.19.0.tgz", + "integrity": "sha512-dW41u5VfLXu8SJh5bwRmyYUbAoSB3c9uQh6L8h/KtsFREPWpbX1lrljJo186Jc4nmci/sGUZ9a0a0J2zgfq2hw==", + "dependencies": { + "debug": "2.6.9", + "depd": "2.0.0", + "destroy": "1.2.0", + "encodeurl": "~1.0.2", + "escape-html": "~1.0.3", + "etag": "~1.8.1", + "fresh": "0.5.2", + "http-errors": "2.0.0", + "mime": "1.6.0", + "ms": "2.1.3", + "on-finished": "2.4.1", + "range-parser": "~1.2.1", + "statuses": "2.0.1" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/send/node_modules/debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "dependencies": { + "ms": "2.0.0" + } + }, + "node_modules/send/node_modules/debug/node_modules/ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==" + }, + "node_modules/send/node_modules/encodeurl": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-1.0.2.tgz", + "integrity": "sha512-TPJXq8JqFaVYm2CWmPvnP2Iyo4ZSM7/QKcSmuMLDObfpH5fi7RUGmd/rTDf+rut/saiDiQEeVTNgAmJEdAOx0w==", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/serve-static": { + "version": "1.16.2", + "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.16.2.tgz", + "integrity": "sha512-VqpjJZKadQB/PEbEwvFdO43Ax5dFBZ2UECszz8bQ7pi7wt//PWe1P6MN7eCnjsatYtBT6EuiClbjSWP2WrIoTw==", + "dependencies": { + "encodeurl": "~2.0.0", + "escape-html": "~1.0.3", + "parseurl": "~1.3.3", + "send": "0.19.0" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/set-function-length": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/set-function-length/-/set-function-length-1.2.2.tgz", + "integrity": "sha512-pgRc4hJ4/sNjWCSS9AmnS40x3bNMDTknHgL5UaMBTMyJnU90EgWh1Rz+MC9eFu4BuN/UwZjKQuY/1v3rM7HMfg==", + "dependencies": { + "define-data-property": "^1.1.4", + "es-errors": "^1.3.0", + "function-bind": "^1.1.2", + "get-intrinsic": "^1.2.4", + "gopd": "^1.0.1", + "has-property-descriptors": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/setprototypeof": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", + "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==" + }, + "node_modules/shebang-command": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", + "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", + "dependencies": { + "shebang-regex": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/shebang-regex": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", + "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", + "engines": { + "node": ">=8" + } + }, + "node_modules/side-channel": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.0.6.tgz", + "integrity": "sha512-fDW/EZ6Q9RiO8eFG8Hj+7u/oW+XrPTIChwCOM2+th2A6OblDtYYIpve9m+KvI9Z4C9qSEXlaGR6bTEYHReuglA==", + "dependencies": { + "call-bind": "^1.0.7", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.4", + "object-inspect": "^1.13.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/sift": { + "version": "17.1.3", + "resolved": "https://registry.npmjs.org/sift/-/sift-17.1.3.tgz", + "integrity": "sha512-Rtlj66/b0ICeFzYTuNvX/EF1igRbbnGSvEyT79McoZa/DeGhMyC5pWKOEsZKnpkqtSeovd5FL/bjHWC3CIIvCQ==" + }, + "node_modules/signal-exit": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz", + "integrity": "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==", + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/simple-update-notifier": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/simple-update-notifier/-/simple-update-notifier-2.0.0.tgz", + "integrity": "sha512-a2B9Y0KlNXl9u/vsW6sTIu9vGEpfKu2wRV6l1H3XEas/0gUIzGzBoP/IouTcUQbm9JWZLH3COxyn03TYlFax6w==", + "dependencies": { + "semver": "^7.5.3" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/sparse-bitfield": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/sparse-bitfield/-/sparse-bitfield-3.0.3.tgz", + "integrity": "sha512-kvzhi7vqKTfkh0PZU+2D2PIllw2ymqJKujUcyPMd9Y75Nv4nPbGJZXNhxsgdQab2BmlDct1YnfQCguEvHr7VsQ==", + "dependencies": { + "memory-pager": "^1.0.2" + } + }, + "node_modules/statuses": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.1.tgz", + "integrity": "sha512-RwNA9Z/7PrK06rYLIzFMlaF+l73iwpzsqRIFgbMLbTcLD6cOao82TaWefPXQvB2fOC4AjuYSEndS7N/mTCbkdQ==", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/string-width": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-5.1.2.tgz", + "integrity": "sha512-HnLOCR3vjcY8beoNLtcjZ5/nxn2afmME6lhrDrebokqMap+XbeW8n9TXpPDOqdGK5qcI3oT0GKTW6wC7EMiVqA==", + "dependencies": { + "eastasianwidth": "^0.2.0", + "emoji-regex": "^9.2.2", + "strip-ansi": "^7.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/string-width-cjs": { + "name": "string-width", + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/string-width-cjs/node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "engines": { + "node": ">=8" + } + }, + "node_modules/string-width-cjs/node_modules/emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==" + }, + "node_modules/string-width-cjs/node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-ansi": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.1.0.tgz", + "integrity": "sha512-iq6eVVI64nQQTRYq2KtEg2d2uU7LElhTJwsH4YzIHZshxlgZms/wIc4VoDQTlG/IvVIrBKG06CrZnp0qv7hkcQ==", + "dependencies": { + "ansi-regex": "^6.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/strip-ansi?sponsor=1" + } + }, + "node_modules/strip-ansi-cjs": { + "name": "strip-ansi", + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-ansi-cjs/node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "engines": { + "node": ">=8" + } + }, + "node_modules/supports-color": { + "version": "5.5.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", + "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", + "dependencies": { + "has-flag": "^3.0.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/to-regex-range": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", + "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", + "dependencies": { + "is-number": "^7.0.0" + }, + "engines": { + "node": ">=8.0" + } + }, + "node_modules/toidentifier": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz", + "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==", + "engines": { + "node": ">=0.6" + } + }, + "node_modules/touch": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/touch/-/touch-3.1.1.tgz", + "integrity": "sha512-r0eojU4bI8MnHr8c5bNo7lJDdI2qXlWWJk6a9EAFG7vbhTjElYhBVS3/miuE0uOuoLdb8Mc/rVfsmm6eo5o9GA==", + "bin": { + "nodetouch": "bin/nodetouch.js" + } + }, + "node_modules/tr46": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-4.1.1.tgz", + "integrity": "sha512-2lv/66T7e5yNyhAAC4NaKe5nVavzuGJQVVtRYLyQ2OI8tsJ61PMLlelehb0wi2Hx6+hT/OJUWZcw8MjlSRnxvw==", + "dependencies": { + "punycode": "^2.3.0" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/type-is": { + "version": "1.6.18", + "resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz", + "integrity": "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==", + "dependencies": { + "media-typer": "0.3.0", + "mime-types": "~2.1.24" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/typescript": { + "version": "5.6.2", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.6.2.tgz", + "integrity": "sha512-NW8ByodCSNCwZeghjN3o+JX5OFH0Ojg6sadjEKY4huZ52TqbJTJnDo5+Tw98lSy63NZvi4n+ez5m2u5d4PkZyw==", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/undefsafe": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/undefsafe/-/undefsafe-2.0.5.tgz", + "integrity": "sha512-WxONCrssBM8TSPRqN5EmsjVrsv4A8X12J4ArBiiayv3DyyG3ZlIg6yysuuSYdZsVz3TKcTg2fd//Ujd4CHV1iA==" + }, + "node_modules/undici-types": { + "version": "6.19.8", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.19.8.tgz", + "integrity": "sha512-ve2KP6f/JnbPBFyobGHuerC9g1FYGn/F8n1LWTwNxCEzd6IfqTwUQcNXgEtmmQ6DlRrC1hrSrBnCZPokRrDHjw==" + }, + "node_modules/unpipe": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", + "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/utils-merge": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz", + "integrity": "sha512-pMZTvIkT1d+TFGvDOqodOclx0QWkkgi6Tdoa8gC8ffGAAqz9pzPTZWAybbsHHoED/ztMtkv/VoYTYyShUn81hA==", + "engines": { + "node": ">= 0.4.0" + } + }, + "node_modules/validator": { + "version": "13.12.0", + "resolved": "https://registry.npmjs.org/validator/-/validator-13.12.0.tgz", + "integrity": "sha512-c1Q0mCiPlgdTVVVIJIrBuxNicYE+t/7oKeI9MWLj3fh/uq2Pxh/3eeWbVZ4OcGW1TUf53At0njHw5SMdA3tmMg==", + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/vary": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", + "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/webidl-conversions": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-7.0.0.tgz", + "integrity": "sha512-VwddBukDzu71offAQR975unBIGqfKZpM+8ZX6ySk8nYhVoo5CYaZyzt3YBvYtRtO+aoGlqxPg/B87NGVZ/fu6g==", + "engines": { + "node": ">=12" + } + }, + "node_modules/whatwg-url": { + "version": "13.0.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-13.0.0.tgz", + "integrity": "sha512-9WWbymnqj57+XEuqADHrCJ2eSXzn8WXIW/YSGaZtb2WKAInQ6CHfaUUcTyyver0p8BDg5StLQq8h1vtZuwmOig==", + "dependencies": { + "tr46": "^4.1.1", + "webidl-conversions": "^7.0.0" + }, + "engines": { + "node": ">=16" + } + }, + "node_modules/which": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", + "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", + "dependencies": { + "isexe": "^2.0.0" + }, + "bin": { + "node-which": "bin/node-which" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/wrap-ansi": { + "version": "8.1.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-8.1.0.tgz", + "integrity": "sha512-si7QWI6zUMq56bESFvagtmzMdGOtoxfR+Sez11Mobfc7tm+VkUckk9bW2UeffTGVUbOksxmSw0AA2gs8g71NCQ==", + "dependencies": { + "ansi-styles": "^6.1.0", + "string-width": "^5.0.1", + "strip-ansi": "^7.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, + "node_modules/wrap-ansi-cjs": { + "name": "wrap-ansi", + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", + "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", + "dependencies": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, + "node_modules/wrap-ansi-cjs/node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "engines": { + "node": ">=8" + } + }, + "node_modules/wrap-ansi-cjs/node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/wrap-ansi-cjs/node_modules/emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==" + }, + "node_modules/wrap-ansi-cjs/node_modules/string-width": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/wrap-ansi-cjs/node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + } + }, + "dependencies": { + "@isaacs/cliui": { + "version": "8.0.2", + "resolved": "https://registry.npmjs.org/@isaacs/cliui/-/cliui-8.0.2.tgz", + "integrity": "sha512-O8jcjabXaleOG9DQ0+ARXWZBTfnP4WNAqzuiJK7ll44AmxGKv/J2M4TPjxjY3znBCfvBXFzucm1twdyFybFqEA==", + "requires": { + "string-width": "^5.1.2", + "string-width-cjs": "npm:string-width@^4.2.0", + "strip-ansi": "^7.0.1", + "strip-ansi-cjs": "npm:strip-ansi@^6.0.1", + "wrap-ansi": "^8.1.0", + "wrap-ansi-cjs": "npm:wrap-ansi@^7.0.0" + } + }, + "@mongodb-js/saslprep": { + "version": "1.1.9", + "resolved": "https://registry.npmjs.org/@mongodb-js/saslprep/-/saslprep-1.1.9.tgz", + "integrity": "sha512-tVkljjeEaAhCqTzajSdgbQ6gE6f3oneVwa3iXR6csiEwXXOFsiC6Uh9iAjAhXPtqa/XMDHWjjeNH/77m/Yq2dw==", + "requires": { + "sparse-bitfield": "^3.0.3" + } + }, + "@pkgjs/parseargs": { + "version": "0.11.0", + "resolved": "https://registry.npmjs.org/@pkgjs/parseargs/-/parseargs-0.11.0.tgz", + "integrity": "sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg==", + "optional": true + }, + "@types/body-parser": { + "version": "1.19.5", + "resolved": "https://registry.npmjs.org/@types/body-parser/-/body-parser-1.19.5.tgz", + "integrity": "sha512-fB3Zu92ucau0iQ0JMCFQE7b/dv8Ot07NI3KaZIkIUNXq82k4eBAqUaneXfleGY9JWskeS9y+u0nXMyspcuQrCg==", + "requires": { + "@types/connect": "*", + "@types/node": "*" + } + }, + "@types/connect": { + "version": "3.4.38", + "resolved": "https://registry.npmjs.org/@types/connect/-/connect-3.4.38.tgz", + "integrity": "sha512-K6uROf1LD88uDQqJCktA4yzL1YYAK6NgfsI0v/mTgyPKWsX1CnJ0XPSDhViejru1GcRkLWb8RlzFYJRqGUbaug==", + "requires": { + "@types/node": "*" + } + }, + "@types/cors": { + "version": "2.8.17", + "resolved": "https://registry.npmjs.org/@types/cors/-/cors-2.8.17.tgz", + "integrity": "sha512-8CGDvrBj1zgo2qE+oS3pOCyYNqCPryMWY2bGfwA0dcfopWGgxs+78df0Rs3rc9THP4JkOhLsAa+15VdpAqkcUA==", + "requires": { + "@types/node": "*" + } + }, + "@types/express": { + "version": "4.17.21", + "resolved": "https://registry.npmjs.org/@types/express/-/express-4.17.21.tgz", + "integrity": "sha512-ejlPM315qwLpaQlQDTjPdsUFSc6ZsP4AN6AlWnogPjQ7CVi7PYF3YVz+CY3jE2pwYf7E/7HlDAN0rV2GxTG0HQ==", + "requires": { + "@types/body-parser": "*", + "@types/express-serve-static-core": "^4.17.33", + "@types/qs": "*", + "@types/serve-static": "*" + } + }, + "@types/express-serve-static-core": { + "version": "4.19.5", + "resolved": "https://registry.npmjs.org/@types/express-serve-static-core/-/express-serve-static-core-4.19.5.tgz", + "integrity": "sha512-y6W03tvrACO72aijJ5uF02FRq5cgDR9lUxddQ8vyF+GvmjJQqbzDcJngEjURc+ZsG31VI3hODNZJ2URj86pzmg==", + "requires": { + "@types/node": "*", + "@types/qs": "*", + "@types/range-parser": "*", + "@types/send": "*" + } + }, + "@types/express-validator": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/@types/express-validator/-/express-validator-3.0.2.tgz", + "integrity": "sha512-dV+1u6absDDEIVe5jd5ID1XYvPPvOSvggMWh09VYM3TeBjAjBDtwJWyJg/5PnK7s8FRgbOtHgD6oX3N2MKWwDw==", + "requires": { + "express-validator": "*" + } + }, + "@types/http-errors": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/@types/http-errors/-/http-errors-2.0.4.tgz", + "integrity": "sha512-D0CFMMtydbJAegzOyHjtiKPLlvnm3iTZyZRSZoLq2mRhDdmLfIWOCYPfQJ4cu2erKghU++QvjcUjp/5h7hESpA==" + }, + "@types/mime": { + "version": "1.3.5", + "resolved": "https://registry.npmjs.org/@types/mime/-/mime-1.3.5.tgz", + "integrity": "sha512-/pyBZWSLD2n0dcHE3hq8s8ZvcETHtEuF+3E7XVt0Ig2nvsVQXdghHVcEkIWjy9A0wKfTn97a/PSDYohKIlnP/w==" + }, + "@types/mongoose": { + "version": "5.11.97", + "resolved": "https://registry.npmjs.org/@types/mongoose/-/mongoose-5.11.97.tgz", + "integrity": "sha512-cqwOVYT3qXyLiGw7ueU2kX9noE8DPGRY6z8eUxudhXY8NZ7DMKYAxyZkLSevGfhCX3dO/AoX5/SO9lAzfjon0Q==", + "requires": { + "mongoose": "*" + } + }, + "@types/node": { + "version": "22.8.5", + "resolved": "https://registry.npmjs.org/@types/node/-/node-22.8.5.tgz", + "integrity": "sha512-5iYk6AMPtsMbkZqCO1UGF9W5L38twq11S2pYWkybGHH2ogPUvXWNlQqJBzuEZWKj/WRH+QTeiv6ySWqJtvIEgA==", + "requires": { + "undici-types": "~6.19.8" + } + }, + "@types/qs": { + "version": "6.9.16", + "resolved": "https://registry.npmjs.org/@types/qs/-/qs-6.9.16.tgz", + "integrity": "sha512-7i+zxXdPD0T4cKDuxCUXJ4wHcsJLwENa6Z3dCu8cfCK743OGy5Nu1RmAGqDPsoTDINVEcdXKRvR/zre+P2Ku1A==" + }, + "@types/range-parser": { + "version": "1.2.7", + "resolved": "https://registry.npmjs.org/@types/range-parser/-/range-parser-1.2.7.tgz", + "integrity": "sha512-hKormJbkJqzQGhziax5PItDUTMAM9uE2XXQmM37dyd4hVM+5aVl7oVxMVUiVQn2oCQFN/LKCZdvSM0pFRqbSmQ==" + }, + "@types/send": { + "version": "0.17.4", + "resolved": "https://registry.npmjs.org/@types/send/-/send-0.17.4.tgz", + "integrity": "sha512-x2EM6TJOybec7c52BX0ZspPodMsQUd5L6PRwOunVyVUhXiBSKf3AezDL8Dgvgt5o0UfKNfuA0eMLr2wLT4AiBA==", + "requires": { + "@types/mime": "^1", + "@types/node": "*" + } + }, + "@types/serve-static": { + "version": "1.15.7", + "resolved": "https://registry.npmjs.org/@types/serve-static/-/serve-static-1.15.7.tgz", + "integrity": "sha512-W8Ym+h8nhuRwaKPaDw34QUkwsGi6Rc4yYqvKFo5rm2FUEhCFbzVWrxXUxuKK8TASjWsysJY0nsmNCGhCOIsrOw==", + "requires": { + "@types/http-errors": "*", + "@types/node": "*", + "@types/send": "*" + } + }, + "@types/webidl-conversions": { + "version": "7.0.3", + "resolved": "https://registry.npmjs.org/@types/webidl-conversions/-/webidl-conversions-7.0.3.tgz", + "integrity": "sha512-CiJJvcRtIgzadHCYXw7dqEnMNRjhGZlYK05Mj9OyktqV8uVT8fD2BFOB7S1uwBE3Kj2Z+4UyPmFw/Ixgw/LAlA==" + }, + "@types/whatwg-url": { + "version": "11.0.5", + "resolved": "https://registry.npmjs.org/@types/whatwg-url/-/whatwg-url-11.0.5.tgz", + "integrity": "sha512-coYR071JRaHa+xoEvvYqvnIHaVqaYrLPbsufM9BF63HkwI5Lgmy2QR8Q5K/lYDYo5AK82wOvSOS0UsLTpTG7uQ==", + "requires": { + "@types/webidl-conversions": "*" + } + }, + "accepts": { + "version": "1.3.8", + "resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.8.tgz", + "integrity": "sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw==", + "requires": { + "mime-types": "~2.1.34", + "negotiator": "0.6.3" + } + }, + "ansi-regex": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.1.0.tgz", + "integrity": "sha512-7HSX4QQb4CspciLpVFwyRe79O3xsIZDDLER21kERQ71oaPodF8jL725AgJMFAYbooIqolJoRLuM81SpeUkpkvA==" + }, + "ansi-styles": { + "version": "6.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.1.tgz", + "integrity": "sha512-bN798gFfQX+viw3R7yrGWRqnrN2oRkEkUjjl4JNn4E8GxxbjtG3FbrEIIY3l8/hrwUwIeCZvi4QuOTP4MErVug==" + }, + "anymatch": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.3.tgz", + "integrity": "sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw==", + "requires": { + "normalize-path": "^3.0.0", + "picomatch": "^2.0.4" + } + }, + "array-flatten": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz", + "integrity": "sha512-PCVAQswWemu6UdxsDFFX/+gVeYqKAod3D3UVm91jHwynguOwAvYPhx8nNlM++NqRcK6CxxpUafjmhIdKiHibqg==" + }, + "balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==" + }, + "binary-extensions": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.3.0.tgz", + "integrity": "sha512-Ceh+7ox5qe7LJuLHoY0feh3pHuUDHAcRUeyL2VYghZwfpkNIy/+8Ocg0a3UuSoYzavmylwuLWQOf3hl0jjMMIw==" + }, + "body-parser": { + "version": "1.20.3", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.3.tgz", + "integrity": "sha512-7rAxByjUMqQ3/bHJy7D6OGXvx/MMc4IqBn/X0fcM1QUcAItpZrBEYhWGem+tzXH90c+G01ypMcYJBO9Y30203g==", + "requires": { + "bytes": "3.1.2", + "content-type": "~1.0.5", + "debug": "2.6.9", + "depd": "2.0.0", + "destroy": "1.2.0", + "http-errors": "2.0.0", + "iconv-lite": "0.4.24", + "on-finished": "2.4.1", + "qs": "6.13.0", + "raw-body": "2.5.2", + "type-is": "~1.6.18", + "unpipe": "1.0.0" + }, + "dependencies": { + "debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "requires": { + "ms": "2.0.0" + } + }, + "ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==" + } + } + }, + "brace-expansion": { + "version": "1.1.11", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", + "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", + "requires": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "braces": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.3.tgz", + "integrity": "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==", + "requires": { + "fill-range": "^7.1.1" + } + }, + "bson": { + "version": "6.8.0", + "resolved": "https://registry.npmjs.org/bson/-/bson-6.8.0.tgz", + "integrity": "sha512-iOJg8pr7wq2tg/zSlCCHMi3hMm5JTOxLTagf3zxhcenHsFp+c6uOs6K7W5UE7A4QIJGtqh/ZovFNMP4mOPJynQ==" + }, + "bytes": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", + "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==" + }, + "call-bind": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.7.tgz", + "integrity": "sha512-GHTSNSYICQ7scH7sZ+M2rFopRoLh8t2bLSW6BbgrtLsahOIB5iyAVJf9GjWK3cYTDaMj4XdBpM1cA6pIS0Kv2w==", + "requires": { + "es-define-property": "^1.0.0", + "es-errors": "^1.3.0", + "function-bind": "^1.1.2", + "get-intrinsic": "^1.2.4", + "set-function-length": "^1.2.1" + } + }, + "chokidar": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.6.0.tgz", + "integrity": "sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw==", + "requires": { + "anymatch": "~3.1.2", + "braces": "~3.0.2", + "fsevents": "~2.3.2", + "glob-parent": "~5.1.2", + "is-binary-path": "~2.1.0", + "is-glob": "~4.0.1", + "normalize-path": "~3.0.0", + "readdirp": "~3.6.0" + } + }, + "color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "requires": { + "color-name": "~1.1.4" + } + }, + "color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==" + }, + "concat-map": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", + "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==" + }, + "content-disposition": { + "version": "0.5.4", + "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.4.tgz", + "integrity": "sha512-FveZTNuGw04cxlAiWbzi6zTAL/lhehaWbTtgluJh4/E95DqMwTmha3KZN1aAWA8cFIhHzMZUvLevkw5Rqk+tSQ==", + "requires": { + "safe-buffer": "5.2.1" + } + }, + "content-type": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz", + "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==" + }, + "cookie": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.6.0.tgz", + "integrity": "sha512-U71cyTamuh1CRNCfpGY6to28lxvNwPG4Guz/EVjgf3Jmzv0vlDp1atT9eS5dDjMYHucpHbWns6Lwf3BKz6svdw==" + }, + "cookie-signature": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.6.tgz", + "integrity": "sha512-QADzlaHc8icV8I7vbaJXJwod9HWYp8uCqf1xa4OfNu1T7JVxQIrUgOWtHdNDtPiywmFbiS12VjotIXLrKM3orQ==" + }, + "cors": { + "version": "2.8.5", + "resolved": "https://registry.npmjs.org/cors/-/cors-2.8.5.tgz", + "integrity": "sha512-KIHbLJqu73RGr/hnbrO9uBeixNGuvSQjul/jdFvS/KFSIH1hWVd1ng7zOHx+YrEfInLG7q4n6GHQ9cDtxv/P6g==", + "requires": { + "object-assign": "^4", + "vary": "^1" + } + }, + "cross-spawn": { + "version": "7.0.3", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.3.tgz", + "integrity": "sha512-iRDPJKUPVEND7dHPO8rkbOnPpyDygcDFtWjpeWNCgy8WP2rXcxXL8TskReQl6OrB2G7+UJrags1q15Fudc7G6w==", + "requires": { + "path-key": "^3.1.0", + "shebang-command": "^2.0.0", + "which": "^2.0.1" + } + }, + "debug": { + "version": "4.3.7", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.7.tgz", + "integrity": "sha512-Er2nc/H7RrMXZBFCEim6TCmMk02Z8vLC2Rbi1KEBggpo0fS6l0S1nnapwmIi3yW/+GOJap1Krg4w0Hg80oCqgQ==", + "requires": { + "ms": "^2.1.3" + } + }, + "define-data-property": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/define-data-property/-/define-data-property-1.1.4.tgz", + "integrity": "sha512-rBMvIzlpA8v6E+SJZoo++HAYqsLrkg7MSfIinMPFhmkorw7X+dOXVJQs+QT69zGkzMyfDnIMN2Wid1+NbL3T+A==", + "requires": { + "es-define-property": "^1.0.0", + "es-errors": "^1.3.0", + "gopd": "^1.0.1" + } + }, + "depd": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", + "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==" + }, + "destroy": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/destroy/-/destroy-1.2.0.tgz", + "integrity": "sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg==" + }, + "dotenv": { + "version": "16.4.5", + "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.4.5.tgz", + "integrity": "sha512-ZmdL2rui+eB2YwhsWzjInR8LldtZHGDoQ1ugH85ppHKwpUHL7j7rN0Ti9NCnGiQbhaZ11FpR+7ao1dNsmduNUg==" + }, + "eastasianwidth": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/eastasianwidth/-/eastasianwidth-0.2.0.tgz", + "integrity": "sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA==" + }, + "ee-first": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", + "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==" + }, + "emoji-regex": { + "version": "9.2.2", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-9.2.2.tgz", + "integrity": "sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg==" + }, + "encodeurl": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz", + "integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==" + }, + "es-define-property": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.0.tgz", + "integrity": "sha512-jxayLKShrEqqzJ0eumQbVhTYQM27CfT1T35+gCgDFoL82JLsXqTJ76zv6A0YLOgEnLUMvLzsDsGIrl8NFpT2gQ==", + "requires": { + "get-intrinsic": "^1.2.4" + } + }, + "es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==" + }, + "escape-html": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", + "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==" + }, + "etag": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", + "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==" + }, + "express": { + "version": "4.21.0", + "resolved": "https://registry.npmjs.org/express/-/express-4.21.0.tgz", + "integrity": "sha512-VqcNGcj/Id5ZT1LZ/cfihi3ttTn+NJmkli2eZADigjq29qTlWi/hAQ43t/VLPq8+UX06FCEx3ByOYet6ZFblng==", + "requires": { + "accepts": "~1.3.8", + "array-flatten": "1.1.1", + "body-parser": "1.20.3", + "content-disposition": "0.5.4", + "content-type": "~1.0.4", + "cookie": "0.6.0", + "cookie-signature": "1.0.6", + "debug": "2.6.9", + "depd": "2.0.0", + "encodeurl": "~2.0.0", + "escape-html": "~1.0.3", + "etag": "~1.8.1", + "finalhandler": "1.3.1", + "fresh": "0.5.2", + "http-errors": "2.0.0", + "merge-descriptors": "1.0.3", + "methods": "~1.1.2", + "on-finished": "2.4.1", + "parseurl": "~1.3.3", + "path-to-regexp": "0.1.10", + "proxy-addr": "~2.0.7", + "qs": "6.13.0", + "range-parser": "~1.2.1", + "safe-buffer": "5.2.1", + "send": "0.19.0", + "serve-static": "1.16.2", + "setprototypeof": "1.2.0", + "statuses": "2.0.1", + "type-is": "~1.6.18", + "utils-merge": "1.0.1", + "vary": "~1.1.2" + }, + "dependencies": { + "debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "requires": { + "ms": "2.0.0" + } + }, + "ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==" + } + } + }, + "express-validator": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/express-validator/-/express-validator-7.2.0.tgz", + "integrity": "sha512-I2ByKD8panjtr8Y05l21Wph9xk7kk64UMyvJCl/fFM/3CTJq8isXYPLeKW/aZBCdb/LYNv63PwhY8khw8VWocA==", + "requires": { + "lodash": "^4.17.21", + "validator": "~13.12.0" + } + }, + "fill-range": { + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz", + "integrity": "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==", + "requires": { + "to-regex-range": "^5.0.1" + } + }, + "finalhandler": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.3.1.tgz", + "integrity": "sha512-6BN9trH7bp3qvnrRyzsBz+g3lZxTNZTbVO2EV1CS0WIcDbawYVdYvGflME/9QP0h0pYlCDBCTjYa9nZzMDpyxQ==", + "requires": { + "debug": "2.6.9", + "encodeurl": "~2.0.0", + "escape-html": "~1.0.3", + "on-finished": "2.4.1", + "parseurl": "~1.3.3", + "statuses": "2.0.1", + "unpipe": "~1.0.0" + }, + "dependencies": { + "debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "requires": { + "ms": "2.0.0" + } + }, + "ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==" + } + } + }, + "foreground-child": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/foreground-child/-/foreground-child-3.3.0.tgz", + "integrity": "sha512-Ld2g8rrAyMYFXBhEqMz8ZAHBi4J4uS1i/CxGMDnjyFWddMXLVcDp051DZfu+t7+ab7Wv6SMqpWmyFIj5UbfFvg==", + "requires": { + "cross-spawn": "^7.0.0", + "signal-exit": "^4.0.1" + } + }, + "forwarded": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz", + "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==" + }, + "fresh": { + "version": "0.5.2", + "resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz", + "integrity": "sha512-zJ2mQYM18rEFOudeV4GShTGIQ7RbzA7ozbU9I/XBpm7kqgMywgmylMwXHxZJmkVoYkna9d2pVXVXPdYTP9ej8Q==" + }, + "fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "optional": true + }, + "function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==" + }, + "get-intrinsic": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.2.4.tgz", + "integrity": "sha512-5uYhsJH8VJBTv7oslg4BznJYhDoRI6waYCxMmCdnTrcCrHA/fCFKoTFz2JKKE0HdDFUF7/oQuhzumXJK7paBRQ==", + "requires": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2", + "has-proto": "^1.0.1", + "has-symbols": "^1.0.3", + "hasown": "^2.0.0" + } + }, + "glob": { + "version": "11.0.0", + "resolved": "https://registry.npmjs.org/glob/-/glob-11.0.0.tgz", + "integrity": "sha512-9UiX/Bl6J2yaBbxKoEBRm4Cipxgok8kQYcOPEhScPwebu2I0HoQOuYdIO6S3hLuWoZgpDpwQZMzTFxgpkyT76g==", + "requires": { + "foreground-child": "^3.1.0", + "jackspeak": "^4.0.1", + "minimatch": "^10.0.0", + "minipass": "^7.1.2", + "package-json-from-dist": "^1.0.0", + "path-scurry": "^2.0.0" + }, + "dependencies": { + "brace-expansion": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.1.tgz", + "integrity": "sha512-XnAIvQ8eM+kC6aULx6wuQiwVsnzsi9d3WxzV3FpWTGA19F621kwdbsAcFKXgKUHZWsy+mY6iL1sHTxWEFCytDA==", + "requires": { + "balanced-match": "^1.0.0" + } + }, + "minimatch": { + "version": "10.0.1", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.0.1.tgz", + "integrity": "sha512-ethXTt3SGGR+95gudmqJ1eNhRO7eGEGIgYA9vnPatK4/etz2MEVDno5GMCibdMTuBMyElzIlgxMna3K94XDIDQ==", + "requires": { + "brace-expansion": "^2.0.1" + } + } + } + }, + "glob-parent": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz", + "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==", + "requires": { + "is-glob": "^4.0.1" + } + }, + "gopd": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.0.1.tgz", + "integrity": "sha512-d65bNlIadxvpb/A2abVdlqKqV563juRnZ1Wtk6s1sIR8uNsXR70xqIzVqxVf1eTqDunwT2MkczEeaezCKTZhwA==", + "requires": { + "get-intrinsic": "^1.1.3" + } + }, + "has-flag": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", + "integrity": "sha512-sKJf1+ceQBr4SMkvQnBDNDtf4TXpVhVGateu0t918bl30FnbE2m4vNLX+VWe/dpjlb+HugGYzW7uQXH98HPEYw==" + }, + "has-property-descriptors": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-property-descriptors/-/has-property-descriptors-1.0.2.tgz", + "integrity": "sha512-55JNKuIW+vq4Ke1BjOTjM2YctQIvCT7GFzHwmfZPGo5wnrgkid0YQtnAleFSqumZm4az3n2BS+erby5ipJdgrg==", + "requires": { + "es-define-property": "^1.0.0" + } + }, + "has-proto": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/has-proto/-/has-proto-1.0.3.tgz", + "integrity": "sha512-SJ1amZAJUiZS+PhsVLf5tGydlaVB8EdFpaSO4gmiUKUOxk8qzn5AIy4ZeJUmh22znIdk/uMAUT2pl3FxzVUH+Q==" + }, + "has-symbols": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.3.tgz", + "integrity": "sha512-l3LCuF6MgDNwTDKkdYGEihYjt5pRPbEg46rtlmnSPlUbgmB8LOIrKJbYYFBSbnPaJexMKtiPO8hmeRjRz2Td+A==" + }, + "hasown": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz", + "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==", + "requires": { + "function-bind": "^1.1.2" + } + }, + "http-errors": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.0.tgz", + "integrity": "sha512-FtwrG/euBzaEjYeRqOgly7G0qviiXoJWnvEH2Z1plBdXgbyjv34pHTSb9zoeHMyDy33+DWy5Wt9Wo+TURtOYSQ==", + "requires": { + "depd": "2.0.0", + "inherits": "2.0.4", + "setprototypeof": "1.2.0", + "statuses": "2.0.1", + "toidentifier": "1.0.1" + } + }, + "iconv-lite": { + "version": "0.4.24", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz", + "integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==", + "requires": { + "safer-buffer": ">= 2.1.2 < 3" + } + }, + "ignore-by-default": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/ignore-by-default/-/ignore-by-default-1.0.1.tgz", + "integrity": "sha512-Ius2VYcGNk7T90CppJqcIkS5ooHUZyIQK+ClZfMfMNFEF9VSE73Fq+906u/CWu92x4gzZMWOwfFYckPObzdEbA==" + }, + "inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==" + }, + "ipaddr.js": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz", + "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==" + }, + "is-binary-path": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/is-binary-path/-/is-binary-path-2.1.0.tgz", + "integrity": "sha512-ZMERYes6pDydyuGidse7OsHxtbI7WVeUEozgR/g7rd0xUimYNlvZRE/K2MgZTjWy725IfelLeVcEM97mmtRGXw==", + "requires": { + "binary-extensions": "^2.0.0" + } + }, + "is-extglob": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", + "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==" + }, + "is-fullwidth-code-point": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==" + }, + "is-glob": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", + "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", + "requires": { + "is-extglob": "^2.1.1" + } + }, + "is-number": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", + "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==" + }, + "isexe": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", + "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==" + }, + "jackspeak": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/jackspeak/-/jackspeak-4.0.1.tgz", + "integrity": "sha512-cub8rahkh0Q/bw1+GxP7aeSe29hHHn2V4m29nnDlvCdlgU+3UGxkZp7Z53jLUdpX3jdTO0nJZUDl3xvbWc2Xog==", + "requires": { + "@isaacs/cliui": "^8.0.2", + "@pkgjs/parseargs": "^0.11.0" + } + }, + "kareem": { + "version": "2.6.3", + "resolved": "https://registry.npmjs.org/kareem/-/kareem-2.6.3.tgz", + "integrity": "sha512-C3iHfuGUXK2u8/ipq9LfjFfXFxAZMQJJq7vLS45r3D9Y2xQ/m4S8zaR4zMLFWh9AsNPXmcFfUDhTEO8UIC/V6Q==" + }, + "lodash": { + "version": "4.17.21", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz", + "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==" + }, + "lru-cache": { + "version": "11.0.1", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.0.1.tgz", + "integrity": "sha512-CgeuL5uom6j/ZVrg7G/+1IXqRY8JXX4Hghfy5YE0EhoYQWvndP1kufu58cmZLNIDKnRhZrXfdS9urVWx98AipQ==" + }, + "media-typer": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz", + "integrity": "sha512-dq+qelQ9akHpcOl/gUVRTxVIOkAJ1wR3QAvb4RsVjS8oVoFjDGTc679wJYmUmknUF5HwMLOgb5O+a3KxfWapPQ==" + }, + "memory-pager": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/memory-pager/-/memory-pager-1.5.0.tgz", + "integrity": "sha512-ZS4Bp4r/Zoeq6+NLJpP+0Zzm0pR8whtGPf1XExKLJBAczGMnSi3It14OiNCStjQjM6NU1okjQGSxgEZN8eBYKg==" + }, + "merge-descriptors": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.3.tgz", + "integrity": "sha512-gaNvAS7TZ897/rVaZ0nMtAyxNyi/pdbjbAwUpFQpN70GqnVfOiXpeUUMKRBmzXaSQ8DdTX4/0ms62r2K+hE6mQ==" + }, + "methods": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/methods/-/methods-1.1.2.tgz", + "integrity": "sha512-iclAHeNqNm68zFtnZ0e+1L2yUIdvzNoauKU4WBA3VvH/vPFieF7qfRlwUZU+DA9P9bPXIS90ulxoUoCH23sV2w==" + }, + "mime": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/mime/-/mime-1.6.0.tgz", + "integrity": "sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg==" + }, + "mime-db": { + "version": "1.52.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", + "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==" + }, + "mime-types": { + "version": "2.1.35", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", + "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", + "requires": { + "mime-db": "1.52.0" + } + }, + "minimatch": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", + "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", + "requires": { + "brace-expansion": "^1.1.7" + } + }, + "minipass": { + "version": "7.1.2", + "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.2.tgz", + "integrity": "sha512-qOOzS1cBTWYF4BH8fVePDBOO9iptMnGUEZwNc/cMWnTV2nVLZ7VoNWEPHkYczZA0pdoA7dl6e7FL659nX9S2aw==" + }, + "mongodb": { + "version": "6.9.0", + "resolved": "https://registry.npmjs.org/mongodb/-/mongodb-6.9.0.tgz", + "integrity": "sha512-UMopBVx1LmEUbW/QE0Hw18u583PEDVQmUmVzzBRH0o/xtE9DBRA5ZYLOjpLIa03i8FXjzvQECJcqoMvCXftTUA==", + "requires": { + "@mongodb-js/saslprep": "^1.1.5", + "bson": "^6.7.0", + "mongodb-connection-string-url": "^3.0.0" + } + }, + "mongodb-connection-string-url": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/mongodb-connection-string-url/-/mongodb-connection-string-url-3.0.1.tgz", + "integrity": "sha512-XqMGwRX0Lgn05TDB4PyG2h2kKO/FfWJyCzYQbIhXUxz7ETt0I/FqHjUeqj37irJ+Dl1ZtU82uYyj14u2XsZKfg==", + "requires": { + "@types/whatwg-url": "^11.0.2", + "whatwg-url": "^13.0.0" + } + }, + "mongoose": { + "version": "8.7.2", + "resolved": "https://registry.npmjs.org/mongoose/-/mongoose-8.7.2.tgz", + "integrity": "sha512-Ok4VzMds9p5G3ZSUhmvBm1GdxanbzhS29jpSn02SPj+IXEVFnIdfwAlHHXWkyNscZKlcn8GuMi68FH++jo0flg==", + "requires": { + "bson": "^6.7.0", + "kareem": "2.6.3", + "mongodb": "6.9.0", + "mpath": "0.9.0", + "mquery": "5.0.0", + "ms": "2.1.3", + "sift": "17.1.3" + } + }, + "mpath": { + "version": "0.9.0", + "resolved": "https://registry.npmjs.org/mpath/-/mpath-0.9.0.tgz", + "integrity": "sha512-ikJRQTk8hw5DEoFVxHG1Gn9T/xcjtdnOKIU1JTmGjZZlg9LST2mBLmcX3/ICIbgJydT2GOc15RnNy5mHmzfSew==" + }, + "mquery": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/mquery/-/mquery-5.0.0.tgz", + "integrity": "sha512-iQMncpmEK8R8ncT8HJGsGc9Dsp8xcgYMVSbs5jgnm1lFHTZqMJTUWTDx1LBO8+mK3tPNZWFLBghQEIOULSTHZg==", + "requires": { + "debug": "4.x" + } + }, + "ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==" + }, + "negotiator": { + "version": "0.6.3", + "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.3.tgz", + "integrity": "sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg==" + }, + "nodemon": { + "version": "3.1.4", + "resolved": "https://registry.npmjs.org/nodemon/-/nodemon-3.1.4.tgz", + "integrity": "sha512-wjPBbFhtpJwmIeY2yP7QF+UKzPfltVGtfce1g/bB15/8vCGZj8uxD62b/b9M9/WVgme0NZudpownKN+c0plXlQ==", + "requires": { + "chokidar": "^3.5.2", + "debug": "^4", + "ignore-by-default": "^1.0.1", + "minimatch": "^3.1.2", + "pstree.remy": "^1.1.8", + "semver": "^7.5.3", + "simple-update-notifier": "^2.0.0", + "supports-color": "^5.5.0", + "touch": "^3.1.0", + "undefsafe": "^2.0.5" + } + }, + "normalize-path": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz", + "integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==" + }, + "object-assign": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", + "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==" + }, + "object-inspect": { + "version": "1.13.2", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.2.tgz", + "integrity": "sha512-IRZSRuzJiynemAXPYtPe5BoI/RESNYR7TYm50MC5Mqbd3Jmw5y790sErYw3V6SryFJD64b74qQQs9wn5Bg/k3g==" + }, + "on-finished": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz", + "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==", + "requires": { + "ee-first": "1.1.1" + } + }, + "package-json-from-dist": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/package-json-from-dist/-/package-json-from-dist-1.0.0.tgz", + "integrity": "sha512-dATvCeZN/8wQsGywez1mzHtTlP22H8OEfPrVMLNr4/eGa+ijtLn/6M5f0dY8UKNrC2O9UCU6SSoG3qRKnt7STw==" + }, + "parseurl": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", + "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==" + }, + "path-key": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", + "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==" + }, + "path-scurry": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-2.0.0.tgz", + "integrity": "sha512-ypGJsmGtdXUOeM5u93TyeIEfEhM6s+ljAhrk5vAvSx8uyY/02OvrZnA0YNGUrPXfpJMgI1ODd3nwz8Npx4O4cg==", + "requires": { + "lru-cache": "^11.0.0", + "minipass": "^7.1.2" + } + }, + "path-to-regexp": { + "version": "0.1.10", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.10.tgz", + "integrity": "sha512-7lf7qcQidTku0Gu3YDPc8DJ1q7OOucfa/BSsIwjuh56VU7katFvuM8hULfkwB3Fns/rsVF7PwPKVw1sl5KQS9w==" + }, + "picomatch": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz", + "integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==" + }, + "proxy-addr": { + "version": "2.0.7", + "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz", + "integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==", + "requires": { + "forwarded": "0.2.0", + "ipaddr.js": "1.9.1" + } + }, + "pstree.remy": { + "version": "1.1.8", + "resolved": "https://registry.npmjs.org/pstree.remy/-/pstree.remy-1.1.8.tgz", + "integrity": "sha512-77DZwxQmxKnu3aR542U+X8FypNzbfJ+C5XQDk3uWjWxn6151aIMGthWYRXTqT1E5oJvg+ljaa2OJi+VfvCOQ8w==" + }, + "punycode": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", + "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==" + }, + "qs": { + "version": "6.13.0", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.13.0.tgz", + "integrity": "sha512-+38qI9SOr8tfZ4QmJNplMUxqjbe7LKvvZgWdExBOmd+egZTtjLB67Gu0HRX3u/XOq7UU2Nx6nsjvS16Z9uwfpg==", + "requires": { + "side-channel": "^1.0.6" + } + }, + "range-parser": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz", + "integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==" + }, + "raw-body": { + "version": "2.5.2", + "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.5.2.tgz", + "integrity": "sha512-8zGqypfENjCIqGhgXToC8aB2r7YrBX+AQAfIPs/Mlk+BtPTztOvTS01NRW/3Eh60J+a48lt8qsCzirQ6loCVfA==", + "requires": { + "bytes": "3.1.2", + "http-errors": "2.0.0", + "iconv-lite": "0.4.24", + "unpipe": "1.0.0" + } + }, + "readdirp": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.6.0.tgz", + "integrity": "sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==", + "requires": { + "picomatch": "^2.2.1" + } + }, + "rimraf": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-6.0.1.tgz", + "integrity": "sha512-9dkvaxAsk/xNXSJzMgFqqMCuFgt2+KsOFek3TMLfo8NCPfWpBmqwyNn5Y+NX56QUYfCtsyhF3ayiboEoUmJk/A==", + "requires": { + "glob": "^11.0.0", + "package-json-from-dist": "^1.0.0" + } + }, + "safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==" + }, + "safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==" + }, + "semver": { + "version": "7.6.3", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.6.3.tgz", + "integrity": "sha512-oVekP1cKtI+CTDvHWYFUcMtsK/00wmAEfyqKfNdARm8u1wNVhSgaX7A8d4UuIlUI5e84iEwOhs7ZPYRmzU9U6A==" + }, + "send": { + "version": "0.19.0", + "resolved": "https://registry.npmjs.org/send/-/send-0.19.0.tgz", + "integrity": "sha512-dW41u5VfLXu8SJh5bwRmyYUbAoSB3c9uQh6L8h/KtsFREPWpbX1lrljJo186Jc4nmci/sGUZ9a0a0J2zgfq2hw==", + "requires": { + "debug": "2.6.9", + "depd": "2.0.0", + "destroy": "1.2.0", + "encodeurl": "~1.0.2", + "escape-html": "~1.0.3", + "etag": "~1.8.1", + "fresh": "0.5.2", + "http-errors": "2.0.0", + "mime": "1.6.0", + "ms": "2.1.3", + "on-finished": "2.4.1", + "range-parser": "~1.2.1", + "statuses": "2.0.1" + }, + "dependencies": { + "debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "requires": { + "ms": "2.0.0" + }, + "dependencies": { + "ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==" + } + } + }, + "encodeurl": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-1.0.2.tgz", + "integrity": "sha512-TPJXq8JqFaVYm2CWmPvnP2Iyo4ZSM7/QKcSmuMLDObfpH5fi7RUGmd/rTDf+rut/saiDiQEeVTNgAmJEdAOx0w==" + } + } + }, + "serve-static": { + "version": "1.16.2", + "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.16.2.tgz", + "integrity": "sha512-VqpjJZKadQB/PEbEwvFdO43Ax5dFBZ2UECszz8bQ7pi7wt//PWe1P6MN7eCnjsatYtBT6EuiClbjSWP2WrIoTw==", + "requires": { + "encodeurl": "~2.0.0", + "escape-html": "~1.0.3", + "parseurl": "~1.3.3", + "send": "0.19.0" + } + }, + "set-function-length": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/set-function-length/-/set-function-length-1.2.2.tgz", + "integrity": "sha512-pgRc4hJ4/sNjWCSS9AmnS40x3bNMDTknHgL5UaMBTMyJnU90EgWh1Rz+MC9eFu4BuN/UwZjKQuY/1v3rM7HMfg==", + "requires": { + "define-data-property": "^1.1.4", + "es-errors": "^1.3.0", + "function-bind": "^1.1.2", + "get-intrinsic": "^1.2.4", + "gopd": "^1.0.1", + "has-property-descriptors": "^1.0.2" + } + }, + "setprototypeof": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", + "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==" + }, + "shebang-command": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", + "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", + "requires": { + "shebang-regex": "^3.0.0" + } + }, + "shebang-regex": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", + "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==" + }, + "side-channel": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.0.6.tgz", + "integrity": "sha512-fDW/EZ6Q9RiO8eFG8Hj+7u/oW+XrPTIChwCOM2+th2A6OblDtYYIpve9m+KvI9Z4C9qSEXlaGR6bTEYHReuglA==", + "requires": { + "call-bind": "^1.0.7", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.4", + "object-inspect": "^1.13.1" + } + }, + "sift": { + "version": "17.1.3", + "resolved": "https://registry.npmjs.org/sift/-/sift-17.1.3.tgz", + "integrity": "sha512-Rtlj66/b0ICeFzYTuNvX/EF1igRbbnGSvEyT79McoZa/DeGhMyC5pWKOEsZKnpkqtSeovd5FL/bjHWC3CIIvCQ==" + }, + "signal-exit": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz", + "integrity": "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==" + }, + "simple-update-notifier": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/simple-update-notifier/-/simple-update-notifier-2.0.0.tgz", + "integrity": "sha512-a2B9Y0KlNXl9u/vsW6sTIu9vGEpfKu2wRV6l1H3XEas/0gUIzGzBoP/IouTcUQbm9JWZLH3COxyn03TYlFax6w==", + "requires": { + "semver": "^7.5.3" + } + }, + "sparse-bitfield": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/sparse-bitfield/-/sparse-bitfield-3.0.3.tgz", + "integrity": "sha512-kvzhi7vqKTfkh0PZU+2D2PIllw2ymqJKujUcyPMd9Y75Nv4nPbGJZXNhxsgdQab2BmlDct1YnfQCguEvHr7VsQ==", + "requires": { + "memory-pager": "^1.0.2" + } + }, + "statuses": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.1.tgz", + "integrity": "sha512-RwNA9Z/7PrK06rYLIzFMlaF+l73iwpzsqRIFgbMLbTcLD6cOao82TaWefPXQvB2fOC4AjuYSEndS7N/mTCbkdQ==" + }, + "string-width": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-5.1.2.tgz", + "integrity": "sha512-HnLOCR3vjcY8beoNLtcjZ5/nxn2afmME6lhrDrebokqMap+XbeW8n9TXpPDOqdGK5qcI3oT0GKTW6wC7EMiVqA==", + "requires": { + "eastasianwidth": "^0.2.0", + "emoji-regex": "^9.2.2", + "strip-ansi": "^7.0.1" + } + }, + "string-width-cjs": { + "version": "npm:string-width@4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "requires": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "dependencies": { + "ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==" + }, + "emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==" + }, + "strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "requires": { + "ansi-regex": "^5.0.1" + } + } + } + }, + "strip-ansi": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.1.0.tgz", + "integrity": "sha512-iq6eVVI64nQQTRYq2KtEg2d2uU7LElhTJwsH4YzIHZshxlgZms/wIc4VoDQTlG/IvVIrBKG06CrZnp0qv7hkcQ==", + "requires": { + "ansi-regex": "^6.0.1" + } + }, + "strip-ansi-cjs": { + "version": "npm:strip-ansi@6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "requires": { + "ansi-regex": "^5.0.1" + }, + "dependencies": { + "ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==" + } + } + }, + "supports-color": { + "version": "5.5.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", + "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", + "requires": { + "has-flag": "^3.0.0" + } + }, + "to-regex-range": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", + "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", + "requires": { + "is-number": "^7.0.0" + } + }, + "toidentifier": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz", + "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==" + }, + "touch": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/touch/-/touch-3.1.1.tgz", + "integrity": "sha512-r0eojU4bI8MnHr8c5bNo7lJDdI2qXlWWJk6a9EAFG7vbhTjElYhBVS3/miuE0uOuoLdb8Mc/rVfsmm6eo5o9GA==" + }, + "tr46": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-4.1.1.tgz", + "integrity": "sha512-2lv/66T7e5yNyhAAC4NaKe5nVavzuGJQVVtRYLyQ2OI8tsJ61PMLlelehb0wi2Hx6+hT/OJUWZcw8MjlSRnxvw==", + "requires": { + "punycode": "^2.3.0" + } + }, + "type-is": { + "version": "1.6.18", + "resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz", + "integrity": "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==", + "requires": { + "media-typer": "0.3.0", + "mime-types": "~2.1.24" + } + }, + "typescript": { + "version": "5.6.2", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.6.2.tgz", + "integrity": "sha512-NW8ByodCSNCwZeghjN3o+JX5OFH0Ojg6sadjEKY4huZ52TqbJTJnDo5+Tw98lSy63NZvi4n+ez5m2u5d4PkZyw==" + }, + "undefsafe": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/undefsafe/-/undefsafe-2.0.5.tgz", + "integrity": "sha512-WxONCrssBM8TSPRqN5EmsjVrsv4A8X12J4ArBiiayv3DyyG3ZlIg6yysuuSYdZsVz3TKcTg2fd//Ujd4CHV1iA==" + }, + "undici-types": { + "version": "6.19.8", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.19.8.tgz", + "integrity": "sha512-ve2KP6f/JnbPBFyobGHuerC9g1FYGn/F8n1LWTwNxCEzd6IfqTwUQcNXgEtmmQ6DlRrC1hrSrBnCZPokRrDHjw==" + }, + "unpipe": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", + "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==" + }, + "utils-merge": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz", + "integrity": "sha512-pMZTvIkT1d+TFGvDOqodOclx0QWkkgi6Tdoa8gC8ffGAAqz9pzPTZWAybbsHHoED/ztMtkv/VoYTYyShUn81hA==" + }, + "validator": { + "version": "13.12.0", + "resolved": "https://registry.npmjs.org/validator/-/validator-13.12.0.tgz", + "integrity": "sha512-c1Q0mCiPlgdTVVVIJIrBuxNicYE+t/7oKeI9MWLj3fh/uq2Pxh/3eeWbVZ4OcGW1TUf53At0njHw5SMdA3tmMg==" + }, + "vary": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", + "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==" + }, + "webidl-conversions": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-7.0.0.tgz", + "integrity": "sha512-VwddBukDzu71offAQR975unBIGqfKZpM+8ZX6ySk8nYhVoo5CYaZyzt3YBvYtRtO+aoGlqxPg/B87NGVZ/fu6g==" + }, + "whatwg-url": { + "version": "13.0.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-13.0.0.tgz", + "integrity": "sha512-9WWbymnqj57+XEuqADHrCJ2eSXzn8WXIW/YSGaZtb2WKAInQ6CHfaUUcTyyver0p8BDg5StLQq8h1vtZuwmOig==", + "requires": { + "tr46": "^4.1.1", + "webidl-conversions": "^7.0.0" + } + }, + "which": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", + "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", + "requires": { + "isexe": "^2.0.0" + } + }, + "wrap-ansi": { + "version": "8.1.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-8.1.0.tgz", + "integrity": "sha512-si7QWI6zUMq56bESFvagtmzMdGOtoxfR+Sez11Mobfc7tm+VkUckk9bW2UeffTGVUbOksxmSw0AA2gs8g71NCQ==", + "requires": { + "ansi-styles": "^6.1.0", + "string-width": "^5.0.1", + "strip-ansi": "^7.0.1" + } + }, + "wrap-ansi-cjs": { + "version": "npm:wrap-ansi@7.0.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", + "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", + "requires": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + }, + "dependencies": { + "ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==" + }, + "ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "requires": { + "color-convert": "^2.0.1" + } + }, + "emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==" + }, + "string-width": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "requires": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + } + }, + "strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "requires": { + "ansi-regex": "^5.0.1" + } + } + } + } + } +} diff --git a/backend/collaboration/package.json b/backend/collaboration/package.json new file mode 100644 index 0000000000..364be1dae6 --- /dev/null +++ b/backend/collaboration/package.json @@ -0,0 +1,28 @@ +{ + "name": "collaboration", + "version": "1.0.0", + "description": "", + "main": "dist/server.js", + "scripts": { + "build": "rimraf dist && npx tsc", + "prestart": "npm run build", + "start": "npx tsc -w & nodemon dist/server.js" + }, + "author": "", + "license": "ISC", + "dependencies": { + "@types/cors": "^2.8.17", + "@types/express": "^4.17.21", + "@types/express-validator": "^3.0.2", + "@types/mongoose": "^5.11.97", + "@types/node": "^22.8.5", + "cors": "^2.8.5", + "dotenv": "^16.4.5", + "express": "^4.21.0", + "express-validator": "^7.2.0", + "mongoose": "^8.7.2", + "nodemon": "^3.1.4", + "rimraf": "^6.0.1", + "typescript": "^5.6.2" + } +} diff --git a/backend/collaboration/sample.env b/backend/collaboration/sample.env new file mode 100644 index 0000000000..dce630388d --- /dev/null +++ b/backend/collaboration/sample.env @@ -0,0 +1,3 @@ +PORT= +NODE_ENV= +MONGODB_URI= \ No newline at end of file diff --git a/backend/collaboration/src/models/ChatLog.ts b/backend/collaboration/src/models/ChatLog.ts new file mode 100644 index 0000000000..c3f4267023 --- /dev/null +++ b/backend/collaboration/src/models/ChatLog.ts @@ -0,0 +1,42 @@ +import mongoose, { Schema } from "mongoose"; + +export type TChatLog = { + collabid: string; + message: string; + senderId: string; + recipientId: string; + timestampEpoch: number; +} + +export interface IChatLog extends TChatLog, Document {} + +const chatLogSchema: Schema = new Schema( + { + collabId: { + type: String, + required: true, + }, + message: { + type: String, + required: true, + }, + senderId: { + type: String, + required: true, + }, + recipientId: { + type: String, + required: true, + }, + timestampEpoch: { + type: Number, + required: true, + }, + }, + { collection: "chatlogs" } +) + +const ChatLogDB = mongoose.connection.useDb("Chatlogs"); +const ChatLog = ChatLogDB.model("ChatLog", chatLogSchema, "chatlogs"); + +export default ChatLog \ No newline at end of file diff --git a/backend/collaboration/src/models/Session.ts b/backend/collaboration/src/models/Session.ts new file mode 100644 index 0000000000..4c272647b0 --- /dev/null +++ b/backend/collaboration/src/models/Session.ts @@ -0,0 +1,70 @@ +import mongoose, { Document, Schema } from "mongoose"; + +/** + * Model for the Session Schema for TypeScript. + */ + +export type TSession = { + collabid: string; + users: [string]; + language: string; + question_id: number; + code: string; + createdAt: Date; +}; + +// Document provides an id field +export interface ISession extends TSession, Document {} + +const sessionSchema: Schema = new Schema( + { + collabid: { + type: String, + required: true, + }, + users: { + type: [String], + required: true, + }, + language: { + type: String, + required: true, + }, + question_id: { + type: Number, + required: true, + }, + code: { + type: String, + required: false, + }, + createdAt: { + type: Date, + required: false, + } + }, + { collection: "sessions" } +); + +// Pre-middleware for findOneAndUpdate +sessionSchema.pre("findOneAndUpdate", async function (next) { + const doc = await this.model.findOne(this.getQuery()); + if (!doc) { + return next(new Error("Document not found")); + } + next(); +}); + +//Pre-middleware for findOneAndDelete +sessionSchema.pre("findOneAndDelete", async function (next) { + const doc = await this.model.findOne(this.getQuery()); + if (!doc) { + return next(new Error("Document not found")); + } + next(); +}); + +const SessionDB = mongoose.connection.useDb("Sessions"); +const Session = SessionDB.model("Session", sessionSchema, "sessions"); + +export default Session; diff --git a/backend/collaboration/src/routes/collaborationRoutes.ts b/backend/collaboration/src/routes/collaborationRoutes.ts new file mode 100644 index 0000000000..9cc26bec93 --- /dev/null +++ b/backend/collaboration/src/routes/collaborationRoutes.ts @@ -0,0 +1,303 @@ +import express, { Request, Response } from "express"; +import { validationResult } from "express-validator"; +import ChatLog from "../models/ChatLog"; +import Session, { TSession } from "../models/Session"; +import { + createChatLogValidators, + createSessionValidators, + getChatLogValidators, + idValidators, + updateSessionValidators, +} from "./validators"; + +/** + * Router for the collaboration service. + */ + +const router = express.Router(); + +router.get("/", (req, res) => { + console.log("Sending Greetings!"); + res.send("Hello from collaboration service!"); +}); + +// Create a new session +router.post( + "/create", + [...createSessionValidators], + async (req: Request, res: Response) => { + const errors = validationResult(req); + if (!errors.isEmpty()) { + return res.status(400).json({ errors: errors.array() }); + } + try { + const { collabid, users, language, question_id } = req.body; + + const existingSession = await Session.findOne({ collabid: collabid }); + if (existingSession) { + return res.status(400).json({ + message: "A session with this id already exists", + }); + } + + const session = { + collabid, + users, + language, + question_id, + code: "", + createdAt: new Date(), + }; + + const newSession = new Session(session); + await newSession.save(); + res.status(200).json({ + message: "Session created successfully", + session: newSession, + }); + } catch (error) { + console.log(error); + return res.status(500).send("Internal server error"); + } + } +); + +// Get all sessions +router.get("/sessions", async (req: Request, res: Response) => { + try { + const sessions: TSession[] = await Session.find().exec(); + res.status(200).json(sessions); + } catch (error) { + return res.status(500).send("Internal server error"); + } +}); + +// Get all sessions with a specific user id in the users array +router.post("/sessions/:id", async (req: Request, res: Response) => { + try { + const { id } = req.params; + const sessions: TSession[] = await Session.find({ users: id }).sort({ createdAt: -1 }).exec(); + + return res.status(200).json(sessions); + } catch (error) { + return res.status(500).send(error); + } +}); + +// Get a single session by collabid +router.get("/:id", [...idValidators], async (req: Request, res: Response) => { + const errors = validationResult(req); + if (!errors.isEmpty()) { + return res.status(400).json({ errors: errors.array() }); + } + const { id } = req.params; + + try { + const session = await Session.findOne({ collabid: id }).exec(); + if (!session) { + return res.status(404).json({ message: "Session not found" }); + } + + res.status(200).json(session); + } catch (error) { + return res.status(500).send("Internal server error"); + } +}); + +// Check if a session exists +router.get( + "/:id/check", + [...idValidators], + async (req: Request, res: Response) => { + const errors = validationResult(req); + if (!errors.isEmpty()) { + return res.status(400).json({ errors: errors.array() }); + } + const { id } = req.params; + + try { + const sessionExists = await Session.exists({ collabid: id }); + res.status(200).json({ exists: Boolean(sessionExists) }); + } catch (error) { + return res.status(500).send("Internal server error"); + } + } +); + +// Check if a session exists with a specific user id in the users array +router.get( + "/:id/check/:userid/:username", + [...idValidators], + async (req: Request, res: Response) => { + const errors = validationResult(req); + if (!errors.isEmpty()) { + return res.status(400).json({ errors: errors.array() }); + } + const { id, userid, username } = req.params; + + try { + // Find a session that has the given collabid and has the given user id or username in the users array + const sessionExists = await Session.exists({ + collabid: id, + $or: [{ users: userid }, { users: username }], + }); + + res.status(200).json({ exists: Boolean(sessionExists) }); + } catch (error) { + return res.status(500).send("Internal server error"); + } + } +); + +// Update a session by ID +router.post( + "/:id/update", + [...updateSessionValidators], + async (req: Request, res: Response) => { + const errors = validationResult(req); + if (!errors.isEmpty()) { + return res.status(400).json({ errors: errors.array() }); + } + const { id } = req.params; + + const updateSession: Partial = {}; + + updateSession.code = req.body.code; + + try { + const session = await Session.findOne({ collabid: id }).exec(); + if (!session) { + return res.status(404).json({ message: "Session not found" }); + } + + const updatedSession = await Session.findOneAndUpdate( + { collabid: id }, + { $set: updateSession }, + { new: true } + ); + res.status(200).json(updatedSession); + } catch (error) { + return res.status(500).send("Internal server error"); + } + } +); + +// Update a session language by ID +router.post( + "/:id/updateLanguage", + async (req: Request, res: Response) => { + const { id } = req.params; + + const updateSession: Partial = {}; + + updateSession.language = req.body.language; + + try { + const session = await Session.findOne({ collabid: id }).exec(); + if (!session) { + return res.status(404).json({ message: "Session not found" }); + } + + const updatedSession = await Session.findOneAndUpdate( + { collabid: id }, + { $set: updateSession } + ); + res.status(200).json(updatedSession); + } catch (error) { + return res.status(500).send("Internal server error"); + } + } +); + +// Delete a session by ID +router.delete( + "/:id", + [...idValidators], + async (req: Request, res: Response) => { + const errors = validationResult(req); + if (!errors.isEmpty()) { + return res.status(400).json({ errors: errors.array() }); + } + try { + const { id } = req.params; + + const deletedSession = await Session.findOneAndDelete({ + collabid: id, + }).exec(); + if (!deletedSession) { + return res.status(404).json({ message: "Session not found" }); + } + + res.status(200).json({ message: "Session deleted successfully" }); + } catch (error) { + return res.status(500).send("Internal server error"); + } + } +); + +// Create a single chat log +router.post("/chat/:collabid/create_chatlog", [...createChatLogValidators], async (req: Request, res: Response) => { + // TODO: Add validation check to check if a collab ID exists and if the sender and recipient IDs are valid + + const errors = validationResult(req); + if (!errors.isEmpty()) { + return res.status(400).json({ errors: errors.array() }); + } + try { + const { message, senderId, recipientId, timestampEpoch } = req.body; + const { collabid } = req.params; + const chatLog = { + collabid, + message, + senderId, + recipientId, + timestampEpoch + }; + + const newChatLog = new ChatLog(chatLog); + await newChatLog.save(); + res.status(200).json({ message: "Chat log created successfully", chatLog: newChatLog }); + } catch (error) { + console.log(error) + return res.status(500).send("Internal server error"); + } +}) + +// Fetch chat logs for a specific collabID with pagination +router.get("/chat/:collabid/get_chatlogs", [...getChatLogValidators], async (req: Request, res: Response) => { + try { + const { collabid } = req.params; + const page = parseInt(req.query.page as string, 10) || 1; + const limit = parseInt(req.query.limit as string, 10) || 10; + + const skip = (page - 1) * limit; + + // Fetch chat logs for the specified collabID, with pagination and sorted by timestamp + const chatLogs = await ChatLog.find({ collabId: collabid }) + .sort({ timestamp: -1 }) // Sort by timestamp in descending order (latest first) + .skip(skip) + .limit(limit); + + chatLogs.reverse(); + + // Get total count of chat logs for the given collabID + const totalLogs = await ChatLog.countDocuments({ collabid }); + const totalPages = Math.ceil(totalLogs / limit); + + res.status(200).json({ + message: "Chat logs fetched successfully", + chatLogs: chatLogs, + pagination: { + page, + limit, + totalPages, + totalLogs, + }, + }); + } catch (error) { + console.log(error); + res.status(500).send("Internal server error"); + } +}); + +export default router; diff --git a/backend/collaboration/src/routes/validators.ts b/backend/collaboration/src/routes/validators.ts new file mode 100644 index 0000000000..b04f9759d6 --- /dev/null +++ b/backend/collaboration/src/routes/validators.ts @@ -0,0 +1,46 @@ +import { check } from "express-validator"; + +export const createSessionValidators = [ + check("collabid").isString().isLength({ min: 1 }), + check("language").isString().isLength({ min: 1 }), + check("question_id").isInt(), + //custom validation for users + check("users").custom((users) => { + if (!Array.isArray(users) || users.length !== 2) { + throw new Error("Users must only contain 2 users"); + } + //check if array contains only non-empty strings and trim whitespace + if ( + !users.every( + (element) => + typeof element === "string" && + element.length > 0 && + element.trim().length > 0 + ) + ) { + throw new Error("Users must be non-empty"); + } + return true; + }), +]; + +export const idValidators = [check("id").isString().isLength({ min: 1 })]; + +export const updateSessionValidators = [ + check("id").isString().isLength({ min: 1 }), + check("code").isString(), +]; + +export const createChatLogValidators = [ + check("collabid").isString().isLength({ min: 1 }), + check("message").isString().isLength({ min: 1 }), + check("senderId").isString().isLength({ min: 1 }), + check("recipientId").isString().isLength({ min: 1 }), + check("timestampEpoch").isInt(), +] + +export const getChatLogValidators = [ + check("collabid").isString().isLength({ min: 1 }), + check("page").isInt(), + check("limit").isInt(), +] \ No newline at end of file diff --git a/backend/collaboration/src/server.ts b/backend/collaboration/src/server.ts new file mode 100644 index 0000000000..9809db2fc6 --- /dev/null +++ b/backend/collaboration/src/server.ts @@ -0,0 +1,42 @@ +import cors from "cors"; +import dotenv from "dotenv"; +import express from "express"; +import mongoose from "mongoose"; +import collaborationRoutes from "./routes/collaborationRoutes"; +dotenv.config(); + +/** + * The URI for the MongoDB database is defined in the environment variable MONGODB_URI, inside your .env file. + * If you face the error "MongoParseError", check the naming of your env variable & check that the .env file exists (/question/.env). + */ +const uri = process.env.MONGODB_URI || ""; + +const app = express(); + +app.use(express.json()); +app.use(cors()); +app.use("/api/collaboration", collaborationRoutes); + +const PORT = process.env.PORT || "3001"; + +async function connect() { + try { + await mongoose.connect(uri); + console.log("Connected to MongoDB"); + } catch (error) { + console.error(error); + } +} + +if (process.env.NODE_ENV === "DEV" || process.env.NODE_ENV === "PRODUCTION") { + connect(); +} + +const server = app.listen(PORT, (err?: Error) => { + if (err) { + return console.error(err); + } + return console.log(`App is running on port ${PORT}`); +}); + +export { app, server }; diff --git a/backend/collaboration/tsconfig.json b/backend/collaboration/tsconfig.json new file mode 100644 index 0000000000..5998441d36 --- /dev/null +++ b/backend/collaboration/tsconfig.json @@ -0,0 +1,110 @@ +{ + "compilerOptions": { + /* Visit https://aka.ms/tsconfig to read more about this file */ + + /* Projects */ + // "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */ + // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */ + // "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */ + // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */ + // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */ + // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */ + + /* Language and Environment */ + "target": "es2016", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */ + // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */ + // "jsx": "preserve", /* Specify what JSX code is generated. */ + // "experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */ + // "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */ + // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */ + // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */ + // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */ + // "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */ + // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */ + // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */ + // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */ + + /* Modules */ + "module": "commonjs", /* Specify what module code is generated. */ + "rootDir": "./src", /* Specify the root folder within your source files. */ + // "moduleResolution": "node10", /* Specify how TypeScript looks up a file from a given module specifier. */ + // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */ + // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */ + // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */ + // "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */ + // "types": [], /* Specify type package names to be included without being referenced in a source file. */ + // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ + // "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */ + // "allowImportingTsExtensions": true, /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */ + // "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */ + // "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */ + // "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */ + // "noUncheckedSideEffectImports": true, /* Check side effect imports. */ + // "resolveJsonModule": true, /* Enable importing .json files. */ + // "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */ + // "noResolve": true, /* Disallow 'import's, 'require's or ''s from expanding the number of files TypeScript should add to a project. */ + + /* JavaScript Support */ + // "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */ + // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */ + // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */ + + /* Emit */ + // "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */ + // "declarationMap": true, /* Create sourcemaps for d.ts files. */ + // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */ + // "sourceMap": true, /* Create source map files for emitted JavaScript files. */ + // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */ + // "noEmit": true, /* Disable emitting files from a compilation. */ + // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */ + "outDir": "./dist", /* Specify an output folder for all emitted files. */ + // "removeComments": true, /* Disable emitting comments. */ + // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */ + // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */ + // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */ + // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ + // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */ + // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */ + // "newLine": "crlf", /* Set the newline character for emitting files. */ + // "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */ + // "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */ + // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */ + // "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */ + // "declarationDir": "./", /* Specify the output directory for generated declaration files. */ + + /* Interop Constraints */ + // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */ + // "verbatimModuleSyntax": true, /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */ + // "isolatedDeclarations": true, /* Require sufficient annotation on exports so other tools can trivially generate declaration files. */ + // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */ + "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */ + // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */ + "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */ + + /* Type Checking */ + "strict": true, /* Enable all strict type-checking options. */ + // "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */ + // "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */ + // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */ + // "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */ + // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */ + // "strictBuiltinIteratorReturn": true, /* Built-in iterators are instantiated with a 'TReturn' type of 'undefined' instead of 'any'. */ + // "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */ + // "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */ + // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */ + // "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */ + // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */ + // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */ + // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */ + // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */ + // "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */ + // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */ + // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */ + // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */ + // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */ + + /* Completeness */ + // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */ + "skipLibCheck": true /* Skip type checking all .d.ts files. */ + } +} diff --git a/backend/matching/.gitignore b/backend/matching/.gitignore new file mode 100644 index 0000000000..5eac309eb1 --- /dev/null +++ b/backend/matching/.gitignore @@ -0,0 +1,33 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ \ No newline at end of file diff --git a/backend/matching/.mvn/wrapper/maven-wrapper.properties b/backend/matching/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000000..d58dfb70ba --- /dev/null +++ b/backend/matching/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,19 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +wrapperVersion=3.3.2 +distributionType=only-script +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.9/apache-maven-3.9.9-bin.zip diff --git a/backend/matching/Dockerfile b/backend/matching/Dockerfile new file mode 100644 index 0000000000..fbedf38570 --- /dev/null +++ b/backend/matching/Dockerfile @@ -0,0 +1,13 @@ +FROM eclipse-temurin:17-jdk-jammy + +WORKDIR /app + +COPY .mvn/ .mvn/ +COPY mvnw pom.xml ./ +RUN ./mvnw dependency:go-offline + +COPY src/ ./src/ + +EXPOSE 3002 + +CMD ["./mvnw", "spring-boot:run"] \ No newline at end of file diff --git a/backend/matching/mvnw b/backend/matching/mvnw new file mode 100755 index 0000000000..19529ddf8c --- /dev/null +++ b/backend/matching/mvnw @@ -0,0 +1,259 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Apache Maven Wrapper startup batch script, version 3.3.2 +# +# Optional ENV vars +# ----------------- +# JAVA_HOME - location of a JDK home dir, required when download maven via java source +# MVNW_REPOURL - repo url base for downloading maven distribution +# MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +# MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output +# ---------------------------------------------------------------------------- + +set -euf +[ "${MVNW_VERBOSE-}" != debug ] || set -x + +# OS specific support. +native_path() { printf %s\\n "$1"; } +case "$(uname)" in +CYGWIN* | MINGW*) + [ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")" + native_path() { cygpath --path --windows "$1"; } + ;; +esac + +# set JAVACMD and JAVACCMD +set_java_home() { + # For Cygwin and MinGW, ensure paths are in Unix format before anything is touched + if [ -n "${JAVA_HOME-}" ]; then + if [ -x "$JAVA_HOME/jre/sh/java" ]; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + JAVACCMD="$JAVA_HOME/jre/sh/javac" + else + JAVACMD="$JAVA_HOME/bin/java" + JAVACCMD="$JAVA_HOME/bin/javac" + + if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then + echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2 + echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2 + return 1 + fi + fi + else + JAVACMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v java + )" || : + JAVACCMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v javac + )" || : + + if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then + echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2 + return 1 + fi + fi +} + +# hash string like Java String::hashCode +hash_string() { + str="${1:-}" h=0 + while [ -n "$str" ]; do + char="${str%"${str#?}"}" + h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296)) + str="${str#?}" + done + printf %x\\n $h +} + +verbose() { :; } +[ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; } + +die() { + printf %s\\n "$1" >&2 + exit 1 +} + +trim() { + # MWRAPPER-139: + # Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds. + # Needed for removing poorly interpreted newline sequences when running in more + # exotic environments such as mingw bash on Windows. + printf "%s" "${1}" | tr -d '[:space:]' +} + +# parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties +while IFS="=" read -r key value; do + case "${key-}" in + distributionUrl) distributionUrl=$(trim "${value-}") ;; + distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;; + esac +done <"${0%/*}/.mvn/wrapper/maven-wrapper.properties" +[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in ${0%/*}/.mvn/wrapper/maven-wrapper.properties" + +case "${distributionUrl##*/}" in +maven-mvnd-*bin.*) + MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ + case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in + *AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;; + :Darwin*x86_64) distributionPlatform=darwin-amd64 ;; + :Darwin*arm64) distributionPlatform=darwin-aarch64 ;; + :Linux*x86_64*) distributionPlatform=linux-amd64 ;; + *) + echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2 + distributionPlatform=linux-amd64 + ;; + esac + distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip" + ;; +maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;; +*) MVN_CMD="mvn${0##*/mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;; +esac + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +[ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}" +distributionUrlName="${distributionUrl##*/}" +distributionUrlNameMain="${distributionUrlName%.*}" +distributionUrlNameMain="${distributionUrlNameMain%-bin}" +MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}" +MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")" + +exec_maven() { + unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || : + exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD" +} + +if [ -d "$MAVEN_HOME" ]; then + verbose "found existing MAVEN_HOME at $MAVEN_HOME" + exec_maven "$@" +fi + +case "${distributionUrl-}" in +*?-bin.zip | *?maven-mvnd-?*-?*.zip) ;; +*) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;; +esac + +# prepare tmp dir +if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then + clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; } + trap clean HUP INT TERM EXIT +else + die "cannot create temp dir" +fi + +mkdir -p -- "${MAVEN_HOME%/*}" + +# Download and Install Apache Maven +verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +verbose "Downloading from: $distributionUrl" +verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +# select .zip or .tar.gz +if ! command -v unzip >/dev/null; then + distributionUrl="${distributionUrl%.zip}.tar.gz" + distributionUrlName="${distributionUrl##*/}" +fi + +# verbose opt +__MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR='' +[ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v + +# normalize http auth +case "${MVNW_PASSWORD:+has-password}" in +'') MVNW_USERNAME='' MVNW_PASSWORD='' ;; +has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;; +esac + +if [ -z "${MVNW_USERNAME-}" ] && command -v wget >/dev/null; then + verbose "Found wget ... using wget" + wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" || die "wget: Failed to fetch $distributionUrl" +elif [ -z "${MVNW_USERNAME-}" ] && command -v curl >/dev/null; then + verbose "Found curl ... using curl" + curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" || die "curl: Failed to fetch $distributionUrl" +elif set_java_home; then + verbose "Falling back to use Java to download" + javaSource="$TMP_DOWNLOAD_DIR/Downloader.java" + targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName" + cat >"$javaSource" <<-END + public class Downloader extends java.net.Authenticator + { + protected java.net.PasswordAuthentication getPasswordAuthentication() + { + return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() ); + } + public static void main( String[] args ) throws Exception + { + setDefault( new Downloader() ); + java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() ); + } + } + END + # For Cygwin/MinGW, switch paths to Windows format before running javac and java + verbose " - Compiling Downloader.java ..." + "$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile Downloader.java" + verbose " - Running Downloader.java ..." + "$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")" +fi + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +if [ -n "${distributionSha256Sum-}" ]; then + distributionSha256Result=false + if [ "$MVN_CMD" = mvnd.sh ]; then + echo "Checksum validation is not supported for maven-mvnd." >&2 + echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + elif command -v sha256sum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c >/dev/null 2>&1; then + distributionSha256Result=true + fi + elif command -v shasum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c >/dev/null 2>&1; then + distributionSha256Result=true + fi + else + echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2 + echo "Please install either command, or disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + fi + if [ $distributionSha256Result = false ]; then + echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2 + echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2 + exit 1 + fi +fi + +# unzip and move +if command -v unzip >/dev/null; then + unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" || die "failed to unzip" +else + tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar" +fi +printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/mvnw.url" +mv -- "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME" + +clean || : +exec_maven "$@" diff --git a/backend/matching/mvnw.cmd b/backend/matching/mvnw.cmd new file mode 100644 index 0000000000..249bdf3822 --- /dev/null +++ b/backend/matching/mvnw.cmd @@ -0,0 +1,149 @@ +<# : batch portion +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM http://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Apache Maven Wrapper startup batch script, version 3.3.2 +@REM +@REM Optional ENV vars +@REM MVNW_REPOURL - repo url base for downloading maven distribution +@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output +@REM ---------------------------------------------------------------------------- + +@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0) +@SET __MVNW_CMD__= +@SET __MVNW_ERROR__= +@SET __MVNW_PSMODULEP_SAVE=%PSModulePath% +@SET PSModulePath= +@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @( + IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B) +) +@SET PSModulePath=%__MVNW_PSMODULEP_SAVE% +@SET __MVNW_PSMODULEP_SAVE= +@SET __MVNW_ARG0_NAME__= +@SET MVNW_USERNAME= +@SET MVNW_PASSWORD= +@IF NOT "%__MVNW_CMD__%"=="" (%__MVNW_CMD__% %*) +@echo Cannot start maven from wrapper >&2 && exit /b 1 +@GOTO :EOF +: end batch / begin powershell #> + +$ErrorActionPreference = "Stop" +if ($env:MVNW_VERBOSE -eq "true") { + $VerbosePreference = "Continue" +} + +# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties +$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl +if (!$distributionUrl) { + Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" +} + +switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) { + "maven-mvnd-*" { + $USE_MVND = $true + $distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip" + $MVN_CMD = "mvnd.cmd" + break + } + default { + $USE_MVND = $false + $MVN_CMD = $script -replace '^mvnw','mvn' + break + } +} + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +if ($env:MVNW_REPOURL) { + $MVNW_REPO_PATTERN = if ($USE_MVND) { "/org/apache/maven/" } else { "/maven/mvnd/" } + $distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace '^.*'+$MVNW_REPO_PATTERN,'')" +} +$distributionUrlName = $distributionUrl -replace '^.*/','' +$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$','' +$MAVEN_HOME_PARENT = "$HOME/.m2/wrapper/dists/$distributionUrlNameMain" +if ($env:MAVEN_USER_HOME) { + $MAVEN_HOME_PARENT = "$env:MAVEN_USER_HOME/wrapper/dists/$distributionUrlNameMain" +} +$MAVEN_HOME_NAME = ([System.Security.Cryptography.MD5]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join '' +$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME" + +if (Test-Path -Path "$MAVEN_HOME" -PathType Container) { + Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME" + Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" + exit $? +} + +if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) { + Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl" +} + +# prepare tmp dir +$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile +$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir" +$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null +trap { + if ($TMP_DOWNLOAD_DIR.Exists) { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } + } +} + +New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null + +# Download and Install Apache Maven +Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +Write-Verbose "Downloading from: $distributionUrl" +Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +$webclient = New-Object System.Net.WebClient +if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) { + $webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD) +} +[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 +$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum +if ($distributionSha256Sum) { + if ($USE_MVND) { + Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." + } + Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash + if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) { + Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property." + } +} + +# unzip and move +Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null +Rename-Item -Path "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" -NewName $MAVEN_HOME_NAME | Out-Null +try { + Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null +} catch { + if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) { + Write-Error "fail to move MAVEN_HOME" + } +} finally { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } +} + +Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" diff --git a/backend/matching/pom.xml b/backend/matching/pom.xml new file mode 100644 index 0000000000..51513a33fd --- /dev/null +++ b/backend/matching/pom.xml @@ -0,0 +1,82 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 3.3.4 + + + com.example.backend + matching + 0.0.1-SNAPSHOT + matching + Matching Service for PeerPrep + + + + + + + + + + + + + + + 17 + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-test + test + + + + org.projectlombok + lombok + 1.18.20 + provided + + + + org.springframework + spring-messaging + + + + org.springframework.boot + spring-boot-starter-websocket + + + + org.springframework.kafka + spring-kafka + + + + redis.clients + jedis + 4.3.1 + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/backend/matching/src/main/java/com/example/backend/matching/MatchingApplication.java b/backend/matching/src/main/java/com/example/backend/matching/MatchingApplication.java new file mode 100644 index 0000000000..2de91628cd --- /dev/null +++ b/backend/matching/src/main/java/com/example/backend/matching/MatchingApplication.java @@ -0,0 +1,13 @@ +package com.example.backend.matching; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class MatchingApplication { + + public static void main(String[] args) { + SpringApplication.run(MatchingApplication.class, args); + } + +} diff --git a/backend/matching/src/main/java/com/example/backend/matching/controller/MatchingRestController.java b/backend/matching/src/main/java/com/example/backend/matching/controller/MatchingRestController.java new file mode 100644 index 0000000000..dd5eb3a895 --- /dev/null +++ b/backend/matching/src/main/java/com/example/backend/matching/controller/MatchingRestController.java @@ -0,0 +1,18 @@ +package com.example.backend.matching.controller; + +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import org.springframework.web.bind.annotation.GetMapping; + +@RestController +@RequestMapping("/api/matching") +public class MatchingRestController { + + @GetMapping("") + public String greeting() { + System.out.println("Sending Greetings!"); + return "Hello from matching service!"; + } + +} diff --git a/backend/matching/src/main/java/com/example/backend/matching/kafka/consumers/KafkaConsumerConfig.java b/backend/matching/src/main/java/com/example/backend/matching/kafka/consumers/KafkaConsumerConfig.java new file mode 100644 index 0000000000..5bf7551930 --- /dev/null +++ b/backend/matching/src/main/java/com/example/backend/matching/kafka/consumers/KafkaConsumerConfig.java @@ -0,0 +1,35 @@ +package com.example.backend.matching.kafka.consumers; + +import java.util.HashMap; +import java.util.Map; + +import org.apache.kafka.clients.consumer.ConsumerConfig; +import org.apache.kafka.common.serialization.StringDeserializer; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.kafka.config.ConcurrentKafkaListenerContainerFactory; +import org.springframework.kafka.core.ConsumerFactory; +import org.springframework.kafka.core.DefaultKafkaConsumerFactory; + +@Configuration +public class KafkaConsumerConfig { + + private final String kafkaBrokerAddress = System.getenv("ENV").equals("DEV") ? System.getenv("DEV_KAFKA_URL") : System.getenv("PROD_KAFKA_URL"); + + @Bean + public ConsumerFactory consumerFactory() { + Map configProps = new HashMap<>(); + configProps.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, kafkaBrokerAddress); // Kafka broker address + configProps.put(ConsumerConfig.GROUP_ID_CONFIG, "matching-service"); // Group ID for consumers + configProps.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class); // Key deserializer + configProps.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class); // Value deserializer + return new DefaultKafkaConsumerFactory<>(configProps); + } + + @Bean + public ConcurrentKafkaListenerContainerFactory kafkaListenerContainerFactory() { + ConcurrentKafkaListenerContainerFactory factory = new ConcurrentKafkaListenerContainerFactory<>(); + factory.setConsumerFactory(consumerFactory()); + return factory; + } +} diff --git a/backend/matching/src/main/java/com/example/backend/matching/kafka/consumers/MatchRequestConsumer.java b/backend/matching/src/main/java/com/example/backend/matching/kafka/consumers/MatchRequestConsumer.java new file mode 100644 index 0000000000..063f20bdb3 --- /dev/null +++ b/backend/matching/src/main/java/com/example/backend/matching/kafka/consumers/MatchRequestConsumer.java @@ -0,0 +1,115 @@ +package com.example.backend.matching.kafka.consumers; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.kafka.annotation.KafkaListener; +import org.springframework.kafka.support.KafkaHeaders; +import org.springframework.messaging.handler.annotation.Header; +import org.springframework.stereotype.Component; +import org.springframework.web.client.RestClientException; +import org.springframework.web.client.RestTemplate; + +import com.example.backend.matching.model.VerificationResponse; +import com.example.backend.matching.model.VerifyMatchesDTO; +import com.example.backend.matching.redis.WaitingRequestsHashMapService; + +@Component +public class MatchRequestConsumer { + + private enum VerificationStatus { + SUCCESS, + CONFLICT_PARTIAL_INVALID, + CONFLICT_BOTH_INVALID + } + + @Autowired + private WaitingRequestsHashMapService waitingRequestsService; + + private final RestTemplate restTemplate = new RestTemplate(); + + private static final String VERIFY_API_URL = System.getenv("ENV").equals("DEV") ? System.getenv("DEV_VERIFY_API_URL") : System.getenv("PROD_VERIFY_API_URL"); + + @KafkaListener(topics = "MATCH_REQUESTS", groupId = "matching-service") + public void listen(@Header(KafkaHeaders.RECEIVED_KEY) String key, String value) { + System.out.println("Received message, key: " + key + " value: " + value); + + if (waitingRequestsService.containsWaitingRequest(key)) { + String receivedUserEmail = value.split("_")[1]; + String storedUserEmail = waitingRequestsService.getWaitingRequest(key).split("_")[1]; + String matchCriteriaTopic = key.split("_")[0]; + String matchCriteriaLanguage = key.split("_")[1]; + String matchCriteriaDifficulty = key.split("_")[2]; + + // Do not match the same user with themselves + if (!storedUserEmail.equals(receivedUserEmail)) { + // Match found + String otherUserValue = waitingRequestsService.getAndRemoveWaitingRequest(key); + + System.out.println("Match found for key: " + key); + System.out.println("Matching users: " + value + " and " + otherUserValue); + System.out.println("Verifying match requests..."); + + VerifyMatchesDTO verifyMatchesDTO = new VerifyMatchesDTO(value, otherUserValue, matchCriteriaTopic, matchCriteriaDifficulty, matchCriteriaLanguage); + + try { + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_JSON); + + HttpEntity request = new HttpEntity<>(verifyMatchesDTO, headers); + ResponseEntity response = restTemplate.exchange( + VERIFY_API_URL + "/verify", + HttpMethod.POST, + request, + new ParameterizedTypeReference() {} + ); + + if (!response.getStatusCode().is2xxSuccessful()) { + throw new RestClientException("Failed to verify match requests. Status code: " + response.getStatusCode()); + } + + VerificationResponse verificationResponse = response.getBody(); + if (verificationResponse == null) { + System.err.println("Failed to verify match requests. Verification response is missing."); + } + + String vStatus = verificationResponse.getStatus(); + + System.out.println("Verification Status: " + vStatus); + System.out.println("Message: " + verificationResponse.getMessage()); + System.out.println("Valid Matches: " + verificationResponse.getValidMatches()); + System.out.println("Invalid Matches: " + verificationResponse.getInvalidMatches()); + + if (vStatus.equals(VerificationStatus.SUCCESS.toString())) { + System.out.println(verificationResponse.getValidMatches()); + } else if (vStatus.equals(VerificationStatus.CONFLICT_PARTIAL_INVALID.toString())) { + System.out.println("Partial match verification failed."); + assert verificationResponse.getInvalidMatches().size() == 1; // Defensive check + String unseenMatch = verificationResponse.getValidMatches().get(0); + waitingRequestsService.addWaitingRequest(key, unseenMatch); + } else if (vStatus.equals(VerificationStatus.CONFLICT_BOTH_INVALID.toString())) { + System.out.println("Both matches are invalid. Not sending to Kafka topic."); + assert verificationResponse.getInvalidMatches().isEmpty(); // Defensive check + } else { + if (verificationResponse.getMessage() != null) { + System.err.println("Verification failed: " + verificationResponse.getMessage()); + } + System.out.println("Match verification failed."); + } + } catch (RestClientException e) { + System.err.println("Error calling verification service: " + e.getMessage()); + } + } else { + System.out.println("No match found for key: " + key); + waitingRequestsService.addWaitingRequest(key, value); + } + } else { + System.out.println("No match found for key: " + key); + waitingRequestsService.addWaitingRequest(key, value); + } + } +} diff --git a/backend/matching/src/main/java/com/example/backend/matching/model/VerificationResponse.java b/backend/matching/src/main/java/com/example/backend/matching/model/VerificationResponse.java new file mode 100644 index 0000000000..41f1bccd51 --- /dev/null +++ b/backend/matching/src/main/java/com/example/backend/matching/model/VerificationResponse.java @@ -0,0 +1,20 @@ +package com.example.backend.matching.model; + +import java.util.List; + +import lombok.Data; + +@Data +public class VerificationResponse { + private String status; + private String message; + private List validMatches; + private List invalidMatches; + + public VerificationResponse(String status, String message, List validMatches, List invalidMatches) { + this.status = status; + this.message = message; + this.validMatches = validMatches; + this.invalidMatches = invalidMatches; + } +} diff --git a/backend/matching/src/main/java/com/example/backend/matching/model/VerifyMatchesDTO.java b/backend/matching/src/main/java/com/example/backend/matching/model/VerifyMatchesDTO.java new file mode 100644 index 0000000000..b188f45b1c --- /dev/null +++ b/backend/matching/src/main/java/com/example/backend/matching/model/VerifyMatchesDTO.java @@ -0,0 +1,20 @@ +package com.example.backend.matching.model; + +import lombok.Data; + +@Data +public class VerifyMatchesDTO { + String user1; + String user2; + String matchCriteriaTopic; + String matchCriteriaDifficulty; + String matchCriteriaLanguage; + + public VerifyMatchesDTO(String user1, String user2, String matchCriteriaTopic, String matchCriteriaDifficulty, String matchCriteriaLanguage) { + this.user1 = user1; + this.user2 = user2; + this.matchCriteriaTopic = matchCriteriaTopic; + this.matchCriteriaDifficulty = matchCriteriaDifficulty; + this.matchCriteriaLanguage = matchCriteriaLanguage; + } +} \ No newline at end of file diff --git a/backend/matching/src/main/java/com/example/backend/matching/redis/JedisConfig.java b/backend/matching/src/main/java/com/example/backend/matching/redis/JedisConfig.java new file mode 100644 index 0000000000..09b0eb8072 --- /dev/null +++ b/backend/matching/src/main/java/com/example/backend/matching/redis/JedisConfig.java @@ -0,0 +1,16 @@ +package com.example.backend.matching.redis; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import redis.clients.jedis.Jedis; + +@Configuration +public class JedisConfig { + private static final String REDIS_HOST = System.getenv("ENV").equals("DEV") ? System.getenv("DEV_REDIS_HOST") : System.getenv("PROD_REDIS_HOST"); + private static final int REDIS_PORT = System.getenv("ENV").equals("DEV") ? Integer.parseInt(System.getenv("DEV_REDIS_PORT")) : Integer.parseInt(System.getenv("PROD_REDIS_PORT")); + + @Bean + public Jedis jedis() { + return new Jedis(REDIS_HOST, REDIS_PORT); + } +} \ No newline at end of file diff --git a/backend/matching/src/main/java/com/example/backend/matching/redis/WaitingRequestsHashMapService.java b/backend/matching/src/main/java/com/example/backend/matching/redis/WaitingRequestsHashMapService.java new file mode 100644 index 0000000000..bd0725f55f --- /dev/null +++ b/backend/matching/src/main/java/com/example/backend/matching/redis/WaitingRequestsHashMapService.java @@ -0,0 +1,37 @@ +package com.example.backend.matching.redis; + +import org.springframework.stereotype.Service; + +import redis.clients.jedis.Jedis; + +@Service +public class WaitingRequestsHashMapService { + private Jedis jedis; + private final String WAITING_MATCH_REQUESTS = "WaitingMatchRequests"; + + public WaitingRequestsHashMapService(Jedis jedis) { + this.jedis = jedis; + } + + public void addWaitingRequest(String matchCriteriaKey, String matchRequestValue) { + jedis.hset(WAITING_MATCH_REQUESTS, matchCriteriaKey, matchRequestValue); + } + + public String getAndRemoveWaitingRequest(String matchCriteriaKey) { + String value = jedis.hget(WAITING_MATCH_REQUESTS, matchCriteriaKey); + + if (value != null) { + jedis.hdel(WAITING_MATCH_REQUESTS, matchCriteriaKey); + } + + return value; + } + + public String getWaitingRequest(String matchCriteriaKey) { + return jedis.hget(WAITING_MATCH_REQUESTS, matchCriteriaKey); + } + + public boolean containsWaitingRequest(String matchCriteriaKey) { + return jedis.hexists(WAITING_MATCH_REQUESTS, matchCriteriaKey); + } +} diff --git a/backend/matching/src/main/resources/application-dev.properties b/backend/matching/src/main/resources/application-dev.properties new file mode 100644 index 0000000000..40d841d20f --- /dev/null +++ b/backend/matching/src/main/resources/application-dev.properties @@ -0,0 +1 @@ +spring.kafka.bootstrap-servers=${DEV_KAFKA_URL} diff --git a/backend/matching/src/main/resources/application-prod.properties b/backend/matching/src/main/resources/application-prod.properties new file mode 100644 index 0000000000..5c71ea6660 --- /dev/null +++ b/backend/matching/src/main/resources/application-prod.properties @@ -0,0 +1 @@ +spring.kafka.bootstrap-servers=${PROD_KAFKA_URL} diff --git a/backend/matching/src/main/resources/application.properties b/backend/matching/src/main/resources/application.properties new file mode 100644 index 0000000000..9c951ff9cd --- /dev/null +++ b/backend/matching/src/main/resources/application.properties @@ -0,0 +1,9 @@ +spring.application.name=matching +server.port=3002 +spring.profiles.active=${ENV} + +# Kafka properties +spring.kafka.consumer.group-id=matching-service +spring.kafka.consumer.auto-offset-reset=earliest +spring.kafka.consumer.properties.spring.json.trusted.packages=* +spring.kafka.consumer.value-deserializer=org.springframework.kafka.support.serializer.JsonDeserializer \ No newline at end of file diff --git a/backend/matching/src/test/java/com/example/backend/matching/MatchingApplicationTests.java b/backend/matching/src/test/java/com/example/backend/matching/MatchingApplicationTests.java new file mode 100644 index 0000000000..df916ffcf9 --- /dev/null +++ b/backend/matching/src/test/java/com/example/backend/matching/MatchingApplicationTests.java @@ -0,0 +1,13 @@ +package com.example.backend.matching; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class MatchingApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/backend/matchverification/.gitignore b/backend/matchverification/.gitignore new file mode 100644 index 0000000000..5eac309eb1 --- /dev/null +++ b/backend/matchverification/.gitignore @@ -0,0 +1,33 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ \ No newline at end of file diff --git a/backend/matchverification/.mvn/wrapper/maven-wrapper.properties b/backend/matchverification/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000000..d58dfb70ba --- /dev/null +++ b/backend/matchverification/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,19 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +wrapperVersion=3.3.2 +distributionType=only-script +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.9/apache-maven-3.9.9-bin.zip diff --git a/backend/matchverification/Dockerfile b/backend/matchverification/Dockerfile new file mode 100644 index 0000000000..98f12125ce --- /dev/null +++ b/backend/matchverification/Dockerfile @@ -0,0 +1,13 @@ +FROM eclipse-temurin:17-jdk-jammy + +WORKDIR /app + +COPY .mvn/ .mvn/ +COPY mvnw pom.xml ./ +RUN ./mvnw dependency:go-offline + +COPY src/ ./src/ + +EXPOSE 3006 + +CMD ["./mvnw", "spring-boot:run"] \ No newline at end of file diff --git a/backend/matchverification/mvnw b/backend/matchverification/mvnw new file mode 100755 index 0000000000..19529ddf8c --- /dev/null +++ b/backend/matchverification/mvnw @@ -0,0 +1,259 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Apache Maven Wrapper startup batch script, version 3.3.2 +# +# Optional ENV vars +# ----------------- +# JAVA_HOME - location of a JDK home dir, required when download maven via java source +# MVNW_REPOURL - repo url base for downloading maven distribution +# MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +# MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output +# ---------------------------------------------------------------------------- + +set -euf +[ "${MVNW_VERBOSE-}" != debug ] || set -x + +# OS specific support. +native_path() { printf %s\\n "$1"; } +case "$(uname)" in +CYGWIN* | MINGW*) + [ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")" + native_path() { cygpath --path --windows "$1"; } + ;; +esac + +# set JAVACMD and JAVACCMD +set_java_home() { + # For Cygwin and MinGW, ensure paths are in Unix format before anything is touched + if [ -n "${JAVA_HOME-}" ]; then + if [ -x "$JAVA_HOME/jre/sh/java" ]; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + JAVACCMD="$JAVA_HOME/jre/sh/javac" + else + JAVACMD="$JAVA_HOME/bin/java" + JAVACCMD="$JAVA_HOME/bin/javac" + + if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then + echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2 + echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2 + return 1 + fi + fi + else + JAVACMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v java + )" || : + JAVACCMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v javac + )" || : + + if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then + echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2 + return 1 + fi + fi +} + +# hash string like Java String::hashCode +hash_string() { + str="${1:-}" h=0 + while [ -n "$str" ]; do + char="${str%"${str#?}"}" + h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296)) + str="${str#?}" + done + printf %x\\n $h +} + +verbose() { :; } +[ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; } + +die() { + printf %s\\n "$1" >&2 + exit 1 +} + +trim() { + # MWRAPPER-139: + # Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds. + # Needed for removing poorly interpreted newline sequences when running in more + # exotic environments such as mingw bash on Windows. + printf "%s" "${1}" | tr -d '[:space:]' +} + +# parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties +while IFS="=" read -r key value; do + case "${key-}" in + distributionUrl) distributionUrl=$(trim "${value-}") ;; + distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;; + esac +done <"${0%/*}/.mvn/wrapper/maven-wrapper.properties" +[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in ${0%/*}/.mvn/wrapper/maven-wrapper.properties" + +case "${distributionUrl##*/}" in +maven-mvnd-*bin.*) + MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ + case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in + *AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;; + :Darwin*x86_64) distributionPlatform=darwin-amd64 ;; + :Darwin*arm64) distributionPlatform=darwin-aarch64 ;; + :Linux*x86_64*) distributionPlatform=linux-amd64 ;; + *) + echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2 + distributionPlatform=linux-amd64 + ;; + esac + distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip" + ;; +maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;; +*) MVN_CMD="mvn${0##*/mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;; +esac + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +[ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}" +distributionUrlName="${distributionUrl##*/}" +distributionUrlNameMain="${distributionUrlName%.*}" +distributionUrlNameMain="${distributionUrlNameMain%-bin}" +MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}" +MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")" + +exec_maven() { + unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || : + exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD" +} + +if [ -d "$MAVEN_HOME" ]; then + verbose "found existing MAVEN_HOME at $MAVEN_HOME" + exec_maven "$@" +fi + +case "${distributionUrl-}" in +*?-bin.zip | *?maven-mvnd-?*-?*.zip) ;; +*) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;; +esac + +# prepare tmp dir +if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then + clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; } + trap clean HUP INT TERM EXIT +else + die "cannot create temp dir" +fi + +mkdir -p -- "${MAVEN_HOME%/*}" + +# Download and Install Apache Maven +verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +verbose "Downloading from: $distributionUrl" +verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +# select .zip or .tar.gz +if ! command -v unzip >/dev/null; then + distributionUrl="${distributionUrl%.zip}.tar.gz" + distributionUrlName="${distributionUrl##*/}" +fi + +# verbose opt +__MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR='' +[ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v + +# normalize http auth +case "${MVNW_PASSWORD:+has-password}" in +'') MVNW_USERNAME='' MVNW_PASSWORD='' ;; +has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;; +esac + +if [ -z "${MVNW_USERNAME-}" ] && command -v wget >/dev/null; then + verbose "Found wget ... using wget" + wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" || die "wget: Failed to fetch $distributionUrl" +elif [ -z "${MVNW_USERNAME-}" ] && command -v curl >/dev/null; then + verbose "Found curl ... using curl" + curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" || die "curl: Failed to fetch $distributionUrl" +elif set_java_home; then + verbose "Falling back to use Java to download" + javaSource="$TMP_DOWNLOAD_DIR/Downloader.java" + targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName" + cat >"$javaSource" <<-END + public class Downloader extends java.net.Authenticator + { + protected java.net.PasswordAuthentication getPasswordAuthentication() + { + return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() ); + } + public static void main( String[] args ) throws Exception + { + setDefault( new Downloader() ); + java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() ); + } + } + END + # For Cygwin/MinGW, switch paths to Windows format before running javac and java + verbose " - Compiling Downloader.java ..." + "$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile Downloader.java" + verbose " - Running Downloader.java ..." + "$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")" +fi + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +if [ -n "${distributionSha256Sum-}" ]; then + distributionSha256Result=false + if [ "$MVN_CMD" = mvnd.sh ]; then + echo "Checksum validation is not supported for maven-mvnd." >&2 + echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + elif command -v sha256sum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c >/dev/null 2>&1; then + distributionSha256Result=true + fi + elif command -v shasum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c >/dev/null 2>&1; then + distributionSha256Result=true + fi + else + echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2 + echo "Please install either command, or disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + fi + if [ $distributionSha256Result = false ]; then + echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2 + echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2 + exit 1 + fi +fi + +# unzip and move +if command -v unzip >/dev/null; then + unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" || die "failed to unzip" +else + tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar" +fi +printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/mvnw.url" +mv -- "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME" + +clean || : +exec_maven "$@" diff --git a/backend/matchverification/mvnw.cmd b/backend/matchverification/mvnw.cmd new file mode 100644 index 0000000000..249bdf3822 --- /dev/null +++ b/backend/matchverification/mvnw.cmd @@ -0,0 +1,149 @@ +<# : batch portion +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM http://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Apache Maven Wrapper startup batch script, version 3.3.2 +@REM +@REM Optional ENV vars +@REM MVNW_REPOURL - repo url base for downloading maven distribution +@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output +@REM ---------------------------------------------------------------------------- + +@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0) +@SET __MVNW_CMD__= +@SET __MVNW_ERROR__= +@SET __MVNW_PSMODULEP_SAVE=%PSModulePath% +@SET PSModulePath= +@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @( + IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B) +) +@SET PSModulePath=%__MVNW_PSMODULEP_SAVE% +@SET __MVNW_PSMODULEP_SAVE= +@SET __MVNW_ARG0_NAME__= +@SET MVNW_USERNAME= +@SET MVNW_PASSWORD= +@IF NOT "%__MVNW_CMD__%"=="" (%__MVNW_CMD__% %*) +@echo Cannot start maven from wrapper >&2 && exit /b 1 +@GOTO :EOF +: end batch / begin powershell #> + +$ErrorActionPreference = "Stop" +if ($env:MVNW_VERBOSE -eq "true") { + $VerbosePreference = "Continue" +} + +# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties +$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl +if (!$distributionUrl) { + Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" +} + +switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) { + "maven-mvnd-*" { + $USE_MVND = $true + $distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip" + $MVN_CMD = "mvnd.cmd" + break + } + default { + $USE_MVND = $false + $MVN_CMD = $script -replace '^mvnw','mvn' + break + } +} + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +if ($env:MVNW_REPOURL) { + $MVNW_REPO_PATTERN = if ($USE_MVND) { "/org/apache/maven/" } else { "/maven/mvnd/" } + $distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace '^.*'+$MVNW_REPO_PATTERN,'')" +} +$distributionUrlName = $distributionUrl -replace '^.*/','' +$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$','' +$MAVEN_HOME_PARENT = "$HOME/.m2/wrapper/dists/$distributionUrlNameMain" +if ($env:MAVEN_USER_HOME) { + $MAVEN_HOME_PARENT = "$env:MAVEN_USER_HOME/wrapper/dists/$distributionUrlNameMain" +} +$MAVEN_HOME_NAME = ([System.Security.Cryptography.MD5]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join '' +$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME" + +if (Test-Path -Path "$MAVEN_HOME" -PathType Container) { + Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME" + Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" + exit $? +} + +if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) { + Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl" +} + +# prepare tmp dir +$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile +$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir" +$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null +trap { + if ($TMP_DOWNLOAD_DIR.Exists) { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } + } +} + +New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null + +# Download and Install Apache Maven +Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +Write-Verbose "Downloading from: $distributionUrl" +Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +$webclient = New-Object System.Net.WebClient +if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) { + $webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD) +} +[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 +$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum +if ($distributionSha256Sum) { + if ($USE_MVND) { + Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." + } + Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash + if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) { + Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property." + } +} + +# unzip and move +Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null +Rename-Item -Path "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" -NewName $MAVEN_HOME_NAME | Out-Null +try { + Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null +} catch { + if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) { + Write-Error "fail to move MAVEN_HOME" + } +} finally { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } +} + +Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" diff --git a/backend/matchverification/pom.xml b/backend/matchverification/pom.xml new file mode 100644 index 0000000000..e820f5bee2 --- /dev/null +++ b/backend/matchverification/pom.xml @@ -0,0 +1,94 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 3.3.4 + + + com.example.backend + matchverification + 0.0.1-SNAPSHOT + matchverification + Matching Verification Service for PeerPrep + + + + + + + + + + + + + + + 17 + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-test + test + + + + org.projectlombok + lombok + 1.18.20 + provided + + + + org.springframework.boot + spring-boot-starter-data-mongodb + + + + org.springframework + spring-messaging + + + + org.springframework.boot + spring-boot-starter-websocket + + + + org.springframework.kafka + spring-kafka + + + + org.projectlombok + lombok + 1.18.20 + provided + + + + redis.clients + jedis + 4.3.1 + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/backend/matchverification/src/main/java/com/example/backend/matchverification/MatchVerificationApplication.java b/backend/matchverification/src/main/java/com/example/backend/matchverification/MatchVerificationApplication.java new file mode 100644 index 0000000000..dcb0a0b5a0 --- /dev/null +++ b/backend/matchverification/src/main/java/com/example/backend/matchverification/MatchVerificationApplication.java @@ -0,0 +1,13 @@ +package com.example.backend.matchverification; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class MatchVerificationApplication { + + public static void main(String[] args) { + SpringApplication.run(MatchVerificationApplication.class, args); + } + +} diff --git a/backend/matchverification/src/main/java/com/example/backend/matchverification/controller/MatchingVerificationRestController.java b/backend/matchverification/src/main/java/com/example/backend/matchverification/controller/MatchingVerificationRestController.java new file mode 100644 index 0000000000..367da58e2c --- /dev/null +++ b/backend/matchverification/src/main/java/com/example/backend/matchverification/controller/MatchingVerificationRestController.java @@ -0,0 +1,165 @@ +package com.example.backend.matchverification.controller; + +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.client.RestClientException; +import org.springframework.web.client.RestTemplate; + +import com.example.backend.matchverification.kafka.producers.MatchVerificationProducer; +import com.example.backend.matchverification.model.PickQuestionDTO; +import com.example.backend.matchverification.model.PickedQuestionResponse; +import com.example.backend.matchverification.model.VerificationResponse; +import com.example.backend.matchverification.model.VerifyMatchesDTO; +import com.example.backend.matchverification.redis.MatchVerificationHashsetService; + +@RestController +@RequestMapping("/api/matchverification") +public class MatchingVerificationRestController { + + private final MatchVerificationHashsetService invalidMatchesHashset; + private MatchVerificationProducer matchVerificationProducer; + + private enum VerificationStatus { + SUCCESS, + CONFLICT_PARTIAL_INVALID, + CONFLICT_BOTH_INVALID + } + + private static final String QUESTION_API_URL = System.getenv("ENV").equals("DEV") ? System.getenv("DEV_QUESTION_API_URL") : System.getenv("PROD_QUESTION_API_URL"); + + private final RestTemplate restTemplate = new RestTemplate(); + + public MatchingVerificationRestController(MatchVerificationHashsetService matchRequestService, MatchVerificationProducer matchVerificationProducer) { + this.invalidMatchesHashset = matchRequestService; + this.matchVerificationProducer = matchVerificationProducer; + } + + @GetMapping("") + public String greeting() { + return "Hello from matching verification service!"; + } + + @PostMapping("/verify") + public VerificationResponse verify(@RequestBody VerifyMatchesDTO userMatches) { + String matchReq1 = userMatches.getUser1(); + String matchReq2 = userMatches.getUser2(); + String userWsId1 = matchReq1.split("_")[0]; + String userEmail1 = matchReq1.split("_")[1]; + String userId1 = matchReq1.split("_")[2]; + String userWsId2 = matchReq2.split("_")[0]; + String userEmail2 = matchReq2.split("_")[1]; + String userId2 = matchReq2.split("_")[2]; + String matchCriteriaTopic = userMatches.getMatchCriteriaTopic(); + String matchCriteriaDifficulty = userMatches.getMatchCriteriaDifficulty(); + String matchCriteriaLanguage = userMatches.getMatchCriteriaLanguage(); + + System.out.println("Verifying match requests: " + matchReq1 + " and " + matchReq2); + + boolean match1IsInvalid = invalidMatchesHashset.isSeen(userWsId1); + boolean match2IsInvalid = invalidMatchesHashset.isSeen(userWsId2); + System.out.println("Match1 status: " + !match1IsInvalid + " Match2 status: " + !match2IsInvalid); + + List validMatches = new ArrayList<>(); + List invalidMatches = new ArrayList<>(); + + if (match1IsInvalid) { + invalidMatches.add(matchReq1); + } else { + validMatches.add(matchReq1); + } + + if (match2IsInvalid) { + invalidMatches.add(matchReq2); + } else { + validMatches.add(matchReq2); + } + + String status = VerificationStatus.SUCCESS.toString(); + String message; + if (validMatches.size() == 1 && invalidMatches.size() == 1) { + System.out.println("PARTIAL INVALID MATCH"); + message = "One or more of the match requests are invalid."; + status = VerificationStatus.CONFLICT_PARTIAL_INVALID.toString(); + } else if (invalidMatches.size() == 2) { + System.out.println("BOTH INVALID MATCH"); + message = "Both match requests are invalid."; + status = VerificationStatus.CONFLICT_BOTH_INVALID.toString(); + } else { + System.out.println("VALID MATCH"); + message = "Both match requests are new and valid."; + invalidMatchesHashset.addToSeenRequests(userWsId1); // Add userWsId1 + invalidMatchesHashset.addToSeenRequests(userWsId2); // Add userWsId2 + + int questionId = -1; + + try { + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_JSON); + + PickQuestionDTO pickQuestionDTO = new PickQuestionDTO(matchCriteriaDifficulty, matchCriteriaTopic); + HttpEntity request = new HttpEntity<>(pickQuestionDTO, headers); + + ResponseEntity response = restTemplate.exchange( + QUESTION_API_URL + "/pick-question", + HttpMethod.POST, + request, + new ParameterizedTypeReference() {} + ); + + if (!response.getStatusCode().is2xxSuccessful()) { + throw new RestClientException("Failed to pick a question for the match criteria. Status code: " + response.getStatusCode()); + } + + PickedQuestionResponse pickedQuestionResponse = response.getBody(); + if (pickedQuestionResponse == null) { + System.err.println("Failed to pick a question for the match criteria. Picked question response is missing."); + } + + questionId = pickedQuestionResponse.getQuestionid(); + } catch (RestClientException e) { + System.err.println("Error calling question service: " + e.getMessage()); + } + + String collaborationUniqueId = UUID.randomUUID().toString(); + String successfulMatch = collaborationUniqueId + + "_" + + questionId + + "_" + + matchCriteriaLanguage + + "_" + + userWsId1 + + "_" + + userId1 + + "_" + + userEmail1 + + "_" + + userWsId2 + + "_" + + userId2 + + "_" + + userEmail2; + System.out.println("Successful match message: " + successfulMatch); + matchVerificationProducer.sendMessage("SUCCESSFUL_MATCHES", successfulMatch, successfulMatch); + } + + return new VerificationResponse( + status, + message, + validMatches, + invalidMatches + ); + } +} diff --git a/backend/matchverification/src/main/java/com/example/backend/matchverification/kafka/consumers/KafkaConsumerConfig.java b/backend/matchverification/src/main/java/com/example/backend/matchverification/kafka/consumers/KafkaConsumerConfig.java new file mode 100644 index 0000000000..8d44fe74ef --- /dev/null +++ b/backend/matchverification/src/main/java/com/example/backend/matchverification/kafka/consumers/KafkaConsumerConfig.java @@ -0,0 +1,35 @@ +package com.example.backend.matchverification.kafka.consumers; + +import java.util.HashMap; +import java.util.Map; + +import org.apache.kafka.clients.consumer.ConsumerConfig; +import org.apache.kafka.common.serialization.StringDeserializer; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.kafka.config.ConcurrentKafkaListenerContainerFactory; +import org.springframework.kafka.core.ConsumerFactory; +import org.springframework.kafka.core.DefaultKafkaConsumerFactory; + +@Configuration +public class KafkaConsumerConfig { + + private final String kafkaBrokerAddress = System.getenv("ENV").equals("DEV") ? System.getenv("DEV_KAFKA_URL") : System.getenv("PROD_KAFKA_URL"); + + @Bean + public ConsumerFactory consumerFactory() { + Map configProps = new HashMap<>(); + configProps.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, kafkaBrokerAddress); // Kafka broker address + configProps.put(ConsumerConfig.GROUP_ID_CONFIG, "match-verification-service"); // Group ID for consumers + configProps.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class); // Key deserializer + configProps.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class); // Value deserializer + return new DefaultKafkaConsumerFactory<>(configProps); + } + + @Bean + public ConcurrentKafkaListenerContainerFactory kafkaListenerContainerFactory() { + ConcurrentKafkaListenerContainerFactory factory = new ConcurrentKafkaListenerContainerFactory<>(); + factory.setConsumerFactory(consumerFactory()); + return factory; + } +} diff --git a/backend/matchverification/src/main/java/com/example/backend/matchverification/kafka/consumers/MatchVerificationConsumer.java b/backend/matchverification/src/main/java/com/example/backend/matchverification/kafka/consumers/MatchVerificationConsumer.java new file mode 100644 index 0000000000..fedd36c77a --- /dev/null +++ b/backend/matchverification/src/main/java/com/example/backend/matchverification/kafka/consumers/MatchVerificationConsumer.java @@ -0,0 +1,22 @@ +package com.example.backend.matchverification.kafka.consumers; + +import org.springframework.kafka.annotation.KafkaListener; +import org.springframework.stereotype.Component; + +import com.example.backend.matchverification.redis.MatchVerificationHashsetService; + +@Component +public class MatchVerificationConsumer { + + private final MatchVerificationHashsetService matchVerificationHashset; + + public MatchVerificationConsumer(MatchVerificationHashsetService matchVerificationHashsetService) { + this.matchVerificationHashset = matchVerificationHashsetService; + } + + @KafkaListener(topics = "DISCONNECTS") + public void listen(String value) { + System.out.println("Disconnect received: " + value); + this.matchVerificationHashset.addToSeenRequests(value); + } +} \ No newline at end of file diff --git a/backend/matchverification/src/main/java/com/example/backend/matchverification/kafka/producers/KafkaProducerConfig.java b/backend/matchverification/src/main/java/com/example/backend/matchverification/kafka/producers/KafkaProducerConfig.java new file mode 100644 index 0000000000..a4f4e68bf0 --- /dev/null +++ b/backend/matchverification/src/main/java/com/example/backend/matchverification/kafka/producers/KafkaProducerConfig.java @@ -0,0 +1,32 @@ +package com.example.backend.matchverification.kafka.producers; + +import java.util.HashMap; +import java.util.Map; + +import org.apache.kafka.clients.producer.ProducerConfig; +import org.apache.kafka.common.serialization.StringSerializer; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.kafka.core.DefaultKafkaProducerFactory; +import org.springframework.kafka.core.KafkaTemplate; +import org.springframework.kafka.core.ProducerFactory; + +@Configuration +public class KafkaProducerConfig { + + private final String kafkaBrokerAddress = System.getenv("ENV").equals("DEV") ? System.getenv("DEV_KAFKA_URL") : System.getenv("PROD_KAFKA_URL"); + + @Bean + public ProducerFactory producerFactory() { + Map configProps = new HashMap<>(); + configProps.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, kafkaBrokerAddress); // Kafka broker address + configProps.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class); // Key serializer + configProps.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class); // Value serializer + return new DefaultKafkaProducerFactory<>(configProps); + } + + @Bean + public KafkaTemplate kafkaTemplate() { + return new KafkaTemplate<>(producerFactory()); + } +} diff --git a/backend/matchverification/src/main/java/com/example/backend/matchverification/kafka/producers/MatchVerificationProducer.java b/backend/matchverification/src/main/java/com/example/backend/matchverification/kafka/producers/MatchVerificationProducer.java new file mode 100644 index 0000000000..c1cd4dc320 --- /dev/null +++ b/backend/matchverification/src/main/java/com/example/backend/matchverification/kafka/producers/MatchVerificationProducer.java @@ -0,0 +1,19 @@ +package com.example.backend.matchverification.kafka.producers; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.kafka.core.KafkaTemplate; +import org.springframework.stereotype.Component; + +@Component +public class MatchVerificationProducer { + @Autowired + private final KafkaTemplate kafkaTemplate; + + public MatchVerificationProducer(KafkaTemplate kafkaTemplate) { + this.kafkaTemplate = kafkaTemplate; + } + + public void sendMessage(String topic, String key, String value) { + kafkaTemplate.send(topic, key, value); + } +} diff --git a/backend/matchverification/src/main/java/com/example/backend/matchverification/model/PickQuestionDTO.java b/backend/matchverification/src/main/java/com/example/backend/matchverification/model/PickQuestionDTO.java new file mode 100644 index 0000000000..eebd95d749 --- /dev/null +++ b/backend/matchverification/src/main/java/com/example/backend/matchverification/model/PickQuestionDTO.java @@ -0,0 +1,14 @@ +package com.example.backend.matchverification.model; + +import lombok.Data; + +@Data +public class PickQuestionDTO { + String complexity; + String category; + + public PickQuestionDTO(String complexity, String category) { + this.complexity = complexity; + this.category = category; + } +} diff --git a/backend/matchverification/src/main/java/com/example/backend/matchverification/model/PickedQuestionResponse.java b/backend/matchverification/src/main/java/com/example/backend/matchverification/model/PickedQuestionResponse.java new file mode 100644 index 0000000000..0b486f4af6 --- /dev/null +++ b/backend/matchverification/src/main/java/com/example/backend/matchverification/model/PickedQuestionResponse.java @@ -0,0 +1,8 @@ +package com.example.backend.matchverification.model; + +import lombok.Data; + +@Data +public class PickedQuestionResponse { + int questionid; +} diff --git a/backend/matchverification/src/main/java/com/example/backend/matchverification/model/VerificationResponse.java b/backend/matchverification/src/main/java/com/example/backend/matchverification/model/VerificationResponse.java new file mode 100644 index 0000000000..c9e676ac04 --- /dev/null +++ b/backend/matchverification/src/main/java/com/example/backend/matchverification/model/VerificationResponse.java @@ -0,0 +1,19 @@ +package com.example.backend.matchverification.model; + +import java.util.List; +import lombok.Data; + +@Data +public class VerificationResponse { + private String status; + private String message; + private List validMatches; + private List invalidMatches; + + public VerificationResponse(String status, String message, List validMatches, List invalidMatches) { + this.status = status; + this.message = message; + this.validMatches = validMatches; + this.invalidMatches = invalidMatches; + } +} diff --git a/backend/matchverification/src/main/java/com/example/backend/matchverification/model/VerifyMatchesDTO.java b/backend/matchverification/src/main/java/com/example/backend/matchverification/model/VerifyMatchesDTO.java new file mode 100644 index 0000000000..e7f8c5ebf1 --- /dev/null +++ b/backend/matchverification/src/main/java/com/example/backend/matchverification/model/VerifyMatchesDTO.java @@ -0,0 +1,20 @@ +package com.example.backend.matchverification.model; + +import lombok.Data; + +@Data +public class VerifyMatchesDTO { + String user1; + String user2; + String matchCriteriaTopic; + String matchCriteriaDifficulty; + String matchCriteriaLanguage; + + public VerifyMatchesDTO(String user1, String user2, String matchCriteriaTopic, String matchCriteriaDifficulty, String matchCriteriaLanguage) { + this.user1 = user1; + this.user2 = user2; + this.matchCriteriaTopic = matchCriteriaTopic; + this.matchCriteriaDifficulty = matchCriteriaDifficulty; + this.matchCriteriaLanguage = matchCriteriaLanguage; + } +} \ No newline at end of file diff --git a/backend/matchverification/src/main/java/com/example/backend/matchverification/redis/JedisConfig.java b/backend/matchverification/src/main/java/com/example/backend/matchverification/redis/JedisConfig.java new file mode 100644 index 0000000000..402bb8060b --- /dev/null +++ b/backend/matchverification/src/main/java/com/example/backend/matchverification/redis/JedisConfig.java @@ -0,0 +1,16 @@ +package com.example.backend.matchverification.redis; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import redis.clients.jedis.Jedis; + +@Configuration +public class JedisConfig { + private static final String REDIS_HOST = System.getenv("ENV").equals("DEV") ? System.getenv("DEV_REDIS_HOST") : System.getenv("PROD_REDIS_HOST"); + private static final int REDIS_PORT = System.getenv("ENV").equals("DEV") ? Integer.parseInt(System.getenv("DEV_REDIS_PORT")) : Integer.parseInt(System.getenv("PROD_REDIS_PORT")); + + @Bean + public Jedis jedis() { + return new Jedis(REDIS_HOST, REDIS_PORT); + } +} \ No newline at end of file diff --git a/backend/matchverification/src/main/java/com/example/backend/matchverification/redis/MatchVerificationHashsetService.java b/backend/matchverification/src/main/java/com/example/backend/matchverification/redis/MatchVerificationHashsetService.java new file mode 100644 index 0000000000..ebdf188eb4 --- /dev/null +++ b/backend/matchverification/src/main/java/com/example/backend/matchverification/redis/MatchVerificationHashsetService.java @@ -0,0 +1,23 @@ +package com.example.backend.matchverification.redis; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import lombok.Data; +import redis.clients.jedis.Jedis; + +@Service +@Data +public class MatchVerificationHashsetService { + @Autowired + private final Jedis jedis; + private final String SEEN_MATCH_REQUESTS = "SeenMatchRequests"; + + public void addToSeenRequests(String matchRequest) { + jedis.sadd(SEEN_MATCH_REQUESTS, matchRequest); + } + + public boolean isSeen(String matchRequest) { + return jedis.sismember(SEEN_MATCH_REQUESTS, matchRequest); + } +} diff --git a/backend/matchverification/src/main/resources/application-dev.properties b/backend/matchverification/src/main/resources/application-dev.properties new file mode 100644 index 0000000000..40d841d20f --- /dev/null +++ b/backend/matchverification/src/main/resources/application-dev.properties @@ -0,0 +1 @@ +spring.kafka.bootstrap-servers=${DEV_KAFKA_URL} diff --git a/backend/matchverification/src/main/resources/application-prod.properties b/backend/matchverification/src/main/resources/application-prod.properties new file mode 100644 index 0000000000..5c71ea6660 --- /dev/null +++ b/backend/matchverification/src/main/resources/application-prod.properties @@ -0,0 +1 @@ +spring.kafka.bootstrap-servers=${PROD_KAFKA_URL} diff --git a/backend/matchverification/src/main/resources/application.properties b/backend/matchverification/src/main/resources/application.properties new file mode 100644 index 0000000000..b446217003 --- /dev/null +++ b/backend/matchverification/src/main/resources/application.properties @@ -0,0 +1,9 @@ +spring.application.name=matchVerification +server.port=3006 +spring.profiles.active=${ENV} + +# Kafka properties +spring.kafka.consumer.group-id=matching-service +spring.kafka.consumer.auto-offset-reset=earliest +spring.kafka.consumer.properties.spring.json.trusted.packages=* +spring.kafka.consumer.value-deserializer=org.springframework.kafka.support.serializer.JsonDeserializer \ No newline at end of file diff --git a/backend/matchverification/src/test/java/com/example/backend/matchverification/MatchVerificationApplicationTests.java b/backend/matchverification/src/test/java/com/example/backend/matchverification/MatchVerificationApplicationTests.java new file mode 100644 index 0000000000..ebb140cd90 --- /dev/null +++ b/backend/matchverification/src/test/java/com/example/backend/matchverification/MatchVerificationApplicationTests.java @@ -0,0 +1,13 @@ +package com.example.backend.matchverification; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class MatchVerificationApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/backend/question/.dockerignore b/backend/question/.dockerignore new file mode 100644 index 0000000000..e99e0ccc55 --- /dev/null +++ b/backend/question/.dockerignore @@ -0,0 +1,4 @@ +.env +node_modules/ +dist/ +sample.env \ No newline at end of file diff --git a/backend/question/Dockerfile b/backend/question/Dockerfile new file mode 100644 index 0000000000..3064654ef8 --- /dev/null +++ b/backend/question/Dockerfile @@ -0,0 +1,13 @@ +FROM node + +WORKDIR /app + +COPY package*.json ./ + +RUN npm install + +COPY . . + +EXPOSE 3003 + +CMD ["npm", "start"] \ No newline at end of file diff --git a/backend/question/README.md b/backend/question/README.md new file mode 100644 index 0000000000..00c6f48474 --- /dev/null +++ b/backend/question/README.md @@ -0,0 +1,18 @@ +# Question Service + +## Description + +This service is used to manage the programming questions given to the users after matching. It uses MongoDB Atlas to host a cloud database to manage the questions. The service comes with a RESTful API interface to support Create, Read, Update and Delete (CRUD) operations. + +This service also includes Jest for unit testing on an isolated Mongo Memory DB server to ensure that all the endpoints work as required. + +## Setup + +1. Install Node version 18 or above. +2. Run `npm install` to install the dependencies required. +3. Create `.env` file in the `/questions` folder, copying the content from `sample.env`, setting `NODE_ENV` as `DEV` and filling in the MONGO_URI. +4. Run `npm start` to start the service. + +## API Documentation + +Refer to [`question.yaml`](./docs/question.yaml) file for the API documentation. diff --git a/backend/question/docs/question.plantuml b/backend/question/docs/question.plantuml new file mode 100644 index 0000000000..a47f989ec0 --- /dev/null +++ b/backend/question/docs/question.plantuml @@ -0,0 +1,70 @@ +@startuml Question Service + +entity Question { + + questionId : number + + title : string + + description : string + + complexity : string + + category : Array + + hints: string + + examples: Example[] + + solution: string +} + +entity Example { + + example_num: number + + expected_input: string + + expected_output: string + + explanation: string +} + +entity EditQuestion { + + title : string + + description : string + + complexity : string + + category : Array + + hints: string + + examples: Example[] + + solution: string +} + +entity Pagination { + + pagination : number = 1 + + pageSize : number = 10 +} + +interface IQuestionServiceAPI { + + GET / + + POST /create [createQuestion: EditQuestion] + + POST /all [pagination: Pagination, title: string, complexity: string[], category: string[]] + + POST /all-ids [questionIds: number[]] + + GET /{id} + + POST /{id}/update [updateQuestion: EditQuestion] + + POST /{id}/delete + + POST /count-question [complexity: string[], category: string[]] + + POST /pick-question [complexity: string[], category: string[]] +} + +note right of IQuestionServiceAPI + - GET /: Check service status + - POST /create: Create a new question + - POST /all: Retrieve all questions with pagination (Supports filtering by title, complexiy and category) + - POST /all-ids: Retrieve questions based on a list of question ids + - GET /{id}: Retrieve a specific question by ID + - POST /{id}/update: Update a specific question by ID + - POST /{id}/delete: Delete a specific question by ID + - POST /count-question: Count non-deleted questions given a list of complexities and categories + - POST /pick-question: Pick a random question given a complexity and category +end note + +class QuestionService { +} + +entity QuestionDatabase { + + questions: Array +} + +QuestionService ..|> IQuestionServiceAPI : implements +QuestionService --> QuestionDatabase : interacts with + +@enduml \ No newline at end of file diff --git a/backend/question/docs/question.yaml b/backend/question/docs/question.yaml new file mode 100644 index 0000000000..e60d61fece --- /dev/null +++ b/backend/question/docs/question.yaml @@ -0,0 +1,433 @@ +openapi: 3.0.0 +info: + title: Question Service API + description: API for managing questions, including CRUD operations. + version: 1.0.0 +servers: + # Added by API Auto Mocking Plugin + - description: SwaggerHub API Auto Mocking + url: https://virtserver.swaggerhub.com/JEHOUSOH/Question/1.0.0 + - url: http://localhost:3003 + description: Local development server + +paths: + /: + get: + summary: Check service status + responses: + "200": + description: Service status message + content: + application/json: + schema: + type: object + properties: + message: + type: string + example: Hello from question service! + + /create: + post: + summary: Create a new question + requestBody: + required: true + content: + application/json: + schema: + $ref: "#/components/schemas/QuestionCreate" + responses: + "200": + description: Question created successfully + content: + application/json: + schema: + type: object + properties: + message: + type: string + example: Question created successfully + question: + $ref: "#/components/schemas/Question" + "400": + description: Bad Request (validation error) + "500": + description: Internal server error + + /all: + post: + summary: Retrieve all questions with pagination + requestBody: + content: + application/json: + schema: + type: object + properties: + pagination: + type: integer + default: 1 + description: Page number + example: 1 + page_size: + type: integer + default: 10 + description: Number of questions per page + example: 10 + title: + type: string + default: "" + description: Filter by title + example: "Two Sum" + complexity: + type: array + items: + type: string + default: [] + description: Filter by complexities + example: ["Easy", "Medium", "Hard"] + category: + type: array + items: + type: string + default: [] + description: Filter by categories + example: + [ + "Hash Table", + "Array", + "Linked List", + "Dynamic Programming", + "Math", + "String", + ] + responses: + "200": + description: List of questions + content: + application/json: + schema: + $ref: "#/components/schemas/QuestionAll" + "500": + description: Internal server error + + /all-ids: + post: + summary: Retrieve all questions based on a list of question ids + requestBody: + content: + application/json: + schema: + type: object + properties: + questionIds: + type: array + items: + type: number + default: [] + description: Retrieve by questionid + example: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + responses: + "200": + description: List of questions + content: + application/json: + schema: + $ref: "#/components/schemas/QuestionAll" + "500": + description: Internal server error + + /{id}: + get: + summary: Get a specific question by ID + parameters: + - in: path + name: id + schema: + type: integer + required: true + description: ID of the question + responses: + "200": + description: A specific question + content: + application/json: + schema: + $ref: "#/components/schemas/Question" + "400": + description: Invalid ID format + "404": + description: Question not found + "500": + description: Internal server error + + /{id}/update: + post: + summary: Update a specific question by ID + parameters: + - in: path + name: id + schema: + type: integer + required: true + description: ID of the question to update + requestBody: + required: true + content: + application/json: + schema: + $ref: "#/components/schemas/QuestionUpdate" + responses: + "200": + description: Updated question + content: + application/json: + schema: + $ref: "#/components/schemas/QuestionUpdate" + "400": + description: Validation or duplicate title error + "404": + description: Question not found + "500": + description: Internal server error + + /{id}/delete: + post: + summary: Delete a specific question by ID + parameters: + - in: path + name: id + schema: + type: integer + required: true + description: ID of the question to delete + responses: + "200": + description: Deleted question + content: + application/json: + schema: + $ref: "#/components/schemas/Question" + "404": + description: Question not found + "500": + description: Internal server error + /count-question: + post: + summary: Count the number of questions given a list of complexities and categories + requestBody: + content: + application/json: + schema: + type: object + properties: + complexity: + type: array + items: + type: string + default: [] + description: Filter by complexities + example: ["Easy"] + category: + type: array + items: + type: string + default: [] + description: Filter by categories + example: ["Hash Table"] + + responses: + "200": + description: Questions count + content: + application/json: + schema: + type: object + properties: + count: + type: integer + example: 1 + + "500": + description: Internal server error + /pick-question: + post: + summary: Pick a random question given a list of complexities and categories + requestBody: + content: + application/json: + schema: + type: object + properties: + complexity: + type: array + items: + type: string + default: [] + description: Filter by complexities + example: ["Easy"] + category: + type: array + items: + type: string + default: [] + description: Filter by categories + example: ["Hash Table"] + + responses: + "200": + description: Question picked + content: + application/json: + schema: + $ref: "#/components/schemas/Question" + "400": + description: Bad Request (validation error) + "404": + description: No Question found + "500": + description: Internal server error + +components: + schemas: + Question: + type: object + properties: + questionid: + type: integer + example: 1 + title: + type: string + example: "Two Sum" + description: + type: string + example: "Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.You may assume that each input would have exactly one solution, and you may not use the same element twice.You can return the answer in any order." + category: + type: array + items: + type: string + example: ["Array", "Hash Table"] + complexity: + type: string + example: "Easy" + deleted: + type: boolean + example: false + + QuestionCreate: + type: object + required: + - title + - description + - category + - complexity + properties: + title: + type: string + example: "Two Sum" + description: + type: string + example: "Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.You may assume that each input would have exactly one solution, and you may not use the same element twice.You can return the answer in any order." + category: + type: array + items: + type: string + example: ["Array", "Hash Table"] + complexity: + type: string + example: "Easy" + + QuestionAll: + type: object + properties: + questions: + type: array + items: + $ref: "#/components/schemas/Question" + example: + - _id: "66f925ddfdfb8e1665720acc" + questionid: 1 + title: "Two Sum" + description: "Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not use the same element twice. You can return the answer in any order. " + category: ["Array", "Hash Table"] + complexity: "Easy" + - _id: "66f925ddfdfb8e1665720acd" + questionid: 2 + title: "Add Two Numbers" + description: "You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list. You may assume the two numbers do not contain any leading zero, except the number 0 itself. " + category: ["Linked List", "Math", "Recursion"] + complexity: "Medium" + - _id: "66f925ddfdfb8e1665720ace" + questionid: 3 + title: "Longest Substring Without Repeating Characters" + description: "Given a string s, find the length of the longest substring without repeating characters. " + category: ["Hash Table", "String", "Sliding Window"] + complexity: "Medium" + - _id: "66f925ddfdfb8e1665720acf" + questionid: 4 + title: "Median of Two Sorted Arrays" + description: "Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)). " + category: ["Array", "Binary Search", "Divide and Conquer"] + complexity: "Hard" + - _id: "66f925ddfdfb8e1665720ad0" + questionid: 5 + title: "Longest Palindromic Substring" + description: "Given a string s, return the longest palindromic substring in s. " + category: ["String", "Dynamic Programming"] + complexity: "Medium" + - _id: "66f925ddfdfb8e1665720ad1" + questionid: 6 + title: "Reverse Integer" + description: "Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0. Assume the environment does not allow you to store 64-bit integers (signed or unsigned). " + category: ["Math"] + complexity: "Medium" + - _id: "66f925ddfdfb8e1665720ad2" + questionid: 7 + title: "Palindrome Number" + description: "Given an integer x, return true if x is palindrome integer. An integer is a palindrome when it reads the same backward as forward. " + category: ["Math"] + complexity: "Easy" + - _id: "66f925ddfdfb8e1665720ad3" + questionid: 8 + title: "Container With Most Water" + description: "You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the ith line are (i, 0) and (i, height[i]). Find two lines that together with the x-axis form a container, such that the container contains the most water. Return the maximum amount of water a container can store. Notice that you may not slant the container. " + category: ["Array", "Two Pointers", "Greedy"] + complexity: "Medium" + - _id: "66f925ddfdfb8e1665720ad4" + questionid: 9 + title: "Longest Common Prefix" + description: 'Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string "". ' + category: ["String"] + complexity: "Easy" + - _id: "66f925ddfdfb8e1665720ad5" + questionid: 10 + title: "3Sum" + description: "Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0. Notice that the solution set must not contain duplicate triplets. " + category: ["Array", "Two Pointers", "Sorting"] + complexity: "Medium" + + currentPage: + type: integer + example: 1 + totalPages: + type: integer + example: 10 + totalQuestions: + type: integer + example: 100 + + QuestionUpdate: + type: object + properties: + title: + type: string + example: "Two Sum Updated" + description: + type: string + example: "Updated question description" + category: + type: array + items: + type: string + example: ["Dynamic Programming", "Bit Manipulation"] + complexity: + type: string + example: "Hard" diff --git a/backend/question/jest.config.ts b/backend/question/jest.config.ts new file mode 100644 index 0000000000..344dcfe0a2 --- /dev/null +++ b/backend/question/jest.config.ts @@ -0,0 +1,8 @@ +export default { + preset: "ts-jest", + testEnvironment: "node", + setupFiles: ["dotenv/config"], + collectCoverage: true, + coverageReporters: ["text", "html"], + coverageDirectory: "/coverage/", +}; diff --git a/backend/question/package-lock.json b/backend/question/package-lock.json new file mode 100644 index 0000000000..d43201d158 --- /dev/null +++ b/backend/question/package-lock.json @@ -0,0 +1,8301 @@ +{ + "name": "question", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "question", + "version": "1.0.0", + "license": "ISC", + "dependencies": { + "@types/cors": "^2.8.17", + "@types/express": "^4.17.21", + "@types/jest": "^29.5.13", + "@types/node": "^22.5.5", + "@types/supertest": "^6.0.2", + "cors": "^2.8.5", + "dotenv": "^16.4.5", + "express": "^4.21.0", + "express-validator": "^7.2.0", + "jest": "^29.7.0", + "mongodb-memory-server": "^10.0.1", + "mongoose": "^8.6.3", + "mongoose-sequence": "^6.0.1", + "supertest": "^7.0.0", + "ts-node": "^10.9.2", + "tsx": "^4.19.1", + "typescript": "^5.6.2" + }, + "devDependencies": { + "@types/express": "^4.17.21", + "@types/mongoose-sequence": "^3.0.11", + "@types/node": "^22.5.5", + "cross-env": "^7.0.3", + "nodemon": "^3.1.7", + "rimraf": "^6.0.1", + "ts-jest": "^29.2.5", + "typescript": "^5.6.2" + } + }, + "node_modules/@ampproject/remapping": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/@ampproject/remapping/-/remapping-2.3.0.tgz", + "integrity": "sha512-30iZtAPgz+LTIYoeivqYo853f02jBYSd5uGnGpkFV0M3xOt9aN73erkgYAmZU43x4VfqcnLxW9Kpg3R5LC4YYw==", + "license": "Apache-2.0", + "dependencies": { + "@jridgewell/gen-mapping": "^0.3.5", + "@jridgewell/trace-mapping": "^0.3.24" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@ampproject/remapping/node_modules/@jridgewell/trace-mapping": { + "version": "0.3.25", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.25.tgz", + "integrity": "sha512-vNk6aEwybGtawWmy/PzwnGDOjCkLWSD2wqvjGGAgOAwCGWySYXfYoxt00IJkTF+8Lb57DwOb3Aa0o9CApepiYQ==", + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, + "node_modules/@aws-crypto/sha256-browser": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/@aws-crypto/sha256-browser/-/sha256-browser-5.2.0.tgz", + "integrity": "sha512-AXfN/lGotSQwu6HNcEsIASo7kWXZ5HYWvfOmSNKDsEqC4OashTp8alTmaz+F7TC2L083SFv5RdB+qU3Vs1kZqw==", + "optional": true, + "dependencies": { + "@aws-crypto/sha256-js": "^5.2.0", + "@aws-crypto/supports-web-crypto": "^5.2.0", + "@aws-crypto/util": "^5.2.0", + "@aws-sdk/types": "^3.222.0", + "@aws-sdk/util-locate-window": "^3.0.0", + "@smithy/util-utf8": "^2.0.0", + "tslib": "^2.6.2" + } + }, + "node_modules/@aws-crypto/sha256-browser/node_modules/@smithy/is-array-buffer": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@smithy/is-array-buffer/-/is-array-buffer-2.2.0.tgz", + "integrity": "sha512-GGP3O9QFD24uGeAXYUjwSTXARoqpZykHadOmA8G5vfJPK0/DC67qa//0qvqrJzL1xc8WQWX7/yc7fwudjPHPhA==", + "optional": true, + "dependencies": { + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@aws-crypto/sha256-browser/node_modules/@smithy/util-buffer-from": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@smithy/util-buffer-from/-/util-buffer-from-2.2.0.tgz", + "integrity": "sha512-IJdWBbTcMQ6DA0gdNhh/BwrLkDR+ADW5Kr1aZmd4k3DIF6ezMV4R2NIAmT08wQJ3yUK82thHWmC/TnK/wpMMIA==", + "optional": true, + "dependencies": { + "@smithy/is-array-buffer": "^2.2.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@aws-crypto/sha256-browser/node_modules/@smithy/util-utf8": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/@smithy/util-utf8/-/util-utf8-2.3.0.tgz", + "integrity": "sha512-R8Rdn8Hy72KKcebgLiv8jQcQkXoLMOGGv5uI1/k0l+snqkOzQ1R0ChUBCxWMlBsFMekWjq0wRudIweFs7sKT5A==", + "optional": true, + "dependencies": { + "@smithy/util-buffer-from": "^2.2.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@aws-crypto/sha256-js": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/@aws-crypto/sha256-js/-/sha256-js-5.2.0.tgz", + "integrity": "sha512-FFQQyu7edu4ufvIZ+OadFpHHOt+eSTBaYaki44c+akjg7qZg9oOQeLlk77F6tSYqjDAFClrHJk9tMf0HdVyOvA==", + "optional": true, + "dependencies": { + "@aws-crypto/util": "^5.2.0", + "@aws-sdk/types": "^3.222.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@aws-crypto/supports-web-crypto": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/@aws-crypto/supports-web-crypto/-/supports-web-crypto-5.2.0.tgz", + "integrity": "sha512-iAvUotm021kM33eCdNfwIN//F77/IADDSs58i+MDaOqFrVjZo9bAal0NK7HurRuWLLpF1iLX7gbWrjHjeo+YFg==", + "optional": true, + "dependencies": { + "tslib": "^2.6.2" + } + }, + "node_modules/@aws-crypto/util": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/@aws-crypto/util/-/util-5.2.0.tgz", + "integrity": "sha512-4RkU9EsI6ZpBve5fseQlGNUWKMa1RLPQ1dnjnQoe07ldfIzcsGb5hC5W0Dm7u423KWzawlrpbjXBrXCEv9zazQ==", + "optional": true, + "dependencies": { + "@aws-sdk/types": "^3.222.0", + "@smithy/util-utf8": "^2.0.0", + "tslib": "^2.6.2" + } + }, + "node_modules/@aws-crypto/util/node_modules/@smithy/is-array-buffer": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@smithy/is-array-buffer/-/is-array-buffer-2.2.0.tgz", + "integrity": "sha512-GGP3O9QFD24uGeAXYUjwSTXARoqpZykHadOmA8G5vfJPK0/DC67qa//0qvqrJzL1xc8WQWX7/yc7fwudjPHPhA==", + "optional": true, + "dependencies": { + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@aws-crypto/util/node_modules/@smithy/util-buffer-from": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@smithy/util-buffer-from/-/util-buffer-from-2.2.0.tgz", + "integrity": "sha512-IJdWBbTcMQ6DA0gdNhh/BwrLkDR+ADW5Kr1aZmd4k3DIF6ezMV4R2NIAmT08wQJ3yUK82thHWmC/TnK/wpMMIA==", + "optional": true, + "dependencies": { + "@smithy/is-array-buffer": "^2.2.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@aws-crypto/util/node_modules/@smithy/util-utf8": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/@smithy/util-utf8/-/util-utf8-2.3.0.tgz", + "integrity": "sha512-R8Rdn8Hy72KKcebgLiv8jQcQkXoLMOGGv5uI1/k0l+snqkOzQ1R0ChUBCxWMlBsFMekWjq0wRudIweFs7sKT5A==", + "optional": true, + "dependencies": { + "@smithy/util-buffer-from": "^2.2.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@aws-sdk/client-cognito-identity": { + "version": "3.654.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/client-cognito-identity/-/client-cognito-identity-3.654.0.tgz", + "integrity": "sha512-3K806KJVivVP011R7Wf4ujGKP8R6d7KFlo9t0Swr9YFnStCdSdjmRX1yW8RpzSzRC4xyuUw+bo8wPf+tE/YxnA==", + "optional": true, + "dependencies": { + "@aws-crypto/sha256-browser": "5.2.0", + "@aws-crypto/sha256-js": "5.2.0", + "@aws-sdk/client-sso-oidc": "3.654.0", + "@aws-sdk/client-sts": "3.654.0", + "@aws-sdk/core": "3.654.0", + "@aws-sdk/credential-provider-node": "3.654.0", + "@aws-sdk/middleware-host-header": "3.654.0", + "@aws-sdk/middleware-logger": "3.654.0", + "@aws-sdk/middleware-recursion-detection": "3.654.0", + "@aws-sdk/middleware-user-agent": "3.654.0", + "@aws-sdk/region-config-resolver": "3.654.0", + "@aws-sdk/types": "3.654.0", + "@aws-sdk/util-endpoints": "3.654.0", + "@aws-sdk/util-user-agent-browser": "3.654.0", + "@aws-sdk/util-user-agent-node": "3.654.0", + "@smithy/config-resolver": "^3.0.8", + "@smithy/core": "^2.4.3", + "@smithy/fetch-http-handler": "^3.2.7", + "@smithy/hash-node": "^3.0.6", + "@smithy/invalid-dependency": "^3.0.6", + "@smithy/middleware-content-length": "^3.0.8", + "@smithy/middleware-endpoint": "^3.1.3", + "@smithy/middleware-retry": "^3.0.18", + "@smithy/middleware-serde": "^3.0.6", + "@smithy/middleware-stack": "^3.0.6", + "@smithy/node-config-provider": "^3.1.7", + "@smithy/node-http-handler": "^3.2.2", + "@smithy/protocol-http": "^4.1.3", + "@smithy/smithy-client": "^3.3.2", + "@smithy/types": "^3.4.2", + "@smithy/url-parser": "^3.0.6", + "@smithy/util-base64": "^3.0.0", + "@smithy/util-body-length-browser": "^3.0.0", + "@smithy/util-body-length-node": "^3.0.0", + "@smithy/util-defaults-mode-browser": "^3.0.18", + "@smithy/util-defaults-mode-node": "^3.0.18", + "@smithy/util-endpoints": "^2.1.2", + "@smithy/util-middleware": "^3.0.6", + "@smithy/util-retry": "^3.0.6", + "@smithy/util-utf8": "^3.0.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@aws-sdk/client-sso": { + "version": "3.654.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/client-sso/-/client-sso-3.654.0.tgz", + "integrity": "sha512-4kBxs2IzCDtj6a6lRXa/lXK5wWpMGzwKtb+HMXf/rJYVM6x7wYRzc1hYrOd3DYkFQ/sR3dUFj+0mTP0os3aAbA==", + "optional": true, + "dependencies": { + "@aws-crypto/sha256-browser": "5.2.0", + "@aws-crypto/sha256-js": "5.2.0", + "@aws-sdk/core": "3.654.0", + "@aws-sdk/middleware-host-header": "3.654.0", + "@aws-sdk/middleware-logger": "3.654.0", + "@aws-sdk/middleware-recursion-detection": "3.654.0", + "@aws-sdk/middleware-user-agent": "3.654.0", + "@aws-sdk/region-config-resolver": "3.654.0", + "@aws-sdk/types": "3.654.0", + "@aws-sdk/util-endpoints": "3.654.0", + "@aws-sdk/util-user-agent-browser": "3.654.0", + "@aws-sdk/util-user-agent-node": "3.654.0", + "@smithy/config-resolver": "^3.0.8", + "@smithy/core": "^2.4.3", + "@smithy/fetch-http-handler": "^3.2.7", + "@smithy/hash-node": "^3.0.6", + "@smithy/invalid-dependency": "^3.0.6", + "@smithy/middleware-content-length": "^3.0.8", + "@smithy/middleware-endpoint": "^3.1.3", + "@smithy/middleware-retry": "^3.0.18", + "@smithy/middleware-serde": "^3.0.6", + "@smithy/middleware-stack": "^3.0.6", + "@smithy/node-config-provider": "^3.1.7", + "@smithy/node-http-handler": "^3.2.2", + "@smithy/protocol-http": "^4.1.3", + "@smithy/smithy-client": "^3.3.2", + "@smithy/types": "^3.4.2", + "@smithy/url-parser": "^3.0.6", + "@smithy/util-base64": "^3.0.0", + "@smithy/util-body-length-browser": "^3.0.0", + "@smithy/util-body-length-node": "^3.0.0", + "@smithy/util-defaults-mode-browser": "^3.0.18", + "@smithy/util-defaults-mode-node": "^3.0.18", + "@smithy/util-endpoints": "^2.1.2", + "@smithy/util-middleware": "^3.0.6", + "@smithy/util-retry": "^3.0.6", + "@smithy/util-utf8": "^3.0.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@aws-sdk/client-sso-oidc": { + "version": "3.654.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/client-sso-oidc/-/client-sso-oidc-3.654.0.tgz", + "integrity": "sha512-gbHrKsEnaAtmkNCVQzLyiqMzpDaThV/bWl/ODEklI+t6stW3Pe3oDMstEHLfJ6JU5g8sYnx4VLuxlnJMtUkvPw==", + "optional": true, + "dependencies": { + "@aws-crypto/sha256-browser": "5.2.0", + "@aws-crypto/sha256-js": "5.2.0", + "@aws-sdk/core": "3.654.0", + "@aws-sdk/credential-provider-node": "3.654.0", + "@aws-sdk/middleware-host-header": "3.654.0", + "@aws-sdk/middleware-logger": "3.654.0", + "@aws-sdk/middleware-recursion-detection": "3.654.0", + "@aws-sdk/middleware-user-agent": "3.654.0", + "@aws-sdk/region-config-resolver": "3.654.0", + "@aws-sdk/types": "3.654.0", + "@aws-sdk/util-endpoints": "3.654.0", + "@aws-sdk/util-user-agent-browser": "3.654.0", + "@aws-sdk/util-user-agent-node": "3.654.0", + "@smithy/config-resolver": "^3.0.8", + "@smithy/core": "^2.4.3", + "@smithy/fetch-http-handler": "^3.2.7", + "@smithy/hash-node": "^3.0.6", + "@smithy/invalid-dependency": "^3.0.6", + "@smithy/middleware-content-length": "^3.0.8", + "@smithy/middleware-endpoint": "^3.1.3", + "@smithy/middleware-retry": "^3.0.18", + "@smithy/middleware-serde": "^3.0.6", + "@smithy/middleware-stack": "^3.0.6", + "@smithy/node-config-provider": "^3.1.7", + "@smithy/node-http-handler": "^3.2.2", + "@smithy/protocol-http": "^4.1.3", + "@smithy/smithy-client": "^3.3.2", + "@smithy/types": "^3.4.2", + "@smithy/url-parser": "^3.0.6", + "@smithy/util-base64": "^3.0.0", + "@smithy/util-body-length-browser": "^3.0.0", + "@smithy/util-body-length-node": "^3.0.0", + "@smithy/util-defaults-mode-browser": "^3.0.18", + "@smithy/util-defaults-mode-node": "^3.0.18", + "@smithy/util-endpoints": "^2.1.2", + "@smithy/util-middleware": "^3.0.6", + "@smithy/util-retry": "^3.0.6", + "@smithy/util-utf8": "^3.0.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + }, + "peerDependencies": { + "@aws-sdk/client-sts": "^3.654.0" + } + }, + "node_modules/@aws-sdk/client-sts": { + "version": "3.654.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/client-sts/-/client-sts-3.654.0.tgz", + "integrity": "sha512-tyHa8jsBy+/NQZFHm6Q2Q09Vi9p3EH4yPy6PU8yPewpi2klreObtrUd0anJa6nzjS9SSuqnlZWsRic3cQ4QwCg==", + "optional": true, + "dependencies": { + "@aws-crypto/sha256-browser": "5.2.0", + "@aws-crypto/sha256-js": "5.2.0", + "@aws-sdk/client-sso-oidc": "3.654.0", + "@aws-sdk/core": "3.654.0", + "@aws-sdk/credential-provider-node": "3.654.0", + "@aws-sdk/middleware-host-header": "3.654.0", + "@aws-sdk/middleware-logger": "3.654.0", + "@aws-sdk/middleware-recursion-detection": "3.654.0", + "@aws-sdk/middleware-user-agent": "3.654.0", + "@aws-sdk/region-config-resolver": "3.654.0", + "@aws-sdk/types": "3.654.0", + "@aws-sdk/util-endpoints": "3.654.0", + "@aws-sdk/util-user-agent-browser": "3.654.0", + "@aws-sdk/util-user-agent-node": "3.654.0", + "@smithy/config-resolver": "^3.0.8", + "@smithy/core": "^2.4.3", + "@smithy/fetch-http-handler": "^3.2.7", + "@smithy/hash-node": "^3.0.6", + "@smithy/invalid-dependency": "^3.0.6", + "@smithy/middleware-content-length": "^3.0.8", + "@smithy/middleware-endpoint": "^3.1.3", + "@smithy/middleware-retry": "^3.0.18", + "@smithy/middleware-serde": "^3.0.6", + "@smithy/middleware-stack": "^3.0.6", + "@smithy/node-config-provider": "^3.1.7", + "@smithy/node-http-handler": "^3.2.2", + "@smithy/protocol-http": "^4.1.3", + "@smithy/smithy-client": "^3.3.2", + "@smithy/types": "^3.4.2", + "@smithy/url-parser": "^3.0.6", + "@smithy/util-base64": "^3.0.0", + "@smithy/util-body-length-browser": "^3.0.0", + "@smithy/util-body-length-node": "^3.0.0", + "@smithy/util-defaults-mode-browser": "^3.0.18", + "@smithy/util-defaults-mode-node": "^3.0.18", + "@smithy/util-endpoints": "^2.1.2", + "@smithy/util-middleware": "^3.0.6", + "@smithy/util-retry": "^3.0.6", + "@smithy/util-utf8": "^3.0.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@aws-sdk/core": { + "version": "3.654.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/core/-/core-3.654.0.tgz", + "integrity": "sha512-4Rwx7BVaNaFqmXBDmnOkMbyuIFFbpZ+ru4lr660p45zY1QoNNSalechfoRffcokLFOZO+VWEJkdcorPUUU993w==", + "optional": true, + "dependencies": { + "@smithy/core": "^2.4.3", + "@smithy/node-config-provider": "^3.1.7", + "@smithy/property-provider": "^3.1.6", + "@smithy/protocol-http": "^4.1.3", + "@smithy/signature-v4": "^4.1.3", + "@smithy/smithy-client": "^3.3.2", + "@smithy/types": "^3.4.2", + "@smithy/util-middleware": "^3.0.6", + "fast-xml-parser": "4.4.1", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@aws-sdk/credential-provider-cognito-identity": { + "version": "3.654.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-cognito-identity/-/credential-provider-cognito-identity-3.654.0.tgz", + "integrity": "sha512-0aq4Ri9VYjixS7AZKNmuJc/5MlQdfrkgtzHV1TBisoroi/ed1WWnZmQvUFi3ZqRkt1Cvi7oZi6J1gZEfzq8p8g==", + "optional": true, + "dependencies": { + "@aws-sdk/client-cognito-identity": "3.654.0", + "@aws-sdk/types": "3.654.0", + "@smithy/property-provider": "^3.1.6", + "@smithy/types": "^3.4.2", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@aws-sdk/credential-provider-env": { + "version": "3.654.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-env/-/credential-provider-env-3.654.0.tgz", + "integrity": "sha512-kogsx3Ql81JouHS7DkheCDU9MYAvK0AokxjcshDveGmf7BbgbWCA8Fnb9wjQyNDaOXNvkZu8Z8rgkX91z324/w==", + "optional": true, + "dependencies": { + "@aws-sdk/types": "3.654.0", + "@smithy/property-provider": "^3.1.6", + "@smithy/types": "^3.4.2", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@aws-sdk/credential-provider-http": { + "version": "3.654.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-http/-/credential-provider-http-3.654.0.tgz", + "integrity": "sha512-tgmAH4MBi/aDR882lfw48+tDV95ZH3GWc1Eoe6DpNLiM3GN2VfU/cZwuHmi6aq+vAbdIlswBHJ/+va0fOvlyjw==", + "optional": true, + "dependencies": { + "@aws-sdk/types": "3.654.0", + "@smithy/fetch-http-handler": "^3.2.7", + "@smithy/node-http-handler": "^3.2.2", + "@smithy/property-provider": "^3.1.6", + "@smithy/protocol-http": "^4.1.3", + "@smithy/smithy-client": "^3.3.2", + "@smithy/types": "^3.4.2", + "@smithy/util-stream": "^3.1.6", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@aws-sdk/credential-provider-ini": { + "version": "3.654.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-ini/-/credential-provider-ini-3.654.0.tgz", + "integrity": "sha512-DKSdaNu2hwdmuvnm9KnA0NLqMWxxmxSOLWjSUSoFIm++wGXUjPrRMFYKvMktaXnPuyf5my8gF/yGbwzPZ8wlTg==", + "optional": true, + "dependencies": { + "@aws-sdk/credential-provider-env": "3.654.0", + "@aws-sdk/credential-provider-http": "3.654.0", + "@aws-sdk/credential-provider-process": "3.654.0", + "@aws-sdk/credential-provider-sso": "3.654.0", + "@aws-sdk/credential-provider-web-identity": "3.654.0", + "@aws-sdk/types": "3.654.0", + "@smithy/credential-provider-imds": "^3.2.3", + "@smithy/property-provider": "^3.1.6", + "@smithy/shared-ini-file-loader": "^3.1.7", + "@smithy/types": "^3.4.2", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + }, + "peerDependencies": { + "@aws-sdk/client-sts": "^3.654.0" + } + }, + "node_modules/@aws-sdk/credential-provider-node": { + "version": "3.654.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-node/-/credential-provider-node-3.654.0.tgz", + "integrity": "sha512-wPV7CNYaXDEc+SS+3R0v8SZwkHRUE1z2k2j1d49tH5QBDT4tb/k2V/biXWkwSk3hbR+IMWXmuhJDv/5lybhIvg==", + "optional": true, + "dependencies": { + "@aws-sdk/credential-provider-env": "3.654.0", + "@aws-sdk/credential-provider-http": "3.654.0", + "@aws-sdk/credential-provider-ini": "3.654.0", + "@aws-sdk/credential-provider-process": "3.654.0", + "@aws-sdk/credential-provider-sso": "3.654.0", + "@aws-sdk/credential-provider-web-identity": "3.654.0", + "@aws-sdk/types": "3.654.0", + "@smithy/credential-provider-imds": "^3.2.3", + "@smithy/property-provider": "^3.1.6", + "@smithy/shared-ini-file-loader": "^3.1.7", + "@smithy/types": "^3.4.2", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@aws-sdk/credential-provider-process": { + "version": "3.654.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-process/-/credential-provider-process-3.654.0.tgz", + "integrity": "sha512-PmQoo8sZ9Q2Ow8OMzK++Z9lI7MsRUG7sNq3E72DVA215dhtTICTDQwGlXH2AAmIp7n+G9LLRds+4wo2ehG4mkg==", + "optional": true, + "dependencies": { + "@aws-sdk/types": "3.654.0", + "@smithy/property-provider": "^3.1.6", + "@smithy/shared-ini-file-loader": "^3.1.7", + "@smithy/types": "^3.4.2", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@aws-sdk/credential-provider-sso": { + "version": "3.654.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-sso/-/credential-provider-sso-3.654.0.tgz", + "integrity": "sha512-7GFme6fWEdA/XYKzZPOAdj/jS6fMBy1NdSIZsDXikS0v9jU+ZzHrAaWt13YLzHyjgxB9Sg9id9ncdY1IiubQXQ==", + "optional": true, + "dependencies": { + "@aws-sdk/client-sso": "3.654.0", + "@aws-sdk/token-providers": "3.654.0", + "@aws-sdk/types": "3.654.0", + "@smithy/property-provider": "^3.1.6", + "@smithy/shared-ini-file-loader": "^3.1.7", + "@smithy/types": "^3.4.2", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@aws-sdk/credential-provider-web-identity": { + "version": "3.654.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-web-identity/-/credential-provider-web-identity-3.654.0.tgz", + "integrity": "sha512-6a2g9gMtZToqSu+CusjNK5zvbLJahQ9di7buO3iXgbizXpLXU1rnawCpWxwslMpT5fLgMSKDnKDrr6wdEk7jSw==", + "optional": true, + "dependencies": { + "@aws-sdk/types": "3.654.0", + "@smithy/property-provider": "^3.1.6", + "@smithy/types": "^3.4.2", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + }, + "peerDependencies": { + "@aws-sdk/client-sts": "^3.654.0" + } + }, + "node_modules/@aws-sdk/credential-providers": { + "version": "3.654.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-providers/-/credential-providers-3.654.0.tgz", + "integrity": "sha512-e9ZDKnmXOMOQW9e3RQyaLUcerZFzHCickRSPoSxAsGKnrhH/ltIm9Od3uyVILl1TGJoOCxVDMBE9nPfl+vNRzQ==", + "optional": true, + "dependencies": { + "@aws-sdk/client-cognito-identity": "3.654.0", + "@aws-sdk/client-sso": "3.654.0", + "@aws-sdk/client-sts": "3.654.0", + "@aws-sdk/credential-provider-cognito-identity": "3.654.0", + "@aws-sdk/credential-provider-env": "3.654.0", + "@aws-sdk/credential-provider-http": "3.654.0", + "@aws-sdk/credential-provider-ini": "3.654.0", + "@aws-sdk/credential-provider-node": "3.654.0", + "@aws-sdk/credential-provider-process": "3.654.0", + "@aws-sdk/credential-provider-sso": "3.654.0", + "@aws-sdk/credential-provider-web-identity": "3.654.0", + "@aws-sdk/types": "3.654.0", + "@smithy/credential-provider-imds": "^3.2.3", + "@smithy/property-provider": "^3.1.6", + "@smithy/types": "^3.4.2", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@aws-sdk/middleware-host-header": { + "version": "3.654.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-host-header/-/middleware-host-header-3.654.0.tgz", + "integrity": "sha512-rxGgVHWKp8U2ubMv+t+vlIk7QYUaRCHaVpmUlJv0Wv6Q0KeO9a42T9FxHphjOTlCGQOLcjCreL9CF8Qhtb4mdQ==", + "optional": true, + "dependencies": { + "@aws-sdk/types": "3.654.0", + "@smithy/protocol-http": "^4.1.3", + "@smithy/types": "^3.4.2", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@aws-sdk/middleware-logger": { + "version": "3.654.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-logger/-/middleware-logger-3.654.0.tgz", + "integrity": "sha512-OQYb+nWlmASyXfRb989pwkJ9EVUMP1CrKn2eyTk3usl20JZmKo2Vjis6I0tLUkMSxMhnBJJlQKyWkRpD/u1FVg==", + "optional": true, + "dependencies": { + "@aws-sdk/types": "3.654.0", + "@smithy/types": "^3.4.2", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@aws-sdk/middleware-recursion-detection": { + "version": "3.654.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-recursion-detection/-/middleware-recursion-detection-3.654.0.tgz", + "integrity": "sha512-gKSomgltKVmsT8sC6W7CrADZ4GHwX9epk3GcH6QhebVO3LA9LRbkL3TwOPUXakxxOLLUTYdOZLIOtFf7iH00lg==", + "optional": true, + "dependencies": { + "@aws-sdk/types": "3.654.0", + "@smithy/protocol-http": "^4.1.3", + "@smithy/types": "^3.4.2", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@aws-sdk/middleware-user-agent": { + "version": "3.654.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-user-agent/-/middleware-user-agent-3.654.0.tgz", + "integrity": "sha512-liCcqPAyRsr53cy2tYu4qeH4MMN0eh9g6k56XzI5xd4SghXH5YWh4qOYAlQ8T66ZV4nPMtD8GLtLXGzsH8moFg==", + "optional": true, + "dependencies": { + "@aws-sdk/types": "3.654.0", + "@aws-sdk/util-endpoints": "3.654.0", + "@smithy/protocol-http": "^4.1.3", + "@smithy/types": "^3.4.2", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@aws-sdk/region-config-resolver": { + "version": "3.654.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/region-config-resolver/-/region-config-resolver-3.654.0.tgz", + "integrity": "sha512-ydGOrXJxj3x0sJhsXyTmvJVLAE0xxuTWFJihTl67RtaO7VRNtd82I3P3bwoMMaDn5WpmV5mPo8fEUDRlBm3fPg==", + "optional": true, + "dependencies": { + "@aws-sdk/types": "3.654.0", + "@smithy/node-config-provider": "^3.1.7", + "@smithy/types": "^3.4.2", + "@smithy/util-config-provider": "^3.0.0", + "@smithy/util-middleware": "^3.0.6", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@aws-sdk/token-providers": { + "version": "3.654.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/token-providers/-/token-providers-3.654.0.tgz", + "integrity": "sha512-D8GeJYmvbfWkQDtTB4owmIobSMexZel0fOoetwvgCQ/7L8VPph3Q2bn1TRRIXvH7wdt6DcDxA3tKMHPBkT3GlA==", + "optional": true, + "dependencies": { + "@aws-sdk/types": "3.654.0", + "@smithy/property-provider": "^3.1.6", + "@smithy/shared-ini-file-loader": "^3.1.7", + "@smithy/types": "^3.4.2", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + }, + "peerDependencies": { + "@aws-sdk/client-sso-oidc": "^3.654.0" + } + }, + "node_modules/@aws-sdk/types": { + "version": "3.654.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/types/-/types-3.654.0.tgz", + "integrity": "sha512-VWvbED3SV+10QJIcmU/PKjsKilsTV16d1I7/on4bvD/jo1qGeMXqLDBSen3ks/tuvXZF/mFc7ZW/W2DiLVtO7A==", + "optional": true, + "dependencies": { + "@smithy/types": "^3.4.2", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@aws-sdk/util-endpoints": { + "version": "3.654.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/util-endpoints/-/util-endpoints-3.654.0.tgz", + "integrity": "sha512-i902fcBknHs0Irgdpi62+QMvzxE+bczvILXigYrlHL4+PiEnlMVpni5L5W1qCkNZXf8AaMrSBuR1NZAGp6UOUw==", + "optional": true, + "dependencies": { + "@aws-sdk/types": "3.654.0", + "@smithy/types": "^3.4.2", + "@smithy/util-endpoints": "^2.1.2", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@aws-sdk/util-locate-window": { + "version": "3.568.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/util-locate-window/-/util-locate-window-3.568.0.tgz", + "integrity": "sha512-3nh4TINkXYr+H41QaPelCceEB2FXP3fxp93YZXB/kqJvX0U9j0N0Uk45gvsjmEPzG8XxkPEeLIfT2I1M7A6Lig==", + "optional": true, + "dependencies": { + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@aws-sdk/util-user-agent-browser": { + "version": "3.654.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/util-user-agent-browser/-/util-user-agent-browser-3.654.0.tgz", + "integrity": "sha512-ykYAJqvnxLt7wfrqya28wuH3/7NdrwzfiFd7NqEVQf7dXVxL5RPEpD7DxjcyQo3DsHvvdUvGZVaQhozycn1pzA==", + "optional": true, + "dependencies": { + "@aws-sdk/types": "3.654.0", + "@smithy/types": "^3.4.2", + "bowser": "^2.11.0", + "tslib": "^2.6.2" + } + }, + "node_modules/@aws-sdk/util-user-agent-node": { + "version": "3.654.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/util-user-agent-node/-/util-user-agent-node-3.654.0.tgz", + "integrity": "sha512-a0ojjdBN6pqv6gB4H/QPPSfhs7mFtlVwnmKCM/QrTaFzN0U810PJ1BST3lBx5sa23I5jWHGaoFY+5q65C3clLQ==", + "optional": true, + "dependencies": { + "@aws-sdk/types": "3.654.0", + "@smithy/node-config-provider": "^3.1.7", + "@smithy/types": "^3.4.2", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + }, + "peerDependencies": { + "aws-crt": ">=1.0.0" + }, + "peerDependenciesMeta": { + "aws-crt": { + "optional": true + } + } + }, + "node_modules/@babel/code-frame": { + "version": "7.24.7", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.24.7.tgz", + "integrity": "sha512-BcYH1CVJBO9tvyIZ2jVeXgSIMvGZ2FDRvDdOIVQyuklNKSsx+eppDEBq/g47Ayw+RqNFE+URvOShmf+f/qwAlA==", + "license": "MIT", + "dependencies": { + "@babel/highlight": "^7.24.7", + "picocolors": "^1.0.0" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/compat-data": { + "version": "7.25.4", + "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.25.4.tgz", + "integrity": "sha512-+LGRog6RAsCJrrrg/IO6LGmpphNe5DiK30dGjCoxxeGv49B10/3XYGxPsAwrDlMFcFEvdAUavDT8r9k/hSyQqQ==", + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/core": { + "version": "7.25.2", + "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.25.2.tgz", + "integrity": "sha512-BBt3opiCOxUr9euZ5/ro/Xv8/V7yJ5bjYMqG/C1YAo8MIKAnumZalCN+msbci3Pigy4lIQfPUpfMM27HMGaYEA==", + "license": "MIT", + "dependencies": { + "@ampproject/remapping": "^2.2.0", + "@babel/code-frame": "^7.24.7", + "@babel/generator": "^7.25.0", + "@babel/helper-compilation-targets": "^7.25.2", + "@babel/helper-module-transforms": "^7.25.2", + "@babel/helpers": "^7.25.0", + "@babel/parser": "^7.25.0", + "@babel/template": "^7.25.0", + "@babel/traverse": "^7.25.2", + "@babel/types": "^7.25.2", + "convert-source-map": "^2.0.0", + "debug": "^4.1.0", + "gensync": "^1.0.0-beta.2", + "json5": "^2.2.3", + "semver": "^6.3.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/babel" + } + }, + "node_modules/@babel/core/node_modules/debug": { + "version": "4.3.7", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.7.tgz", + "integrity": "sha512-Er2nc/H7RrMXZBFCEim6TCmMk02Z8vLC2Rbi1KEBggpo0fS6l0S1nnapwmIi3yW/+GOJap1Krg4w0Hg80oCqgQ==", + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/@babel/core/node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "license": "MIT" + }, + "node_modules/@babel/core/node_modules/semver": { + "version": "6.3.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", + "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + } + }, + "node_modules/@babel/generator": { + "version": "7.25.6", + "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.25.6.tgz", + "integrity": "sha512-VPC82gr1seXOpkjAAKoLhP50vx4vGNlF4msF64dSFq1P8RfB+QAuJWGHPXXPc8QyfVWwwB/TNNU4+ayZmHNbZw==", + "license": "MIT", + "dependencies": { + "@babel/types": "^7.25.6", + "@jridgewell/gen-mapping": "^0.3.5", + "@jridgewell/trace-mapping": "^0.3.25", + "jsesc": "^2.5.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/generator/node_modules/@jridgewell/trace-mapping": { + "version": "0.3.25", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.25.tgz", + "integrity": "sha512-vNk6aEwybGtawWmy/PzwnGDOjCkLWSD2wqvjGGAgOAwCGWySYXfYoxt00IJkTF+8Lb57DwOb3Aa0o9CApepiYQ==", + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, + "node_modules/@babel/helper-compilation-targets": { + "version": "7.25.2", + "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.25.2.tgz", + "integrity": "sha512-U2U5LsSaZ7TAt3cfaymQ8WHh0pxvdHoEk6HVpaexxixjyEquMh0L0YNJNM6CTGKMXV1iksi0iZkGw4AcFkPaaw==", + "license": "MIT", + "dependencies": { + "@babel/compat-data": "^7.25.2", + "@babel/helper-validator-option": "^7.24.8", + "browserslist": "^4.23.1", + "lru-cache": "^5.1.1", + "semver": "^6.3.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-compilation-targets/node_modules/lru-cache": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz", + "integrity": "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==", + "license": "ISC", + "dependencies": { + "yallist": "^3.0.2" + } + }, + "node_modules/@babel/helper-compilation-targets/node_modules/semver": { + "version": "6.3.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", + "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + } + }, + "node_modules/@babel/helper-module-imports": { + "version": "7.24.7", + "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.24.7.tgz", + "integrity": "sha512-8AyH3C+74cgCVVXow/myrynrAGv+nTVg5vKu2nZph9x7RcRwzmh0VFallJuFTZ9mx6u4eSdXZfcOzSqTUm0HCA==", + "license": "MIT", + "dependencies": { + "@babel/traverse": "^7.24.7", + "@babel/types": "^7.24.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-module-transforms": { + "version": "7.25.2", + "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.25.2.tgz", + "integrity": "sha512-BjyRAbix6j/wv83ftcVJmBt72QtHI56C7JXZoG2xATiLpmoC7dpd8WnkikExHDVPpi/3qCmO6WY1EaXOluiecQ==", + "license": "MIT", + "dependencies": { + "@babel/helper-module-imports": "^7.24.7", + "@babel/helper-simple-access": "^7.24.7", + "@babel/helper-validator-identifier": "^7.24.7", + "@babel/traverse": "^7.25.2" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0" + } + }, + "node_modules/@babel/helper-plugin-utils": { + "version": "7.24.8", + "resolved": "https://registry.npmjs.org/@babel/helper-plugin-utils/-/helper-plugin-utils-7.24.8.tgz", + "integrity": "sha512-FFWx5142D8h2Mgr/iPVGH5G7w6jDn4jUSpZTyDnQO0Yn7Ks2Kuz6Pci8H6MPCoUJegd/UZQ3tAvfLCxQSnWWwg==", + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-simple-access": { + "version": "7.24.7", + "resolved": "https://registry.npmjs.org/@babel/helper-simple-access/-/helper-simple-access-7.24.7.tgz", + "integrity": "sha512-zBAIvbCMh5Ts+b86r/CjU+4XGYIs+R1j951gxI3KmmxBMhCg4oQMsv6ZXQ64XOm/cvzfU1FmoCyt6+owc5QMYg==", + "license": "MIT", + "dependencies": { + "@babel/traverse": "^7.24.7", + "@babel/types": "^7.24.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-string-parser": { + "version": "7.24.8", + "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.24.8.tgz", + "integrity": "sha512-pO9KhhRcuUyGnJWwyEgnRJTSIZHiT+vMD0kPeD+so0l7mxkMT19g3pjY9GTnHySck/hDzq+dtW/4VgnMkippsQ==", + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-identifier": { + "version": "7.24.7", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.24.7.tgz", + "integrity": "sha512-rR+PBcQ1SMQDDyF6X0wxtG8QyLCgUB0eRAGguqRLfkCA87l7yAP7ehq8SNj96OOGTO8OBV70KhuFYcIkHXOg0w==", + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-option": { + "version": "7.24.8", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-option/-/helper-validator-option-7.24.8.tgz", + "integrity": "sha512-xb8t9tD1MHLungh/AIoWYN+gVHaB9kwlu8gffXGSt3FFEIT7RjS+xWbc2vUD1UTZdIpKj/ab3rdqJ7ufngyi2Q==", + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helpers": { + "version": "7.25.6", + "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.25.6.tgz", + "integrity": "sha512-Xg0tn4HcfTijTwfDwYlvVCl43V6h4KyVVX2aEm4qdO/PC6L2YvzLHFdmxhoeSA3eslcE6+ZVXHgWwopXYLNq4Q==", + "license": "MIT", + "dependencies": { + "@babel/template": "^7.25.0", + "@babel/types": "^7.25.6" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/highlight": { + "version": "7.24.7", + "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.24.7.tgz", + "integrity": "sha512-EStJpq4OuY8xYfhGVXngigBJRWxftKX9ksiGDnmlY3o7B/V7KIAc9X4oiK87uPJSc/vs5L869bem5fhZa8caZw==", + "license": "MIT", + "dependencies": { + "@babel/helper-validator-identifier": "^7.24.7", + "chalk": "^2.4.2", + "js-tokens": "^4.0.0", + "picocolors": "^1.0.0" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/highlight/node_modules/ansi-styles": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", + "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", + "license": "MIT", + "dependencies": { + "color-convert": "^1.9.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/@babel/highlight/node_modules/chalk": { + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", + "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", + "license": "MIT", + "dependencies": { + "ansi-styles": "^3.2.1", + "escape-string-regexp": "^1.0.5", + "supports-color": "^5.3.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/@babel/highlight/node_modules/color-convert": { + "version": "1.9.3", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz", + "integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==", + "license": "MIT", + "dependencies": { + "color-name": "1.1.3" + } + }, + "node_modules/@babel/highlight/node_modules/color-name": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz", + "integrity": "sha512-72fSenhMw2HZMTVHeCA9KCmpEIbzWiQsjN+BHcBbS9vr1mtt+vJjPdksIBNUmKAW8TFUDPJK5SUU3QhE9NEXDw==", + "license": "MIT" + }, + "node_modules/@babel/highlight/node_modules/escape-string-regexp": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", + "integrity": "sha512-vbRorB5FUQWvla16U8R/qgaFIya2qGzwDrNmCZuYKrbdSUMG6I1ZCGQRefkRVhuOkIGVne7BQ35DSfo1qvJqFg==", + "license": "MIT", + "engines": { + "node": ">=0.8.0" + } + }, + "node_modules/@babel/parser": { + "version": "7.25.6", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.25.6.tgz", + "integrity": "sha512-trGdfBdbD0l1ZPmcJ83eNxB9rbEax4ALFTF7fN386TMYbeCQbyme5cOEXQhbGXKebwGaB/J52w1mrklMcbgy6Q==", + "license": "MIT", + "dependencies": { + "@babel/types": "^7.25.6" + }, + "bin": { + "parser": "bin/babel-parser.js" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@babel/plugin-syntax-async-generators": { + "version": "7.8.4", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-async-generators/-/plugin-syntax-async-generators-7.8.4.tgz", + "integrity": "sha512-tycmZxkGfZaxhMRbXlPXuVFpdWlXpir2W4AMhSJgRKzk/eDlIXOhb2LHWoLpDF7TEHylV5zNhykX6KAgHJmTNw==", + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.8.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-bigint": { + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-bigint/-/plugin-syntax-bigint-7.8.3.tgz", + "integrity": "sha512-wnTnFlG+YxQm3vDxpGE57Pj0srRU4sHE/mDkt1qv2YJJSeUAec2ma4WLUnUPeKjyrfntVwe/N6dCXpU+zL3Npg==", + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.8.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-class-properties": { + "version": "7.12.13", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-class-properties/-/plugin-syntax-class-properties-7.12.13.tgz", + "integrity": "sha512-fm4idjKla0YahUNgFNLCB0qySdsoPiZP3iQE3rky0mBUtMZ23yDJ9SJdg6dXTSDnulOVqiF3Hgr9nbXvXTQZYA==", + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.12.13" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-class-static-block": { + "version": "7.14.5", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-class-static-block/-/plugin-syntax-class-static-block-7.14.5.tgz", + "integrity": "sha512-b+YyPmr6ldyNnM6sqYeMWE+bgJcJpO6yS4QD7ymxgH34GBPNDM/THBh8iunyvKIZztiwLH4CJZ0RxTk9emgpjw==", + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.14.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-import-attributes": { + "version": "7.25.6", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-import-attributes/-/plugin-syntax-import-attributes-7.25.6.tgz", + "integrity": "sha512-sXaDXaJN9SNLymBdlWFA+bjzBhFD617ZaFiY13dGt7TVslVvVgA6fkZOP7Ki3IGElC45lwHdOTrCtKZGVAWeLQ==", + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.24.8" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-import-meta": { + "version": "7.10.4", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-import-meta/-/plugin-syntax-import-meta-7.10.4.tgz", + "integrity": "sha512-Yqfm+XDx0+Prh3VSeEQCPU81yC+JWZ2pDPFSS4ZdpfZhp4MkFMaDC1UqseovEKwSUpnIL7+vK+Clp7bfh0iD7g==", + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.10.4" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-json-strings": { + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-json-strings/-/plugin-syntax-json-strings-7.8.3.tgz", + "integrity": "sha512-lY6kdGpWHvjoe2vk4WrAapEuBR69EMxZl+RoGRhrFGNYVK8mOPAW8VfbT/ZgrFbXlDNiiaxQnAtgVCZ6jv30EA==", + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.8.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-jsx": { + "version": "7.24.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-jsx/-/plugin-syntax-jsx-7.24.7.tgz", + "integrity": "sha512-6ddciUPe/mpMnOKv/U+RSd2vvVy+Yw/JfBB0ZHYjEZt9NLHmCUylNYlsbqCCS1Bffjlb0fCwC9Vqz+sBz6PsiQ==", + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.24.7" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-logical-assignment-operators": { + "version": "7.10.4", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-logical-assignment-operators/-/plugin-syntax-logical-assignment-operators-7.10.4.tgz", + "integrity": "sha512-d8waShlpFDinQ5MtvGU9xDAOzKH47+FFoney2baFIoMr952hKOLp1HR7VszoZvOsV/4+RRszNY7D17ba0te0ig==", + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.10.4" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-nullish-coalescing-operator": { + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-nullish-coalescing-operator/-/plugin-syntax-nullish-coalescing-operator-7.8.3.tgz", + "integrity": "sha512-aSff4zPII1u2QD7y+F8oDsz19ew4IGEJg9SVW+bqwpwtfFleiQDMdzA/R+UlWDzfnHFCxxleFT0PMIrR36XLNQ==", + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.8.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-numeric-separator": { + "version": "7.10.4", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-numeric-separator/-/plugin-syntax-numeric-separator-7.10.4.tgz", + "integrity": "sha512-9H6YdfkcK/uOnY/K7/aA2xpzaAgkQn37yzWUMRK7OaPOqOpGS1+n0H5hxT9AUw9EsSjPW8SVyMJwYRtWs3X3ug==", + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.10.4" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-object-rest-spread": { + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-object-rest-spread/-/plugin-syntax-object-rest-spread-7.8.3.tgz", + "integrity": "sha512-XoqMijGZb9y3y2XskN+P1wUGiVwWZ5JmoDRwx5+3GmEplNyVM2s2Dg8ILFQm8rWM48orGy5YpI5Bl8U1y7ydlA==", + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.8.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-optional-catch-binding": { + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-optional-catch-binding/-/plugin-syntax-optional-catch-binding-7.8.3.tgz", + "integrity": "sha512-6VPD0Pc1lpTqw0aKoeRTMiB+kWhAoT24PA+ksWSBrFtl5SIRVpZlwN3NNPQjehA2E/91FV3RjLWoVTglWcSV3Q==", + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.8.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-optional-chaining": { + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-optional-chaining/-/plugin-syntax-optional-chaining-7.8.3.tgz", + "integrity": "sha512-KoK9ErH1MBlCPxV0VANkXW2/dw4vlbGDrFgz8bmUsBGYkFRcbRwMh6cIJubdPrkxRwuGdtCk0v/wPTKbQgBjkg==", + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.8.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-private-property-in-object": { + "version": "7.14.5", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-private-property-in-object/-/plugin-syntax-private-property-in-object-7.14.5.tgz", + "integrity": "sha512-0wVnp9dxJ72ZUJDV27ZfbSj6iHLoytYZmh3rFcxNnvsJF3ktkzLDZPy/mA17HGsaQT3/DQsWYX1f1QGWkCoVUg==", + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.14.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-top-level-await": { + "version": "7.14.5", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-top-level-await/-/plugin-syntax-top-level-await-7.14.5.tgz", + "integrity": "sha512-hx++upLv5U1rgYfwe1xBQUhRmU41NEvpUvrp8jkrSCdvGSnM5/qdRMtylJ6PG5OFkBaHkbTAKTnd3/YyESRHFw==", + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.14.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-typescript": { + "version": "7.25.4", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-typescript/-/plugin-syntax-typescript-7.25.4.tgz", + "integrity": "sha512-uMOCoHVU52BsSWxPOMVv5qKRdeSlPuImUCB2dlPuBSU+W2/ROE7/Zg8F2Kepbk+8yBa68LlRKxO+xgEVWorsDg==", + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.24.8" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/template": { + "version": "7.25.0", + "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.25.0.tgz", + "integrity": "sha512-aOOgh1/5XzKvg1jvVz7AVrx2piJ2XBi227DHmbY6y+bM9H2FlN+IfecYu4Xl0cNiiVejlsCri89LUsbj8vJD9Q==", + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.24.7", + "@babel/parser": "^7.25.0", + "@babel/types": "^7.25.0" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/traverse": { + "version": "7.25.6", + "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.25.6.tgz", + "integrity": "sha512-9Vrcx5ZW6UwK5tvqsj0nGpp/XzqthkT0dqIc9g1AdtygFToNtTF67XzYS//dm+SAK9cp3B9R4ZO/46p63SCjlQ==", + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.24.7", + "@babel/generator": "^7.25.6", + "@babel/parser": "^7.25.6", + "@babel/template": "^7.25.0", + "@babel/types": "^7.25.6", + "debug": "^4.3.1", + "globals": "^11.1.0" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/traverse/node_modules/debug": { + "version": "4.3.7", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.7.tgz", + "integrity": "sha512-Er2nc/H7RrMXZBFCEim6TCmMk02Z8vLC2Rbi1KEBggpo0fS6l0S1nnapwmIi3yW/+GOJap1Krg4w0Hg80oCqgQ==", + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/@babel/traverse/node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "license": "MIT" + }, + "node_modules/@babel/types": { + "version": "7.25.6", + "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.25.6.tgz", + "integrity": "sha512-/l42B1qxpG6RdfYf343Uw1vmDjeNhneUXtzhojE7pDgfpEypmRhI6j1kr17XCVv4Cgl9HdAiQY2x0GwKm7rWCw==", + "license": "MIT", + "dependencies": { + "@babel/helper-string-parser": "^7.24.8", + "@babel/helper-validator-identifier": "^7.24.7", + "to-fast-properties": "^2.0.0" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@bcoe/v8-coverage": { + "version": "0.2.3", + "resolved": "https://registry.npmjs.org/@bcoe/v8-coverage/-/v8-coverage-0.2.3.tgz", + "integrity": "sha512-0hYQ8SB4Db5zvZB4axdMHGwEaQjkZzFjQiN9LVYvIFB2nSUHW9tYpxWriPrWDASIxiaXax83REcLxuSdnGPZtw==", + "license": "MIT" + }, + "node_modules/@cspotcode/source-map-support": { + "version": "0.8.1", + "resolved": "https://registry.npmjs.org/@cspotcode/source-map-support/-/source-map-support-0.8.1.tgz", + "integrity": "sha512-IchNf6dN4tHoMFIn/7OE8LWZ19Y6q/67Bmf6vnGREv8RSbBVb9LPJxEcnwrcwX6ixSvaiGoomAUvu4YSxXrVgw==", + "dependencies": { + "@jridgewell/trace-mapping": "0.3.9" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.23.1", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.23.1.tgz", + "integrity": "sha512-6VhYk1diRqrhBAqpJEdjASR/+WVRtfjpqKuNw11cLiaWpAT/Uu+nokB+UJnevzy/P9C/ty6AOe0dwueMrGh/iQ==", + "cpu": [ + "ppc64" + ], + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.23.1", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.23.1.tgz", + "integrity": "sha512-uz6/tEy2IFm9RYOyvKl88zdzZfwEfKZmnX9Cj1BHjeSGNuGLuMD1kR8y5bteYmwqKm1tj8m4cb/aKEorr6fHWQ==", + "cpu": [ + "arm" + ], + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.23.1", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.23.1.tgz", + "integrity": "sha512-xw50ipykXcLstLeWH7WRdQuysJqejuAGPd30vd1i5zSyKK3WE+ijzHmLKxdiCMtH1pHz78rOg0BKSYOSB/2Khw==", + "cpu": [ + "arm64" + ], + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.23.1", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.23.1.tgz", + "integrity": "sha512-nlN9B69St9BwUoB+jkyU090bru8L0NA3yFvAd7k8dNsVH8bi9a8cUAUSEcEEgTp2z3dbEDGJGfP6VUnkQnlReg==", + "cpu": [ + "x64" + ], + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.23.1", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.23.1.tgz", + "integrity": "sha512-YsS2e3Wtgnw7Wq53XXBLcV6JhRsEq8hkfg91ESVadIrzr9wO6jJDMZnCQbHm1Guc5t/CdDiFSSfWP58FNuvT3Q==", + "cpu": [ + "arm64" + ], + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.23.1", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.23.1.tgz", + "integrity": "sha512-aClqdgTDVPSEGgoCS8QDG37Gu8yc9lTHNAQlsztQ6ENetKEO//b8y31MMu2ZaPbn4kVsIABzVLXYLhCGekGDqw==", + "cpu": [ + "x64" + ], + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.23.1", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.23.1.tgz", + "integrity": "sha512-h1k6yS8/pN/NHlMl5+v4XPfikhJulk4G+tKGFIOwURBSFzE8bixw1ebjluLOjfwtLqY0kewfjLSrO6tN2MgIhA==", + "cpu": [ + "arm64" + ], + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.23.1", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.23.1.tgz", + "integrity": "sha512-lK1eJeyk1ZX8UklqFd/3A60UuZ/6UVfGT2LuGo3Wp4/z7eRTRYY+0xOu2kpClP+vMTi9wKOfXi2vjUpO1Ro76g==", + "cpu": [ + "x64" + ], + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.23.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.23.1.tgz", + "integrity": "sha512-CXXkzgn+dXAPs3WBwE+Kvnrf4WECwBdfjfeYHpMeVxWE0EceB6vhWGShs6wi0IYEqMSIzdOF1XjQ/Mkm5d7ZdQ==", + "cpu": [ + "arm" + ], + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.23.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.23.1.tgz", + "integrity": "sha512-/93bf2yxencYDnItMYV/v116zff6UyTjo4EtEQjUBeGiVpMmffDNUyD9UN2zV+V3LRV3/on4xdZ26NKzn6754g==", + "cpu": [ + "arm64" + ], + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.23.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.23.1.tgz", + "integrity": "sha512-VTN4EuOHwXEkXzX5nTvVY4s7E/Krz7COC8xkftbbKRYAl96vPiUssGkeMELQMOnLOJ8k3BY1+ZY52tttZnHcXQ==", + "cpu": [ + "ia32" + ], + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.23.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.23.1.tgz", + "integrity": "sha512-Vx09LzEoBa5zDnieH8LSMRToj7ir/Jeq0Gu6qJ/1GcBq9GkfoEAoXvLiW1U9J1qE/Y/Oyaq33w5p2ZWrNNHNEw==", + "cpu": [ + "loong64" + ], + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.23.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.23.1.tgz", + "integrity": "sha512-nrFzzMQ7W4WRLNUOU5dlWAqa6yVeI0P78WKGUo7lg2HShq/yx+UYkeNSE0SSfSure0SqgnsxPvmAUu/vu0E+3Q==", + "cpu": [ + "mips64el" + ], + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.23.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.23.1.tgz", + "integrity": "sha512-dKN8fgVqd0vUIjxuJI6P/9SSSe/mB9rvA98CSH2sJnlZ/OCZWO1DJvxj8jvKTfYUdGfcq2dDxoKaC6bHuTlgcw==", + "cpu": [ + "ppc64" + ], + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.23.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.23.1.tgz", + "integrity": "sha512-5AV4Pzp80fhHL83JM6LoA6pTQVWgB1HovMBsLQ9OZWLDqVY8MVobBXNSmAJi//Csh6tcY7e7Lny2Hg1tElMjIA==", + "cpu": [ + "riscv64" + ], + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.23.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.23.1.tgz", + "integrity": "sha512-9ygs73tuFCe6f6m/Tb+9LtYxWR4c9yg7zjt2cYkjDbDpV/xVn+68cQxMXCjUpYwEkze2RcU/rMnfIXNRFmSoDw==", + "cpu": [ + "s390x" + ], + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.23.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.23.1.tgz", + "integrity": "sha512-EV6+ovTsEXCPAp58g2dD68LxoP/wK5pRvgy0J/HxPGB009omFPv3Yet0HiaqvrIrgPTBuC6wCH1LTOY91EO5hQ==", + "cpu": [ + "x64" + ], + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.23.1", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.23.1.tgz", + "integrity": "sha512-aevEkCNu7KlPRpYLjwmdcuNz6bDFiE7Z8XC4CPqExjTvrHugh28QzUXVOZtiYghciKUacNktqxdpymplil1beA==", + "cpu": [ + "x64" + ], + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.23.1", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.23.1.tgz", + "integrity": "sha512-3x37szhLexNA4bXhLrCC/LImN/YtWis6WXr1VESlfVtVeoFJBRINPJ3f0a/6LV8zpikqoUg4hyXw0sFBt5Cr+Q==", + "cpu": [ + "arm64" + ], + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.23.1", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.23.1.tgz", + "integrity": "sha512-aY2gMmKmPhxfU+0EdnN+XNtGbjfQgwZj43k8G3fyrDM/UdZww6xrWxmDkuz2eCZchqVeABjV5BpildOrUbBTqA==", + "cpu": [ + "x64" + ], + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.23.1", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.23.1.tgz", + "integrity": "sha512-RBRT2gqEl0IKQABT4XTj78tpk9v7ehp+mazn2HbUeZl1YMdaGAQqhapjGTCe7uw7y0frDi4gS0uHzhvpFuI1sA==", + "cpu": [ + "x64" + ], + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.23.1", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.23.1.tgz", + "integrity": "sha512-4O+gPR5rEBe2FpKOVyiJ7wNDPA8nGzDuJ6gN4okSA1gEOYZ67N8JPk58tkWtdtPeLz7lBnY6I5L3jdsr3S+A6A==", + "cpu": [ + "arm64" + ], + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.23.1", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.23.1.tgz", + "integrity": "sha512-BcaL0Vn6QwCwre3Y717nVHZbAa4UBEigzFm6VdsVdT/MbZ38xoj1X9HPkZhbmaBGUD1W8vxAfffbDe8bA6AKnQ==", + "cpu": [ + "ia32" + ], + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.23.1", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.23.1.tgz", + "integrity": "sha512-BHpFFeslkWrXWyUPnbKm+xYYVYruCinGcftSBaa8zoF9hZO4BcSCFUvHVTtzpIY6YzUnYtuEhZ+C9iEXjxnasg==", + "cpu": [ + "x64" + ], + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@isaacs/cliui": { + "version": "8.0.2", + "resolved": "https://registry.npmjs.org/@isaacs/cliui/-/cliui-8.0.2.tgz", + "integrity": "sha512-O8jcjabXaleOG9DQ0+ARXWZBTfnP4WNAqzuiJK7ll44AmxGKv/J2M4TPjxjY3znBCfvBXFzucm1twdyFybFqEA==", + "dev": true, + "dependencies": { + "string-width": "^5.1.2", + "string-width-cjs": "npm:string-width@^4.2.0", + "strip-ansi": "^7.0.1", + "strip-ansi-cjs": "npm:strip-ansi@^6.0.1", + "wrap-ansi": "^8.1.0", + "wrap-ansi-cjs": "npm:wrap-ansi@^7.0.0" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/@istanbuljs/load-nyc-config": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@istanbuljs/load-nyc-config/-/load-nyc-config-1.1.0.tgz", + "integrity": "sha512-VjeHSlIzpv/NyD3N0YuHfXOPDIixcA1q2ZV98wsMqcYlPmv2n3Yb2lYP9XMElnaFVXg5A7YLTeLu6V84uQDjmQ==", + "license": "ISC", + "dependencies": { + "camelcase": "^5.3.1", + "find-up": "^4.1.0", + "get-package-type": "^0.1.0", + "js-yaml": "^3.13.1", + "resolve-from": "^5.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/@istanbuljs/schema": { + "version": "0.1.3", + "resolved": "https://registry.npmjs.org/@istanbuljs/schema/-/schema-0.1.3.tgz", + "integrity": "sha512-ZXRY4jNvVgSVQ8DL3LTcakaAtXwTVUxE81hslsyD2AtoXW/wVob10HkOJ1X/pAlcI7D+2YoZKg5do8G/w6RYgA==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/@jest/console": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/@jest/console/-/console-29.7.0.tgz", + "integrity": "sha512-5Ni4CU7XHQi32IJ398EEP4RrB8eV09sXP2ROqD4bksHrnTree52PsxvX8tpL8LvTZ3pFzXyPbNQReSN41CAhOg==", + "license": "MIT", + "dependencies": { + "@jest/types": "^29.6.3", + "@types/node": "*", + "chalk": "^4.0.0", + "jest-message-util": "^29.7.0", + "jest-util": "^29.7.0", + "slash": "^3.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/@jest/core": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/@jest/core/-/core-29.7.0.tgz", + "integrity": "sha512-n7aeXWKMnGtDA48y8TLWJPJmLmmZ642Ceo78cYWEpiD7FzDgmNDV/GCVRorPABdXLJZ/9wzzgZAlHjXjxDHGsg==", + "license": "MIT", + "dependencies": { + "@jest/console": "^29.7.0", + "@jest/reporters": "^29.7.0", + "@jest/test-result": "^29.7.0", + "@jest/transform": "^29.7.0", + "@jest/types": "^29.6.3", + "@types/node": "*", + "ansi-escapes": "^4.2.1", + "chalk": "^4.0.0", + "ci-info": "^3.2.0", + "exit": "^0.1.2", + "graceful-fs": "^4.2.9", + "jest-changed-files": "^29.7.0", + "jest-config": "^29.7.0", + "jest-haste-map": "^29.7.0", + "jest-message-util": "^29.7.0", + "jest-regex-util": "^29.6.3", + "jest-resolve": "^29.7.0", + "jest-resolve-dependencies": "^29.7.0", + "jest-runner": "^29.7.0", + "jest-runtime": "^29.7.0", + "jest-snapshot": "^29.7.0", + "jest-util": "^29.7.0", + "jest-validate": "^29.7.0", + "jest-watcher": "^29.7.0", + "micromatch": "^4.0.4", + "pretty-format": "^29.7.0", + "slash": "^3.0.0", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "peerDependencies": { + "node-notifier": "^8.0.1 || ^9.0.0 || ^10.0.0" + }, + "peerDependenciesMeta": { + "node-notifier": { + "optional": true + } + } + }, + "node_modules/@jest/core/node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/@jest/core/node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "license": "MIT", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/@jest/environment": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/@jest/environment/-/environment-29.7.0.tgz", + "integrity": "sha512-aQIfHDq33ExsN4jP1NWGXhxgQ/wixs60gDiKO+XVMd8Mn0NWPWgc34ZQDTb2jKaUWQ7MuwoitXAsN2XVXNMpAw==", + "license": "MIT", + "dependencies": { + "@jest/fake-timers": "^29.7.0", + "@jest/types": "^29.6.3", + "@types/node": "*", + "jest-mock": "^29.7.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/@jest/expect": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/@jest/expect/-/expect-29.7.0.tgz", + "integrity": "sha512-8uMeAMycttpva3P1lBHB8VciS9V0XAr3GymPpipdyQXbBcuhkLQOSe8E/p92RyAdToS6ZD1tFkX+CkhoECE0dQ==", + "license": "MIT", + "dependencies": { + "expect": "^29.7.0", + "jest-snapshot": "^29.7.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/@jest/expect-utils": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/@jest/expect-utils/-/expect-utils-29.7.0.tgz", + "integrity": "sha512-GlsNBWiFQFCVi9QVSx7f5AgMeLxe9YCCs5PuP2O2LdjDAA8Jh9eX7lA1Jq/xdXw3Wb3hyvlFNfZIfcRetSzYcA==", + "license": "MIT", + "dependencies": { + "jest-get-type": "^29.6.3" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/@jest/fake-timers": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/@jest/fake-timers/-/fake-timers-29.7.0.tgz", + "integrity": "sha512-q4DH1Ha4TTFPdxLsqDXK1d3+ioSL7yL5oCMJZgDYm6i+6CygW5E5xVr/D1HdsGxjt1ZWSfUAs9OxSB/BNelWrQ==", + "license": "MIT", + "dependencies": { + "@jest/types": "^29.6.3", + "@sinonjs/fake-timers": "^10.0.2", + "@types/node": "*", + "jest-message-util": "^29.7.0", + "jest-mock": "^29.7.0", + "jest-util": "^29.7.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/@jest/globals": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/@jest/globals/-/globals-29.7.0.tgz", + "integrity": "sha512-mpiz3dutLbkW2MNFubUGUEVLkTGiqW6yLVTA+JbP6fI6J5iL9Y0Nlg8k95pcF8ctKwCS7WVxteBs29hhfAotzQ==", + "license": "MIT", + "dependencies": { + "@jest/environment": "^29.7.0", + "@jest/expect": "^29.7.0", + "@jest/types": "^29.6.3", + "jest-mock": "^29.7.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/@jest/reporters": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/@jest/reporters/-/reporters-29.7.0.tgz", + "integrity": "sha512-DApq0KJbJOEzAFYjHADNNxAE3KbhxQB1y5Kplb5Waqw6zVbuWatSnMjE5gs8FUgEPmNsnZA3NCWl9NG0ia04Pg==", + "license": "MIT", + "dependencies": { + "@bcoe/v8-coverage": "^0.2.3", + "@jest/console": "^29.7.0", + "@jest/test-result": "^29.7.0", + "@jest/transform": "^29.7.0", + "@jest/types": "^29.6.3", + "@jridgewell/trace-mapping": "^0.3.18", + "@types/node": "*", + "chalk": "^4.0.0", + "collect-v8-coverage": "^1.0.0", + "exit": "^0.1.2", + "glob": "^7.1.3", + "graceful-fs": "^4.2.9", + "istanbul-lib-coverage": "^3.0.0", + "istanbul-lib-instrument": "^6.0.0", + "istanbul-lib-report": "^3.0.0", + "istanbul-lib-source-maps": "^4.0.0", + "istanbul-reports": "^3.1.3", + "jest-message-util": "^29.7.0", + "jest-util": "^29.7.0", + "jest-worker": "^29.7.0", + "slash": "^3.0.0", + "string-length": "^4.0.1", + "strip-ansi": "^6.0.0", + "v8-to-istanbul": "^9.0.1" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "peerDependencies": { + "node-notifier": "^8.0.1 || ^9.0.0 || ^10.0.0" + }, + "peerDependenciesMeta": { + "node-notifier": { + "optional": true + } + } + }, + "node_modules/@jest/reporters/node_modules/@jridgewell/trace-mapping": { + "version": "0.3.25", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.25.tgz", + "integrity": "sha512-vNk6aEwybGtawWmy/PzwnGDOjCkLWSD2wqvjGGAgOAwCGWySYXfYoxt00IJkTF+8Lb57DwOb3Aa0o9CApepiYQ==", + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, + "node_modules/@jest/reporters/node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/@jest/reporters/node_modules/glob": { + "version": "7.2.3", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz", + "integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==", + "deprecated": "Glob versions prior to v9 are no longer supported", + "license": "ISC", + "dependencies": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.1.1", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + }, + "engines": { + "node": "*" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/@jest/reporters/node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "license": "MIT", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/@jest/schemas": { + "version": "29.6.3", + "resolved": "https://registry.npmjs.org/@jest/schemas/-/schemas-29.6.3.tgz", + "integrity": "sha512-mo5j5X+jIZmJQveBKeS/clAueipV7KgiX1vMgCxam1RNYiqE1w62n0/tJJnHtjW8ZHcQco5gY85jA3mi0L+nSA==", + "license": "MIT", + "dependencies": { + "@sinclair/typebox": "^0.27.8" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/@jest/source-map": { + "version": "29.6.3", + "resolved": "https://registry.npmjs.org/@jest/source-map/-/source-map-29.6.3.tgz", + "integrity": "sha512-MHjT95QuipcPrpLM+8JMSzFx6eHp5Bm+4XeFDJlwsvVBjmKNiIAvasGK2fxz2WbGRlnvqehFbh07MMa7n3YJnw==", + "license": "MIT", + "dependencies": { + "@jridgewell/trace-mapping": "^0.3.18", + "callsites": "^3.0.0", + "graceful-fs": "^4.2.9" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/@jest/source-map/node_modules/@jridgewell/trace-mapping": { + "version": "0.3.25", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.25.tgz", + "integrity": "sha512-vNk6aEwybGtawWmy/PzwnGDOjCkLWSD2wqvjGGAgOAwCGWySYXfYoxt00IJkTF+8Lb57DwOb3Aa0o9CApepiYQ==", + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, + "node_modules/@jest/test-result": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/@jest/test-result/-/test-result-29.7.0.tgz", + "integrity": "sha512-Fdx+tv6x1zlkJPcWXmMDAG2HBnaR9XPSd5aDWQVsfrZmLVT3lU1cwyxLgRmXR9yrq4NBoEm9BMsfgFzTQAbJYA==", + "license": "MIT", + "dependencies": { + "@jest/console": "^29.7.0", + "@jest/types": "^29.6.3", + "@types/istanbul-lib-coverage": "^2.0.0", + "collect-v8-coverage": "^1.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/@jest/test-sequencer": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/@jest/test-sequencer/-/test-sequencer-29.7.0.tgz", + "integrity": "sha512-GQwJ5WZVrKnOJuiYiAF52UNUJXgTZx1NHjFSEB0qEMmSZKAkdMoIzw/Cj6x6NF4AvV23AUqDpFzQkN/eYCYTxw==", + "license": "MIT", + "dependencies": { + "@jest/test-result": "^29.7.0", + "graceful-fs": "^4.2.9", + "jest-haste-map": "^29.7.0", + "slash": "^3.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/@jest/transform": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/@jest/transform/-/transform-29.7.0.tgz", + "integrity": "sha512-ok/BTPFzFKVMwO5eOHRrvnBVHdRy9IrsrW1GpMaQ9MCnilNLXQKmAX8s1YXDFaai9xJpac2ySzV0YeRRECr2Vw==", + "license": "MIT", + "dependencies": { + "@babel/core": "^7.11.6", + "@jest/types": "^29.6.3", + "@jridgewell/trace-mapping": "^0.3.18", + "babel-plugin-istanbul": "^6.1.1", + "chalk": "^4.0.0", + "convert-source-map": "^2.0.0", + "fast-json-stable-stringify": "^2.1.0", + "graceful-fs": "^4.2.9", + "jest-haste-map": "^29.7.0", + "jest-regex-util": "^29.6.3", + "jest-util": "^29.7.0", + "micromatch": "^4.0.4", + "pirates": "^4.0.4", + "slash": "^3.0.0", + "write-file-atomic": "^4.0.2" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/@jest/transform/node_modules/@jridgewell/trace-mapping": { + "version": "0.3.25", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.25.tgz", + "integrity": "sha512-vNk6aEwybGtawWmy/PzwnGDOjCkLWSD2wqvjGGAgOAwCGWySYXfYoxt00IJkTF+8Lb57DwOb3Aa0o9CApepiYQ==", + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, + "node_modules/@jest/types": { + "version": "29.6.3", + "resolved": "https://registry.npmjs.org/@jest/types/-/types-29.6.3.tgz", + "integrity": "sha512-u3UPsIilWKOM3F9CXtrG8LEJmNxwoCQC/XVj4IKYXvvpx7QIi/Kg1LI5uDmDpKlac62NUtX7eLjRh+jVZcLOzw==", + "license": "MIT", + "dependencies": { + "@jest/schemas": "^29.6.3", + "@types/istanbul-lib-coverage": "^2.0.0", + "@types/istanbul-reports": "^3.0.0", + "@types/node": "*", + "@types/yargs": "^17.0.8", + "chalk": "^4.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/@jridgewell/gen-mapping": { + "version": "0.3.5", + "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.5.tgz", + "integrity": "sha512-IzL8ZoEDIBRWEzlCcRhOaCupYyN5gdIK+Q6fbFdPDg6HqX6jpkItn7DFIpW9LQzXG6Df9sA7+OKnq0qlz/GaQg==", + "license": "MIT", + "dependencies": { + "@jridgewell/set-array": "^1.2.1", + "@jridgewell/sourcemap-codec": "^1.4.10", + "@jridgewell/trace-mapping": "^0.3.24" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/gen-mapping/node_modules/@jridgewell/trace-mapping": { + "version": "0.3.25", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.25.tgz", + "integrity": "sha512-vNk6aEwybGtawWmy/PzwnGDOjCkLWSD2wqvjGGAgOAwCGWySYXfYoxt00IJkTF+8Lb57DwOb3Aa0o9CApepiYQ==", + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", + "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/set-array": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@jridgewell/set-array/-/set-array-1.2.1.tgz", + "integrity": "sha512-R8gLRTZeyp03ymzP/6Lil/28tGeGEzhx1q2k703KGWRAI1VdvPIXdG70VJc2pAMw3NA6JKL5hhFu1sJX0Mnn/A==", + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.0.tgz", + "integrity": "sha512-gv3ZRaISU3fjPAgNsriBRqGWQL6quFx04YMPW/zD8XMLsU32mhCCbfbO6KZFLjvYpCZ8zyDEgqsgf+PwPaM7GQ==" + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.9", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.9.tgz", + "integrity": "sha512-3Belt6tdc8bPgAtbcmdtNJlirVoTmEb5e2gC94PnkwEW9jI6CAHUeoG85tjWP5WquqfavoMtMwiG4P926ZKKuQ==", + "dependencies": { + "@jridgewell/resolve-uri": "^3.0.3", + "@jridgewell/sourcemap-codec": "^1.4.10" + } + }, + "node_modules/@mongodb-js/saslprep": { + "version": "1.1.9", + "resolved": "https://registry.npmjs.org/@mongodb-js/saslprep/-/saslprep-1.1.9.tgz", + "integrity": "sha512-tVkljjeEaAhCqTzajSdgbQ6gE6f3oneVwa3iXR6csiEwXXOFsiC6Uh9iAjAhXPtqa/XMDHWjjeNH/77m/Yq2dw==", + "dependencies": { + "sparse-bitfield": "^3.0.3" + } + }, + "node_modules/@sinclair/typebox": { + "version": "0.27.8", + "resolved": "https://registry.npmjs.org/@sinclair/typebox/-/typebox-0.27.8.tgz", + "integrity": "sha512-+Fj43pSMwJs4KRrH/938Uf+uAELIgVBmQzg/q1YG10djyfA3TnrU8N8XzqCh/okZdszqBQTZf96idMfE5lnwTA==", + "license": "MIT" + }, + "node_modules/@sinonjs/commons": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/@sinonjs/commons/-/commons-3.0.1.tgz", + "integrity": "sha512-K3mCHKQ9sVh8o1C9cxkwxaOmXoAMlDxC1mYyHrjqOWEcBjYr76t96zL2zlj5dUGZ3HSw240X1qgH3Mjf1yJWpQ==", + "license": "BSD-3-Clause", + "dependencies": { + "type-detect": "4.0.8" + } + }, + "node_modules/@sinonjs/fake-timers": { + "version": "10.3.0", + "resolved": "https://registry.npmjs.org/@sinonjs/fake-timers/-/fake-timers-10.3.0.tgz", + "integrity": "sha512-V4BG07kuYSUkTCSBHG8G8TNhM+F19jXFWnQtzj+we8DrkpSBCee9Z3Ms8yiGer/dlmhe35/Xdgyo3/0rQKg7YA==", + "license": "BSD-3-Clause", + "dependencies": { + "@sinonjs/commons": "^3.0.0" + } + }, + "node_modules/@smithy/abort-controller": { + "version": "3.1.4", + "resolved": "https://registry.npmjs.org/@smithy/abort-controller/-/abort-controller-3.1.4.tgz", + "integrity": "sha512-VupaALAQlXViW3/enTf/f5l5JZYSAxoJL7f0nanhNNKnww6DGCg1oYIuNP78KDugnkwthBO6iEcym16HhWV8RQ==", + "optional": true, + "dependencies": { + "@smithy/types": "^3.4.2", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@smithy/config-resolver": { + "version": "3.0.8", + "resolved": "https://registry.npmjs.org/@smithy/config-resolver/-/config-resolver-3.0.8.tgz", + "integrity": "sha512-Tv1obAC18XOd2OnDAjSWmmthzx6Pdeh63FbLin8MlPiuJ2ATpKkq0NcNOJFr0dO+JmZXnwu8FQxKJ3TKJ3Hulw==", + "optional": true, + "dependencies": { + "@smithy/node-config-provider": "^3.1.7", + "@smithy/types": "^3.4.2", + "@smithy/util-config-provider": "^3.0.0", + "@smithy/util-middleware": "^3.0.6", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@smithy/core": { + "version": "2.4.5", + "resolved": "https://registry.npmjs.org/@smithy/core/-/core-2.4.5.tgz", + "integrity": "sha512-Z0qlPXgZ0pouYgnu/cZTEYeRAvniiKZmVl4wIbZHX/nEMHkMDV9ao6KFArsU9KndE0TuhL149xcRx45wfw1YCA==", + "optional": true, + "dependencies": { + "@smithy/middleware-endpoint": "^3.1.3", + "@smithy/middleware-retry": "^3.0.20", + "@smithy/middleware-serde": "^3.0.6", + "@smithy/protocol-http": "^4.1.3", + "@smithy/smithy-client": "^3.3.4", + "@smithy/types": "^3.4.2", + "@smithy/util-body-length-browser": "^3.0.0", + "@smithy/util-middleware": "^3.0.6", + "@smithy/util-utf8": "^3.0.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@smithy/credential-provider-imds": { + "version": "3.2.3", + "resolved": "https://registry.npmjs.org/@smithy/credential-provider-imds/-/credential-provider-imds-3.2.3.tgz", + "integrity": "sha512-VoxMzSzdvkkjMJNE38yQgx4CfnmT+Z+5EUXkg4x7yag93eQkVQgZvN3XBSHC/ylfBbLbAtdu7flTCChX9I+mVg==", + "optional": true, + "dependencies": { + "@smithy/node-config-provider": "^3.1.7", + "@smithy/property-provider": "^3.1.6", + "@smithy/types": "^3.4.2", + "@smithy/url-parser": "^3.0.6", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@smithy/fetch-http-handler": { + "version": "3.2.8", + "resolved": "https://registry.npmjs.org/@smithy/fetch-http-handler/-/fetch-http-handler-3.2.8.tgz", + "integrity": "sha512-Lqe0B8F5RM7zkw//6avq1SJ8AfaRd3ubFUS1eVp5WszV7p6Ne5hQ4dSuMHDpNRPhgTvj4va9Kd/pcVigHEHRow==", + "optional": true, + "dependencies": { + "@smithy/protocol-http": "^4.1.3", + "@smithy/querystring-builder": "^3.0.6", + "@smithy/types": "^3.4.2", + "@smithy/util-base64": "^3.0.0", + "tslib": "^2.6.2" + } + }, + "node_modules/@smithy/hash-node": { + "version": "3.0.6", + "resolved": "https://registry.npmjs.org/@smithy/hash-node/-/hash-node-3.0.6.tgz", + "integrity": "sha512-c/FHEdKK/7DU2z6ZE91L36ahyXWayR3B+FzELjnYq7wH5YqIseM24V+pWCS9kFn1Ln8OFGTf+pyYPiHZuX0s/Q==", + "optional": true, + "dependencies": { + "@smithy/types": "^3.4.2", + "@smithy/util-buffer-from": "^3.0.0", + "@smithy/util-utf8": "^3.0.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@smithy/invalid-dependency": { + "version": "3.0.6", + "resolved": "https://registry.npmjs.org/@smithy/invalid-dependency/-/invalid-dependency-3.0.6.tgz", + "integrity": "sha512-czM7Ioq3s8pIXht7oD+vmgy4Wfb4XavU/k/irO8NdXFFOx7YAlsCCcKOh/lJD1mJSYQqiR7NmpZ9JviryD/7AQ==", + "optional": true, + "dependencies": { + "@smithy/types": "^3.4.2", + "tslib": "^2.6.2" + } + }, + "node_modules/@smithy/is-array-buffer": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@smithy/is-array-buffer/-/is-array-buffer-3.0.0.tgz", + "integrity": "sha512-+Fsu6Q6C4RSJiy81Y8eApjEB5gVtM+oFKTffg+jSuwtvomJJrhUJBu2zS8wjXSgH/g1MKEWrzyChTBe6clb5FQ==", + "optional": true, + "dependencies": { + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@smithy/middleware-content-length": { + "version": "3.0.8", + "resolved": "https://registry.npmjs.org/@smithy/middleware-content-length/-/middleware-content-length-3.0.8.tgz", + "integrity": "sha512-VuyszlSO49WKh3H9/kIO2kf07VUwGV80QRiaDxUfP8P8UKlokz381ETJvwLhwuypBYhLymCYyNhB3fLAGBX2og==", + "optional": true, + "dependencies": { + "@smithy/protocol-http": "^4.1.3", + "@smithy/types": "^3.4.2", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@smithy/middleware-endpoint": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/@smithy/middleware-endpoint/-/middleware-endpoint-3.1.3.tgz", + "integrity": "sha512-KeM/OrK8MVFUsoJsmCN0MZMVPjKKLudn13xpgwIMpGTYpA8QZB2Xq5tJ+RE6iu3A6NhOI4VajDTwBsm8pwwrhg==", + "optional": true, + "dependencies": { + "@smithy/middleware-serde": "^3.0.6", + "@smithy/node-config-provider": "^3.1.7", + "@smithy/shared-ini-file-loader": "^3.1.7", + "@smithy/types": "^3.4.2", + "@smithy/url-parser": "^3.0.6", + "@smithy/util-middleware": "^3.0.6", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@smithy/middleware-retry": { + "version": "3.0.20", + "resolved": "https://registry.npmjs.org/@smithy/middleware-retry/-/middleware-retry-3.0.20.tgz", + "integrity": "sha512-HELCOVwYw5hFDBm69d+LmmGjBCjWnwp/t7SJiHmp+c4u9vgfIaCjdSeIdnlOsLrr5ic5jGTJXvJFUQnd987b/g==", + "optional": true, + "dependencies": { + "@smithy/node-config-provider": "^3.1.7", + "@smithy/protocol-http": "^4.1.3", + "@smithy/service-error-classification": "^3.0.6", + "@smithy/smithy-client": "^3.3.4", + "@smithy/types": "^3.4.2", + "@smithy/util-middleware": "^3.0.6", + "@smithy/util-retry": "^3.0.6", + "tslib": "^2.6.2", + "uuid": "^9.0.1" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@smithy/middleware-serde": { + "version": "3.0.6", + "resolved": "https://registry.npmjs.org/@smithy/middleware-serde/-/middleware-serde-3.0.6.tgz", + "integrity": "sha512-KKTUSl1MzOM0MAjGbudeaVNtIDo+PpekTBkCNwvfZlKndodrnvRo+00USatiyLOc0ujjO9UydMRu3O9dYML7ag==", + "optional": true, + "dependencies": { + "@smithy/types": "^3.4.2", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@smithy/middleware-stack": { + "version": "3.0.6", + "resolved": "https://registry.npmjs.org/@smithy/middleware-stack/-/middleware-stack-3.0.6.tgz", + "integrity": "sha512-2c0eSYhTQ8xQqHMcRxLMpadFbTXg6Zla5l0mwNftFCZMQmuhI7EbAJMx6R5eqfuV3YbJ3QGyS3d5uSmrHV8Khg==", + "optional": true, + "dependencies": { + "@smithy/types": "^3.4.2", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@smithy/node-config-provider": { + "version": "3.1.7", + "resolved": "https://registry.npmjs.org/@smithy/node-config-provider/-/node-config-provider-3.1.7.tgz", + "integrity": "sha512-g3mfnC3Oo8pOI0dYuPXLtdW1WGVb3bR2tkV21GNkm0ZvQjLTtamXAwCWt/FCb0HGvKt3gHHmF1XerG0ICfalOg==", + "optional": true, + "dependencies": { + "@smithy/property-provider": "^3.1.6", + "@smithy/shared-ini-file-loader": "^3.1.7", + "@smithy/types": "^3.4.2", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@smithy/node-http-handler": { + "version": "3.2.3", + "resolved": "https://registry.npmjs.org/@smithy/node-http-handler/-/node-http-handler-3.2.3.tgz", + "integrity": "sha512-/gcm5DJ3k1b1zEInzBGAZC8ntJ+jwrz1NcSIu+9dSXd1FfG0G6QgkDI40tt8/WYUbHtLyo8fEqtm2v29koWo/w==", + "optional": true, + "dependencies": { + "@smithy/abort-controller": "^3.1.4", + "@smithy/protocol-http": "^4.1.3", + "@smithy/querystring-builder": "^3.0.6", + "@smithy/types": "^3.4.2", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@smithy/property-provider": { + "version": "3.1.6", + "resolved": "https://registry.npmjs.org/@smithy/property-provider/-/property-provider-3.1.6.tgz", + "integrity": "sha512-NK3y/T7Q/Bw+Z8vsVs9MYIQ5v7gOX7clyrXcwhhIBQhbPgRl6JDrZbusO9qWDhcEus75Tg+VCxtIRfo3H76fpw==", + "optional": true, + "dependencies": { + "@smithy/types": "^3.4.2", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@smithy/protocol-http": { + "version": "4.1.3", + "resolved": "https://registry.npmjs.org/@smithy/protocol-http/-/protocol-http-4.1.3.tgz", + "integrity": "sha512-GcbMmOYpH9iRqtC05RbRnc/0FssxSTHlmaNhYBTgSgNCYpdR3Kt88u5GAZTBmouzv+Zlj/VRv92J9ruuDeJuEw==", + "optional": true, + "dependencies": { + "@smithy/types": "^3.4.2", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@smithy/querystring-builder": { + "version": "3.0.6", + "resolved": "https://registry.npmjs.org/@smithy/querystring-builder/-/querystring-builder-3.0.6.tgz", + "integrity": "sha512-sQe08RunoObe+Usujn9+R2zrLuQERi3CWvRO3BvnoWSYUaIrLKuAIeY7cMeDax6xGyfIP3x/yFWbEKSXvOnvVg==", + "optional": true, + "dependencies": { + "@smithy/types": "^3.4.2", + "@smithy/util-uri-escape": "^3.0.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@smithy/querystring-parser": { + "version": "3.0.6", + "resolved": "https://registry.npmjs.org/@smithy/querystring-parser/-/querystring-parser-3.0.6.tgz", + "integrity": "sha512-UJKw4LlEkytzz2Wq+uIdHf6qOtFfee/o7ruH0jF5I6UAuU+19r9QV7nU3P/uI0l6+oElRHmG/5cBBcGJrD7Ozg==", + "optional": true, + "dependencies": { + "@smithy/types": "^3.4.2", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@smithy/service-error-classification": { + "version": "3.0.6", + "resolved": "https://registry.npmjs.org/@smithy/service-error-classification/-/service-error-classification-3.0.6.tgz", + "integrity": "sha512-53SpchU3+DUZrN7J6sBx9tBiCVGzsib2e4sc512Q7K9fpC5zkJKs6Z9s+qbMxSYrkEkle6hnMtrts7XNkMJJMg==", + "optional": true, + "dependencies": { + "@smithy/types": "^3.4.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@smithy/shared-ini-file-loader": { + "version": "3.1.7", + "resolved": "https://registry.npmjs.org/@smithy/shared-ini-file-loader/-/shared-ini-file-loader-3.1.7.tgz", + "integrity": "sha512-IA4K2qTJYXkF5OfVN4vsY1hfnUZjaslEE8Fsr/gGFza4TAC2A9NfnZuSY2srQIbt9bwtjHiAayrRVgKse4Q7fA==", + "optional": true, + "dependencies": { + "@smithy/types": "^3.4.2", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@smithy/signature-v4": { + "version": "4.1.4", + "resolved": "https://registry.npmjs.org/@smithy/signature-v4/-/signature-v4-4.1.4.tgz", + "integrity": "sha512-72MiK7xYukNsnLJI9NqvUHqTu0ziEsfMsYNlWpiJfuGQnCTFKpckThlEatirvcA/LmT1h7rRO+pJD06PYsPu9Q==", + "optional": true, + "dependencies": { + "@smithy/is-array-buffer": "^3.0.0", + "@smithy/protocol-http": "^4.1.3", + "@smithy/types": "^3.4.2", + "@smithy/util-hex-encoding": "^3.0.0", + "@smithy/util-middleware": "^3.0.6", + "@smithy/util-uri-escape": "^3.0.0", + "@smithy/util-utf8": "^3.0.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@smithy/smithy-client": { + "version": "3.3.4", + "resolved": "https://registry.npmjs.org/@smithy/smithy-client/-/smithy-client-3.3.4.tgz", + "integrity": "sha512-NKw/2XxOW/Rg3rzB90HxsmGok5oS6vRzJgMh/JN4BHaOQQ4q5OuX999GmOGxEp730wbpIXIowfKZmIMXkG4v0Q==", + "optional": true, + "dependencies": { + "@smithy/middleware-endpoint": "^3.1.3", + "@smithy/middleware-stack": "^3.0.6", + "@smithy/protocol-http": "^4.1.3", + "@smithy/types": "^3.4.2", + "@smithy/util-stream": "^3.1.8", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@smithy/types": { + "version": "3.4.2", + "resolved": "https://registry.npmjs.org/@smithy/types/-/types-3.4.2.tgz", + "integrity": "sha512-tHiFcfcVedVBHpmHUEUHOCCih8iZbIAYn9NvPsNzaPm/237I3imdDdZoOC8c87H5HBAVEa06tTgb+OcSWV9g5w==", + "optional": true, + "dependencies": { + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@smithy/url-parser": { + "version": "3.0.6", + "resolved": "https://registry.npmjs.org/@smithy/url-parser/-/url-parser-3.0.6.tgz", + "integrity": "sha512-47Op/NU8Opt49KyGpHtVdnmmJMsp2hEwBdyjuFB9M2V5QVOwA7pBhhxKN5z6ztKGrMw76gd8MlbPuzzvaAncuQ==", + "optional": true, + "dependencies": { + "@smithy/querystring-parser": "^3.0.6", + "@smithy/types": "^3.4.2", + "tslib": "^2.6.2" + } + }, + "node_modules/@smithy/util-base64": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@smithy/util-base64/-/util-base64-3.0.0.tgz", + "integrity": "sha512-Kxvoh5Qtt0CDsfajiZOCpJxgtPHXOKwmM+Zy4waD43UoEMA+qPxxa98aE/7ZhdnBFZFXMOiBR5xbcaMhLtznQQ==", + "optional": true, + "dependencies": { + "@smithy/util-buffer-from": "^3.0.0", + "@smithy/util-utf8": "^3.0.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@smithy/util-body-length-browser": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@smithy/util-body-length-browser/-/util-body-length-browser-3.0.0.tgz", + "integrity": "sha512-cbjJs2A1mLYmqmyVl80uoLTJhAcfzMOyPgjwAYusWKMdLeNtzmMz9YxNl3/jRLoxSS3wkqkf0jwNdtXWtyEBaQ==", + "optional": true, + "dependencies": { + "tslib": "^2.6.2" + } + }, + "node_modules/@smithy/util-body-length-node": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@smithy/util-body-length-node/-/util-body-length-node-3.0.0.tgz", + "integrity": "sha512-Tj7pZ4bUloNUP6PzwhN7K386tmSmEET9QtQg0TgdNOnxhZvCssHji+oZTUIuzxECRfG8rdm2PMw2WCFs6eIYkA==", + "optional": true, + "dependencies": { + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@smithy/util-buffer-from": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@smithy/util-buffer-from/-/util-buffer-from-3.0.0.tgz", + "integrity": "sha512-aEOHCgq5RWFbP+UDPvPot26EJHjOC+bRgse5A8V3FSShqd5E5UN4qc7zkwsvJPPAVsf73QwYcHN1/gt/rtLwQA==", + "optional": true, + "dependencies": { + "@smithy/is-array-buffer": "^3.0.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@smithy/util-config-provider": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@smithy/util-config-provider/-/util-config-provider-3.0.0.tgz", + "integrity": "sha512-pbjk4s0fwq3Di/ANL+rCvJMKM5bzAQdE5S/6RL5NXgMExFAi6UgQMPOm5yPaIWPpr+EOXKXRonJ3FoxKf4mCJQ==", + "optional": true, + "dependencies": { + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@smithy/util-defaults-mode-browser": { + "version": "3.0.20", + "resolved": "https://registry.npmjs.org/@smithy/util-defaults-mode-browser/-/util-defaults-mode-browser-3.0.20.tgz", + "integrity": "sha512-HpYmCpEThQJpCKzwzrGrklhdegRfuXI9keHRrHidbyEMliCdgic6t38MikJeZEkdIcEMhO1g95HIYMzjUzB+xg==", + "optional": true, + "dependencies": { + "@smithy/property-provider": "^3.1.6", + "@smithy/smithy-client": "^3.3.4", + "@smithy/types": "^3.4.2", + "bowser": "^2.11.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">= 10.0.0" + } + }, + "node_modules/@smithy/util-defaults-mode-node": { + "version": "3.0.20", + "resolved": "https://registry.npmjs.org/@smithy/util-defaults-mode-node/-/util-defaults-mode-node-3.0.20.tgz", + "integrity": "sha512-atdsHNtAX0rwTvRRGsrONU0C0XzapH6tI8T1y/OReOvWN7uBwXqqWRft6m8egU2DgeReU0xqT3PHdGCe5VRaaQ==", + "optional": true, + "dependencies": { + "@smithy/config-resolver": "^3.0.8", + "@smithy/credential-provider-imds": "^3.2.3", + "@smithy/node-config-provider": "^3.1.7", + "@smithy/property-provider": "^3.1.6", + "@smithy/smithy-client": "^3.3.4", + "@smithy/types": "^3.4.2", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">= 10.0.0" + } + }, + "node_modules/@smithy/util-endpoints": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/@smithy/util-endpoints/-/util-endpoints-2.1.2.tgz", + "integrity": "sha512-FEISzffb4H8DLzGq1g4MuDpcv6CIG15fXoQzDH9SjpRJv6h7J++1STFWWinilG0tQh9H1v2UKWG19Jjr2B16zQ==", + "optional": true, + "dependencies": { + "@smithy/node-config-provider": "^3.1.7", + "@smithy/types": "^3.4.2", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@smithy/util-hex-encoding": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@smithy/util-hex-encoding/-/util-hex-encoding-3.0.0.tgz", + "integrity": "sha512-eFndh1WEK5YMUYvy3lPlVmYY/fZcQE1D8oSf41Id2vCeIkKJXPcYDCZD+4+xViI6b1XSd7tE+s5AmXzz5ilabQ==", + "optional": true, + "dependencies": { + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@smithy/util-middleware": { + "version": "3.0.6", + "resolved": "https://registry.npmjs.org/@smithy/util-middleware/-/util-middleware-3.0.6.tgz", + "integrity": "sha512-BxbX4aBhI1O9p87/xM+zWy0GzT3CEVcXFPBRDoHAM+pV0eSW156pR+PSYEz0DQHDMYDsYAflC2bQNz2uaDBUZQ==", + "optional": true, + "dependencies": { + "@smithy/types": "^3.4.2", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@smithy/util-retry": { + "version": "3.0.6", + "resolved": "https://registry.npmjs.org/@smithy/util-retry/-/util-retry-3.0.6.tgz", + "integrity": "sha512-BRZiuF7IwDntAbevqMco67an0Sr9oLQJqqRCsSPZZHYRnehS0LHDAkJk/pSmI7Z8c/1Vet294H7fY2fWUgB+Rg==", + "optional": true, + "dependencies": { + "@smithy/service-error-classification": "^3.0.6", + "@smithy/types": "^3.4.2", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@smithy/util-stream": { + "version": "3.1.8", + "resolved": "https://registry.npmjs.org/@smithy/util-stream/-/util-stream-3.1.8.tgz", + "integrity": "sha512-hoKOqSmb8FD3WLObuB5hwbM7bNIWgcnvkThokTvVq7J5PKjlLUK5qQQcB9zWLHIoSaIlf3VIv2OxZY2wtQjcRQ==", + "optional": true, + "dependencies": { + "@smithy/fetch-http-handler": "^3.2.8", + "@smithy/node-http-handler": "^3.2.3", + "@smithy/types": "^3.4.2", + "@smithy/util-base64": "^3.0.0", + "@smithy/util-buffer-from": "^3.0.0", + "@smithy/util-hex-encoding": "^3.0.0", + "@smithy/util-utf8": "^3.0.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@smithy/util-uri-escape": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@smithy/util-uri-escape/-/util-uri-escape-3.0.0.tgz", + "integrity": "sha512-LqR7qYLgZTD7nWLBecUi4aqolw8Mhza9ArpNEQ881MJJIU2sE5iHCK6TdyqqzcDLy0OPe10IY4T8ctVdtynubg==", + "optional": true, + "dependencies": { + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@smithy/util-utf8": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@smithy/util-utf8/-/util-utf8-3.0.0.tgz", + "integrity": "sha512-rUeT12bxFnplYDe815GXbq/oixEGHfRFFtcTF3YdDi/JaENIM6aSYYLJydG83UNzLXeRI5K8abYd/8Sp/QM0kA==", + "optional": true, + "dependencies": { + "@smithy/util-buffer-from": "^3.0.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@tsconfig/node10": { + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/@tsconfig/node10/-/node10-1.0.11.tgz", + "integrity": "sha512-DcRjDCujK/kCk/cUe8Xz8ZSpm8mS3mNNpta+jGCA6USEDfktlNvm1+IuZ9eTcDbNk41BHwpHHeW+N1lKCz4zOw==" + }, + "node_modules/@tsconfig/node12": { + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/@tsconfig/node12/-/node12-1.0.11.tgz", + "integrity": "sha512-cqefuRsh12pWyGsIoBKJA9luFu3mRxCA+ORZvA4ktLSzIuCUtWVxGIuXigEwO5/ywWFMZ2QEGKWvkZG1zDMTag==" + }, + "node_modules/@tsconfig/node14": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/@tsconfig/node14/-/node14-1.0.3.tgz", + "integrity": "sha512-ysT8mhdixWK6Hw3i1V2AeRqZ5WfXg1G43mqoYlM2nc6388Fq5jcXyr5mRsqViLx/GJYdoL0bfXD8nmF+Zn/Iow==" + }, + "node_modules/@tsconfig/node16": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/@tsconfig/node16/-/node16-1.0.4.tgz", + "integrity": "sha512-vxhUy4J8lyeyinH7Azl1pdd43GJhZH/tP2weN8TntQblOY+A0XbT8DJk1/oCPuOOyg/Ja757rG0CgHcWC8OfMA==" + }, + "node_modules/@types/babel__core": { + "version": "7.20.5", + "resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.20.5.tgz", + "integrity": "sha512-qoQprZvz5wQFJwMDqeseRXWv3rqMvhgpbXFfVyWhbx9X47POIA6i/+dXefEmZKoAgOaTdaIgNSMqMIU61yRyzA==", + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.20.7", + "@babel/types": "^7.20.7", + "@types/babel__generator": "*", + "@types/babel__template": "*", + "@types/babel__traverse": "*" + } + }, + "node_modules/@types/babel__generator": { + "version": "7.6.8", + "resolved": "https://registry.npmjs.org/@types/babel__generator/-/babel__generator-7.6.8.tgz", + "integrity": "sha512-ASsj+tpEDsEiFr1arWrlN6V3mdfjRMZt6LtK/Vp/kreFLnr5QH5+DhvD5nINYZXzwJvXeGq+05iUXcAzVrqWtw==", + "license": "MIT", + "dependencies": { + "@babel/types": "^7.0.0" + } + }, + "node_modules/@types/babel__template": { + "version": "7.4.4", + "resolved": "https://registry.npmjs.org/@types/babel__template/-/babel__template-7.4.4.tgz", + "integrity": "sha512-h/NUaSyG5EyxBIp8YRxo4RMe2/qQgvyowRwVMzhYhBCONbW8PUsg4lkFMrhgZhUe5z3L3MiLDuvyJ/CaPa2A8A==", + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.1.0", + "@babel/types": "^7.0.0" + } + }, + "node_modules/@types/babel__traverse": { + "version": "7.20.6", + "resolved": "https://registry.npmjs.org/@types/babel__traverse/-/babel__traverse-7.20.6.tgz", + "integrity": "sha512-r1bzfrm0tomOI8g1SzvCaQHo6Lcv6zu0EA+W2kHrt8dyrHQxGzBBL4kdkzIS+jBMV+EYcMAEAqXqYaLJq5rOZg==", + "license": "MIT", + "dependencies": { + "@babel/types": "^7.20.7" + } + }, + "node_modules/@types/body-parser": { + "version": "1.19.5", + "resolved": "https://registry.npmjs.org/@types/body-parser/-/body-parser-1.19.5.tgz", + "integrity": "sha512-fB3Zu92ucau0iQ0JMCFQE7b/dv8Ot07NI3KaZIkIUNXq82k4eBAqUaneXfleGY9JWskeS9y+u0nXMyspcuQrCg==", + "dev": true, + "dependencies": { + "@types/connect": "*", + "@types/node": "*" + } + }, + "node_modules/@types/connect": { + "version": "3.4.38", + "resolved": "https://registry.npmjs.org/@types/connect/-/connect-3.4.38.tgz", + "integrity": "sha512-K6uROf1LD88uDQqJCktA4yzL1YYAK6NgfsI0v/mTgyPKWsX1CnJ0XPSDhViejru1GcRkLWb8RlzFYJRqGUbaug==", + "dev": true, + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/cookiejar": { + "version": "2.1.5", + "resolved": "https://registry.npmjs.org/@types/cookiejar/-/cookiejar-2.1.5.tgz", + "integrity": "sha512-he+DHOWReW0nghN24E1WUqM0efK4kI9oTqDm6XmK8ZPe2djZ90BSNdGnIyCLzCPw7/pogPlGbzI2wHGGmi4O/Q==", + "license": "MIT" + }, + "node_modules/@types/cors": { + "version": "2.8.17", + "resolved": "https://registry.npmjs.org/@types/cors/-/cors-2.8.17.tgz", + "integrity": "sha512-8CGDvrBj1zgo2qE+oS3pOCyYNqCPryMWY2bGfwA0dcfopWGgxs+78df0Rs3rc9THP4JkOhLsAa+15VdpAqkcUA==", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/express": { + "version": "4.17.21", + "resolved": "https://registry.npmjs.org/@types/express/-/express-4.17.21.tgz", + "integrity": "sha512-ejlPM315qwLpaQlQDTjPdsUFSc6ZsP4AN6AlWnogPjQ7CVi7PYF3YVz+CY3jE2pwYf7E/7HlDAN0rV2GxTG0HQ==", + "dev": true, + "dependencies": { + "@types/body-parser": "*", + "@types/express-serve-static-core": "^4.17.33", + "@types/qs": "*", + "@types/serve-static": "*" + } + }, + "node_modules/@types/express-serve-static-core": { + "version": "4.19.5", + "resolved": "https://registry.npmjs.org/@types/express-serve-static-core/-/express-serve-static-core-4.19.5.tgz", + "integrity": "sha512-y6W03tvrACO72aijJ5uF02FRq5cgDR9lUxddQ8vyF+GvmjJQqbzDcJngEjURc+ZsG31VI3hODNZJ2URj86pzmg==", + "dev": true, + "dependencies": { + "@types/node": "*", + "@types/qs": "*", + "@types/range-parser": "*", + "@types/send": "*" + } + }, + "node_modules/@types/graceful-fs": { + "version": "4.1.9", + "resolved": "https://registry.npmjs.org/@types/graceful-fs/-/graceful-fs-4.1.9.tgz", + "integrity": "sha512-olP3sd1qOEe5dXTSaFvQG+02VdRXcdytWLAZsAq1PecU8uqQAhkrnbli7DagjtXKW/Bl7YJbUsa8MPcuc8LHEQ==", + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/http-errors": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/@types/http-errors/-/http-errors-2.0.4.tgz", + "integrity": "sha512-D0CFMMtydbJAegzOyHjtiKPLlvnm3iTZyZRSZoLq2mRhDdmLfIWOCYPfQJ4cu2erKghU++QvjcUjp/5h7hESpA==", + "dev": true + }, + "node_modules/@types/istanbul-lib-coverage": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/@types/istanbul-lib-coverage/-/istanbul-lib-coverage-2.0.6.tgz", + "integrity": "sha512-2QF/t/auWm0lsy8XtKVPG19v3sSOQlJe/YHZgfjb/KBBHOGSV+J2q/S671rcq9uTBrLAXmZpqJiaQbMT+zNU1w==", + "license": "MIT" + }, + "node_modules/@types/istanbul-lib-report": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/@types/istanbul-lib-report/-/istanbul-lib-report-3.0.3.tgz", + "integrity": "sha512-NQn7AHQnk/RSLOxrBbGyJM/aVQ+pjj5HCgasFxc0K/KhoATfQ/47AyUl15I2yBUpihjmas+a+VJBOqecrFH+uA==", + "license": "MIT", + "dependencies": { + "@types/istanbul-lib-coverage": "*" + } + }, + "node_modules/@types/istanbul-reports": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/@types/istanbul-reports/-/istanbul-reports-3.0.4.tgz", + "integrity": "sha512-pk2B1NWalF9toCRu6gjBzR69syFjP4Od8WRAX+0mmf9lAjCRicLOWc+ZrxZHx/0XRjotgkF9t6iaMJ+aXcOdZQ==", + "license": "MIT", + "dependencies": { + "@types/istanbul-lib-report": "*" + } + }, + "node_modules/@types/jest": { + "version": "29.5.13", + "resolved": "https://registry.npmjs.org/@types/jest/-/jest-29.5.13.tgz", + "integrity": "sha512-wd+MVEZCHt23V0/L642O5APvspWply/rGY5BcW4SUETo2UzPU3Z26qr8jC2qxpimI2jjx9h7+2cj2FwIr01bXg==", + "license": "MIT", + "dependencies": { + "expect": "^29.0.0", + "pretty-format": "^29.0.0" + } + }, + "node_modules/@types/methods": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/@types/methods/-/methods-1.1.4.tgz", + "integrity": "sha512-ymXWVrDiCxTBE3+RIrrP533E70eA+9qu7zdWoHuOmGujkYtzf4HQF96b8nwHLqhuf4ykX61IGRIB38CC6/sImQ==", + "license": "MIT" + }, + "node_modules/@types/mime": { + "version": "1.3.5", + "resolved": "https://registry.npmjs.org/@types/mime/-/mime-1.3.5.tgz", + "integrity": "sha512-/pyBZWSLD2n0dcHE3hq8s8ZvcETHtEuF+3E7XVt0Ig2nvsVQXdghHVcEkIWjy9A0wKfTn97a/PSDYohKIlnP/w==", + "dev": true + }, + "node_modules/@types/mongoose-sequence": { + "version": "3.0.11", + "resolved": "https://registry.npmjs.org/@types/mongoose-sequence/-/mongoose-sequence-3.0.11.tgz", + "integrity": "sha512-5O7YNjLACoVri5ikrUFNpT+PY8f+EKYSeJLh3CKjczX5S7h5xvVL9VpJvQj5nQhawyaKu+peqZdMcfj5gOIFnA==", + "dev": true, + "dependencies": { + "@types/node": "*", + "mongoose": "^6.3.0" + } + }, + "node_modules/@types/mongoose-sequence/node_modules/@types/whatwg-url": { + "version": "8.2.2", + "resolved": "https://registry.npmjs.org/@types/whatwg-url/-/whatwg-url-8.2.2.tgz", + "integrity": "sha512-FtQu10RWgn3D9U4aazdwIE2yzphmTJREDqNdODHrbrZmmMqI0vMheC/6NE/J1Yveaj8H+ela+YwWTjq5PGmuhA==", + "dev": true, + "dependencies": { + "@types/node": "*", + "@types/webidl-conversions": "*" + } + }, + "node_modules/@types/mongoose-sequence/node_modules/bson": { + "version": "4.7.2", + "resolved": "https://registry.npmjs.org/bson/-/bson-4.7.2.tgz", + "integrity": "sha512-Ry9wCtIZ5kGqkJoi6aD8KjxFZEx78guTQDnpXWiNthsxzrxAK/i8E6pCHAIZTbaEFWcOCvbecMukfK7XUvyLpQ==", + "dev": true, + "dependencies": { + "buffer": "^5.6.0" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@types/mongoose-sequence/node_modules/debug": { + "version": "4.3.7", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.7.tgz", + "integrity": "sha512-Er2nc/H7RrMXZBFCEim6TCmMk02Z8vLC2Rbi1KEBggpo0fS6l0S1nnapwmIi3yW/+GOJap1Krg4w0Hg80oCqgQ==", + "dev": true, + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/@types/mongoose-sequence/node_modules/kareem": { + "version": "2.5.1", + "resolved": "https://registry.npmjs.org/kareem/-/kareem-2.5.1.tgz", + "integrity": "sha512-7jFxRVm+jD+rkq3kY0iZDJfsO2/t4BBPeEb2qKn2lR/9KhuksYk5hxzfRYWMPV8P/x2d0kHD306YyWLzjjH+uA==", + "dev": true, + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/@types/mongoose-sequence/node_modules/mongodb": { + "version": "4.17.2", + "resolved": "https://registry.npmjs.org/mongodb/-/mongodb-4.17.2.tgz", + "integrity": "sha512-mLV7SEiov2LHleRJPMPrK2PMyhXFZt2UQLC4VD4pnth3jMjYKHhtqfwwkkvS/NXuo/Fp3vbhaNcXrIDaLRb9Tg==", + "dev": true, + "dependencies": { + "bson": "^4.7.2", + "mongodb-connection-string-url": "^2.6.0", + "socks": "^2.7.1" + }, + "engines": { + "node": ">=12.9.0" + }, + "optionalDependencies": { + "@aws-sdk/credential-providers": "^3.186.0", + "@mongodb-js/saslprep": "^1.1.0" + } + }, + "node_modules/@types/mongoose-sequence/node_modules/mongodb-connection-string-url": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/mongodb-connection-string-url/-/mongodb-connection-string-url-2.6.0.tgz", + "integrity": "sha512-WvTZlI9ab0QYtTYnuMLgobULWhokRjtC7db9LtcVfJ+Hsnyr5eo6ZtNAt3Ly24XZScGMelOcGtm7lSn0332tPQ==", + "dev": true, + "dependencies": { + "@types/whatwg-url": "^8.2.1", + "whatwg-url": "^11.0.0" + } + }, + "node_modules/@types/mongoose-sequence/node_modules/mongoose": { + "version": "6.13.3", + "resolved": "https://registry.npmjs.org/mongoose/-/mongoose-6.13.3.tgz", + "integrity": "sha512-TCB/k6ZmkLZGZY/HJ78Ep45Za63591ZuZu5+HCISTe+0lsqbDeomqwezh+Ir7gMLa0wJwIy6CNkl5dxhCXTu9Q==", + "dev": true, + "dependencies": { + "bson": "^4.7.2", + "kareem": "2.5.1", + "mongodb": "4.17.2", + "mpath": "0.9.0", + "mquery": "4.0.3", + "ms": "2.1.3", + "sift": "16.0.1" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/mongoose" + } + }, + "node_modules/@types/mongoose-sequence/node_modules/mquery": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/mquery/-/mquery-4.0.3.tgz", + "integrity": "sha512-J5heI+P08I6VJ2Ky3+33IpCdAvlYGTSUjwTPxkAr8i8EoduPMBX2OY/wa3IKZIQl7MU4SbFk8ndgSKyB/cl1zA==", + "dev": true, + "dependencies": { + "debug": "4.x" + }, + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/@types/mongoose-sequence/node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "dev": true + }, + "node_modules/@types/mongoose-sequence/node_modules/sift": { + "version": "16.0.1", + "resolved": "https://registry.npmjs.org/sift/-/sift-16.0.1.tgz", + "integrity": "sha512-Wv6BjQ5zbhW7VFefWusVP33T/EM0vYikCaQ2qR8yULbsilAT8/wQaXvuQ3ptGLpoKx+lihJE3y2UTgKDyyNHZQ==", + "dev": true + }, + "node_modules/@types/mongoose-sequence/node_modules/tr46": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-3.0.0.tgz", + "integrity": "sha512-l7FvfAHlcmulp8kr+flpQZmVwtu7nfRV7NZujtN0OqES8EL4O4e0qqzL0DC5gAvx/ZC/9lk6rhcUwYvkBnBnYA==", + "dev": true, + "dependencies": { + "punycode": "^2.1.1" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/@types/mongoose-sequence/node_modules/whatwg-url": { + "version": "11.0.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-11.0.0.tgz", + "integrity": "sha512-RKT8HExMpoYx4igMiVMY83lN6UeITKJlBQ+vR/8ZJ8OCdSiN3RwCq+9gH0+Xzj0+5IrM6i4j/6LuvzbZIQgEcQ==", + "dev": true, + "dependencies": { + "tr46": "^3.0.0", + "webidl-conversions": "^7.0.0" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/@types/node": { + "version": "22.6.1", + "resolved": "https://registry.npmjs.org/@types/node/-/node-22.6.1.tgz", + "integrity": "sha512-V48tCfcKb/e6cVUigLAaJDAILdMP0fUW6BidkPK4GpGjXcfbnoHasCZDwz3N3yVt5we2RHm4XTQCpv0KJz9zqw==", + "dependencies": { + "undici-types": "~6.19.2" + } + }, + "node_modules/@types/qs": { + "version": "6.9.16", + "resolved": "https://registry.npmjs.org/@types/qs/-/qs-6.9.16.tgz", + "integrity": "sha512-7i+zxXdPD0T4cKDuxCUXJ4wHcsJLwENa6Z3dCu8cfCK743OGy5Nu1RmAGqDPsoTDINVEcdXKRvR/zre+P2Ku1A==", + "dev": true + }, + "node_modules/@types/range-parser": { + "version": "1.2.7", + "resolved": "https://registry.npmjs.org/@types/range-parser/-/range-parser-1.2.7.tgz", + "integrity": "sha512-hKormJbkJqzQGhziax5PItDUTMAM9uE2XXQmM37dyd4hVM+5aVl7oVxMVUiVQn2oCQFN/LKCZdvSM0pFRqbSmQ==", + "dev": true + }, + "node_modules/@types/send": { + "version": "0.17.4", + "resolved": "https://registry.npmjs.org/@types/send/-/send-0.17.4.tgz", + "integrity": "sha512-x2EM6TJOybec7c52BX0ZspPodMsQUd5L6PRwOunVyVUhXiBSKf3AezDL8Dgvgt5o0UfKNfuA0eMLr2wLT4AiBA==", + "dev": true, + "dependencies": { + "@types/mime": "^1", + "@types/node": "*" + } + }, + "node_modules/@types/serve-static": { + "version": "1.15.7", + "resolved": "https://registry.npmjs.org/@types/serve-static/-/serve-static-1.15.7.tgz", + "integrity": "sha512-W8Ym+h8nhuRwaKPaDw34QUkwsGi6Rc4yYqvKFo5rm2FUEhCFbzVWrxXUxuKK8TASjWsysJY0nsmNCGhCOIsrOw==", + "dev": true, + "dependencies": { + "@types/http-errors": "*", + "@types/node": "*", + "@types/send": "*" + } + }, + "node_modules/@types/stack-utils": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/@types/stack-utils/-/stack-utils-2.0.3.tgz", + "integrity": "sha512-9aEbYZ3TbYMznPdcdr3SmIrLXwC/AKZXQeCf9Pgao5CKb8CyHuEX5jzWPTkvregvhRJHcpRO6BFoGW9ycaOkYw==", + "license": "MIT" + }, + "node_modules/@types/superagent": { + "version": "8.1.9", + "resolved": "https://registry.npmjs.org/@types/superagent/-/superagent-8.1.9.tgz", + "integrity": "sha512-pTVjI73witn+9ILmoJdajHGW2jkSaOzhiFYF1Rd3EQ94kymLqB9PjD9ISg7WaALC7+dCHT0FGe9T2LktLq/3GQ==", + "license": "MIT", + "dependencies": { + "@types/cookiejar": "^2.1.5", + "@types/methods": "^1.1.4", + "@types/node": "*", + "form-data": "^4.0.0" + } + }, + "node_modules/@types/supertest": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/@types/supertest/-/supertest-6.0.2.tgz", + "integrity": "sha512-137ypx2lk/wTQbW6An6safu9hXmajAifU/s7szAHLN/FeIm5w7yR0Wkl9fdJMRSHwOn4HLAI0DaB2TOORuhPDg==", + "license": "MIT", + "dependencies": { + "@types/methods": "^1.1.4", + "@types/superagent": "^8.1.0" + } + }, + "node_modules/@types/webidl-conversions": { + "version": "7.0.3", + "resolved": "https://registry.npmjs.org/@types/webidl-conversions/-/webidl-conversions-7.0.3.tgz", + "integrity": "sha512-CiJJvcRtIgzadHCYXw7dqEnMNRjhGZlYK05Mj9OyktqV8uVT8fD2BFOB7S1uwBE3Kj2Z+4UyPmFw/Ixgw/LAlA==" + }, + "node_modules/@types/whatwg-url": { + "version": "11.0.5", + "resolved": "https://registry.npmjs.org/@types/whatwg-url/-/whatwg-url-11.0.5.tgz", + "integrity": "sha512-coYR071JRaHa+xoEvvYqvnIHaVqaYrLPbsufM9BF63HkwI5Lgmy2QR8Q5K/lYDYo5AK82wOvSOS0UsLTpTG7uQ==", + "dependencies": { + "@types/webidl-conversions": "*" + } + }, + "node_modules/@types/yargs": { + "version": "17.0.33", + "resolved": "https://registry.npmjs.org/@types/yargs/-/yargs-17.0.33.tgz", + "integrity": "sha512-WpxBCKWPLr4xSsHgz511rFJAM+wS28w2zEO1QDNY5zM/S8ok70NNfztH0xwhqKyaK0OHCbN98LDAZuy1ctxDkA==", + "license": "MIT", + "dependencies": { + "@types/yargs-parser": "*" + } + }, + "node_modules/@types/yargs-parser": { + "version": "21.0.3", + "resolved": "https://registry.npmjs.org/@types/yargs-parser/-/yargs-parser-21.0.3.tgz", + "integrity": "sha512-I4q9QU9MQv4oEOz4tAHJtNz1cwuLxn2F3xcc2iV5WdqLPpUnj30aUuxt1mAxYTG+oe8CZMV/+6rU4S4gRDzqtQ==", + "license": "MIT" + }, + "node_modules/accepts": { + "version": "1.3.8", + "resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.8.tgz", + "integrity": "sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw==", + "dependencies": { + "mime-types": "~2.1.34", + "negotiator": "0.6.3" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/acorn": { + "version": "8.12.1", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.12.1.tgz", + "integrity": "sha512-tcpGyI9zbizT9JbV6oYE477V6mTlXvvi0T0G3SNIYE2apm/G5huBa1+K89VGeovbg+jycCrfhl3ADxErOuO6Jg==", + "bin": { + "acorn": "bin/acorn" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/acorn-walk": { + "version": "8.3.4", + "resolved": "https://registry.npmjs.org/acorn-walk/-/acorn-walk-8.3.4.tgz", + "integrity": "sha512-ueEepnujpqee2o5aIYnvHU6C0A42MNdsIDeqy5BydrkuC5R1ZuUFnm27EeFJGoEHJQgn3uleRvmTXaJgfXbt4g==", + "dependencies": { + "acorn": "^8.11.0" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/agent-base": { + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.1.tgz", + "integrity": "sha512-H0TSyFNDMomMNJQBn8wFV5YC/2eJ+VXECwOadZJT554xP6cODZHPX3H9QMQECxvrgiSOP1pHjy1sMWQVYJOUOA==", + "license": "MIT", + "dependencies": { + "debug": "^4.3.4" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/agent-base/node_modules/debug": { + "version": "4.3.7", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.7.tgz", + "integrity": "sha512-Er2nc/H7RrMXZBFCEim6TCmMk02Z8vLC2Rbi1KEBggpo0fS6l0S1nnapwmIi3yW/+GOJap1Krg4w0Hg80oCqgQ==", + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/agent-base/node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "license": "MIT" + }, + "node_modules/ansi-escapes": { + "version": "4.3.2", + "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-4.3.2.tgz", + "integrity": "sha512-gKXj5ALrKWQLsYG9jlTRmR/xKluxHV+Z9QEwNIgCfM1/uwPMCuzVVnh5mwTd+OuBZcwSIMbqssNWRm1lE51QaQ==", + "license": "MIT", + "dependencies": { + "type-fest": "^0.21.3" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/ansi-regex": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.1.0.tgz", + "integrity": "sha512-7HSX4QQb4CspciLpVFwyRe79O3xsIZDDLER21kERQ71oaPodF8jL725AgJMFAYbooIqolJoRLuM81SpeUkpkvA==", + "dev": true, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-regex?sponsor=1" + } + }, + "node_modules/ansi-styles": { + "version": "6.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.1.tgz", + "integrity": "sha512-bN798gFfQX+viw3R7yrGWRqnrN2oRkEkUjjl4JNn4E8GxxbjtG3FbrEIIY3l8/hrwUwIeCZvi4QuOTP4MErVug==", + "dev": true, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/anymatch": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.3.tgz", + "integrity": "sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw==", + "dependencies": { + "normalize-path": "^3.0.0", + "picomatch": "^2.0.4" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/arg": { + "version": "4.1.3", + "resolved": "https://registry.npmjs.org/arg/-/arg-4.1.3.tgz", + "integrity": "sha512-58S9QDqG0Xx27YwPSt9fJxivjYl432YCwfDMfZ+71RAqUrZef7LrKQZ3LHLOwCS4FLNBplP533Zx895SeOCHvA==" + }, + "node_modules/argparse": { + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.10.tgz", + "integrity": "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==", + "license": "MIT", + "dependencies": { + "sprintf-js": "~1.0.2" + } + }, + "node_modules/argparse/node_modules/sprintf-js": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz", + "integrity": "sha512-D9cPgkvLlV3t3IzL0D0YLvGA9Ahk4PcvVwUbN0dSGr1aP0Nrt4AEnTUbuGvquEC0mA64Gqt1fzirlRs5ibXx8g==", + "license": "BSD-3-Clause" + }, + "node_modules/array-flatten": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz", + "integrity": "sha512-PCVAQswWemu6UdxsDFFX/+gVeYqKAod3D3UVm91jHwynguOwAvYPhx8nNlM++NqRcK6CxxpUafjmhIdKiHibqg==" + }, + "node_modules/asap": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/asap/-/asap-2.0.6.tgz", + "integrity": "sha512-BSHWgDSAiKs50o2Re8ppvp3seVHXSRM44cdSsT9FfNEUUZLOGWVCsiWaRPWM1Znn+mqZ1OfVZ3z3DWEzSp7hRA==", + "license": "MIT" + }, + "node_modules/async": { + "version": "3.2.6", + "resolved": "https://registry.npmjs.org/async/-/async-3.2.6.tgz", + "integrity": "sha512-htCUDlxyyCLMgaM3xXg0C0LW2xqfuQ6p05pCEIsXuyQ+a1koYKTuBMzRNwmybfLgvJDMd0r1LTn4+E0Ti6C2AA==" + }, + "node_modules/async-mutex": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/async-mutex/-/async-mutex-0.5.0.tgz", + "integrity": "sha512-1A94B18jkJ3DYq284ohPxoXbfTA5HsQ7/Mf4DEhcyLx3Bz27Rh59iScbB6EPiP+B+joue6YCxcMXSbFC1tZKwA==", + "license": "MIT", + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/asynckit": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", + "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==", + "license": "MIT" + }, + "node_modules/b4a": { + "version": "1.6.6", + "resolved": "https://registry.npmjs.org/b4a/-/b4a-1.6.6.tgz", + "integrity": "sha512-5Tk1HLk6b6ctmjIkAcU/Ujv/1WqiDl0F0JdRCR80VsOcUlHcu7pWeWRlOqQLHfDEsVx9YH/aif5AG4ehoCtTmg==", + "license": "Apache-2.0" + }, + "node_modules/babel-jest": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/babel-jest/-/babel-jest-29.7.0.tgz", + "integrity": "sha512-BrvGY3xZSwEcCzKvKsCi2GgHqDqsYkOP4/by5xCgIwGXQxIEh+8ew3gmrE1y7XRR6LHZIj6yLYnUi/mm2KXKBg==", + "license": "MIT", + "dependencies": { + "@jest/transform": "^29.7.0", + "@types/babel__core": "^7.1.14", + "babel-plugin-istanbul": "^6.1.1", + "babel-preset-jest": "^29.6.3", + "chalk": "^4.0.0", + "graceful-fs": "^4.2.9", + "slash": "^3.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "peerDependencies": { + "@babel/core": "^7.8.0" + } + }, + "node_modules/babel-plugin-istanbul": { + "version": "6.1.1", + "resolved": "https://registry.npmjs.org/babel-plugin-istanbul/-/babel-plugin-istanbul-6.1.1.tgz", + "integrity": "sha512-Y1IQok9821cC9onCx5otgFfRm7Lm+I+wwxOx738M/WLPZ9Q42m4IG5W0FNX8WLL2gYMZo3JkuXIH2DOpWM+qwA==", + "license": "BSD-3-Clause", + "dependencies": { + "@babel/helper-plugin-utils": "^7.0.0", + "@istanbuljs/load-nyc-config": "^1.0.0", + "@istanbuljs/schema": "^0.1.2", + "istanbul-lib-instrument": "^5.0.4", + "test-exclude": "^6.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/babel-plugin-istanbul/node_modules/istanbul-lib-instrument": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/istanbul-lib-instrument/-/istanbul-lib-instrument-5.2.1.tgz", + "integrity": "sha512-pzqtp31nLv/XFOzXGuvhCb8qhjmTVo5vjVk19XE4CRlSWz0KoeJ3bw9XsA7nOp9YBf4qHjwBxkDzKcME/J29Yg==", + "license": "BSD-3-Clause", + "dependencies": { + "@babel/core": "^7.12.3", + "@babel/parser": "^7.14.7", + "@istanbuljs/schema": "^0.1.2", + "istanbul-lib-coverage": "^3.2.0", + "semver": "^6.3.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/babel-plugin-istanbul/node_modules/semver": { + "version": "6.3.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", + "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + } + }, + "node_modules/babel-plugin-jest-hoist": { + "version": "29.6.3", + "resolved": "https://registry.npmjs.org/babel-plugin-jest-hoist/-/babel-plugin-jest-hoist-29.6.3.tgz", + "integrity": "sha512-ESAc/RJvGTFEzRwOTT4+lNDk/GNHMkKbNzsvT0qKRfDyyYTskxB5rnU2njIDYVxXCBHHEI1c0YwHob3WaYujOg==", + "license": "MIT", + "dependencies": { + "@babel/template": "^7.3.3", + "@babel/types": "^7.3.3", + "@types/babel__core": "^7.1.14", + "@types/babel__traverse": "^7.0.6" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/babel-preset-current-node-syntax": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/babel-preset-current-node-syntax/-/babel-preset-current-node-syntax-1.1.0.tgz", + "integrity": "sha512-ldYss8SbBlWva1bs28q78Ju5Zq1F+8BrqBZZ0VFhLBvhh6lCpC2o3gDJi/5DRLs9FgYZCnmPYIVFU4lRXCkyUw==", + "license": "MIT", + "dependencies": { + "@babel/plugin-syntax-async-generators": "^7.8.4", + "@babel/plugin-syntax-bigint": "^7.8.3", + "@babel/plugin-syntax-class-properties": "^7.12.13", + "@babel/plugin-syntax-class-static-block": "^7.14.5", + "@babel/plugin-syntax-import-attributes": "^7.24.7", + "@babel/plugin-syntax-import-meta": "^7.10.4", + "@babel/plugin-syntax-json-strings": "^7.8.3", + "@babel/plugin-syntax-logical-assignment-operators": "^7.10.4", + "@babel/plugin-syntax-nullish-coalescing-operator": "^7.8.3", + "@babel/plugin-syntax-numeric-separator": "^7.10.4", + "@babel/plugin-syntax-object-rest-spread": "^7.8.3", + "@babel/plugin-syntax-optional-catch-binding": "^7.8.3", + "@babel/plugin-syntax-optional-chaining": "^7.8.3", + "@babel/plugin-syntax-private-property-in-object": "^7.14.5", + "@babel/plugin-syntax-top-level-await": "^7.14.5" + }, + "peerDependencies": { + "@babel/core": "^7.0.0" + } + }, + "node_modules/babel-preset-jest": { + "version": "29.6.3", + "resolved": "https://registry.npmjs.org/babel-preset-jest/-/babel-preset-jest-29.6.3.tgz", + "integrity": "sha512-0B3bhxR6snWXJZtR/RliHTDPRgn1sNHOR0yVtq/IiQFyuOVjFS+wuio/R4gSNkyYmKmJB4wGZv2NZanmKmTnNA==", + "license": "MIT", + "dependencies": { + "babel-plugin-jest-hoist": "^29.6.3", + "babel-preset-current-node-syntax": "^1.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0" + } + }, + "node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==" + }, + "node_modules/bare-events": { + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/bare-events/-/bare-events-2.5.0.tgz", + "integrity": "sha512-/E8dDe9dsbLyh2qrZ64PEPadOQ0F4gbl1sUJOrmph7xOiIxfY8vwab/4bFLh4Y88/Hk/ujKcrQKc+ps0mv873A==", + "license": "Apache-2.0", + "optional": true + }, + "node_modules/base64-js": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", + "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] + }, + "node_modules/binary-extensions": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.3.0.tgz", + "integrity": "sha512-Ceh+7ox5qe7LJuLHoY0feh3pHuUDHAcRUeyL2VYghZwfpkNIy/+8Ocg0a3UuSoYzavmylwuLWQOf3hl0jjMMIw==", + "dev": true, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/body-parser": { + "version": "1.20.3", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.3.tgz", + "integrity": "sha512-7rAxByjUMqQ3/bHJy7D6OGXvx/MMc4IqBn/X0fcM1QUcAItpZrBEYhWGem+tzXH90c+G01ypMcYJBO9Y30203g==", + "dependencies": { + "bytes": "3.1.2", + "content-type": "~1.0.5", + "debug": "2.6.9", + "depd": "2.0.0", + "destroy": "1.2.0", + "http-errors": "2.0.0", + "iconv-lite": "0.4.24", + "on-finished": "2.4.1", + "qs": "6.13.0", + "raw-body": "2.5.2", + "type-is": "~1.6.18", + "unpipe": "1.0.0" + }, + "engines": { + "node": ">= 0.8", + "npm": "1.2.8000 || >= 1.4.16" + } + }, + "node_modules/bowser": { + "version": "2.11.0", + "resolved": "https://registry.npmjs.org/bowser/-/bowser-2.11.0.tgz", + "integrity": "sha512-AlcaJBi/pqqJBIQ8U9Mcpc9i8Aqxn88Skv5d+xBX006BY5u8N3mGLHa5Lgppa7L/HfwgwLgZ6NYs+Ag6uUmJRA==", + "optional": true + }, + "node_modules/brace-expansion": { + "version": "1.1.11", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", + "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "node_modules/braces": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.3.tgz", + "integrity": "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==", + "dependencies": { + "fill-range": "^7.1.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/browserslist": { + "version": "4.24.0", + "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.24.0.tgz", + "integrity": "sha512-Rmb62sR1Zpjql25eSanFGEhAxcFwfA1K0GuQcLoaJBAcENegrQut3hYdhXFF1obQfiDyqIW/cLM5HSJ/9k884A==", + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "caniuse-lite": "^1.0.30001663", + "electron-to-chromium": "^1.5.28", + "node-releases": "^2.0.18", + "update-browserslist-db": "^1.1.0" + }, + "bin": { + "browserslist": "cli.js" + }, + "engines": { + "node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7" + } + }, + "node_modules/bs-logger": { + "version": "0.2.6", + "resolved": "https://registry.npmjs.org/bs-logger/-/bs-logger-0.2.6.tgz", + "integrity": "sha512-pd8DCoxmbgc7hyPKOvxtqNcjYoOsABPQdcCUjGp3d42VR2CX1ORhk2A87oqqu5R1kk+76nsxZupkmyd+MVtCog==", + "dev": true, + "license": "MIT", + "dependencies": { + "fast-json-stable-stringify": "2.x" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/bser": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/bser/-/bser-2.1.1.tgz", + "integrity": "sha512-gQxTNE/GAfIIrmHLUE3oJyp5FO6HRBfhjnw4/wMmA63ZGDJnWBmgY/lyQBpnDUkGmAhbSe39tx2d/iTOAfglwQ==", + "license": "Apache-2.0", + "dependencies": { + "node-int64": "^0.4.0" + } + }, + "node_modules/bson": { + "version": "6.8.0", + "resolved": "https://registry.npmjs.org/bson/-/bson-6.8.0.tgz", + "integrity": "sha512-iOJg8pr7wq2tg/zSlCCHMi3hMm5JTOxLTagf3zxhcenHsFp+c6uOs6K7W5UE7A4QIJGtqh/ZovFNMP4mOPJynQ==", + "engines": { + "node": ">=16.20.1" + } + }, + "node_modules/buffer": { + "version": "5.7.1", + "resolved": "https://registry.npmjs.org/buffer/-/buffer-5.7.1.tgz", + "integrity": "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "dependencies": { + "base64-js": "^1.3.1", + "ieee754": "^1.1.13" + } + }, + "node_modules/buffer-crc32": { + "version": "0.2.13", + "resolved": "https://registry.npmjs.org/buffer-crc32/-/buffer-crc32-0.2.13.tgz", + "integrity": "sha512-VO9Ht/+p3SN7SKWqcrgEzjGbRSJYTx+Q1pTQC0wrWqHx0vpJraQ6GtHx8tvcg1rlK1byhU5gccxgOgj7B0TDkQ==", + "license": "MIT", + "engines": { + "node": "*" + } + }, + "node_modules/buffer-from": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz", + "integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==", + "license": "MIT" + }, + "node_modules/bytes": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", + "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/call-bind": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.7.tgz", + "integrity": "sha512-GHTSNSYICQ7scH7sZ+M2rFopRoLh8t2bLSW6BbgrtLsahOIB5iyAVJf9GjWK3cYTDaMj4XdBpM1cA6pIS0Kv2w==", + "dependencies": { + "es-define-property": "^1.0.0", + "es-errors": "^1.3.0", + "function-bind": "^1.1.2", + "get-intrinsic": "^1.2.4", + "set-function-length": "^1.2.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/callsites": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz", + "integrity": "sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/camelcase": { + "version": "5.3.1", + "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-5.3.1.tgz", + "integrity": "sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/caniuse-lite": { + "version": "1.0.30001663", + "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001663.tgz", + "integrity": "sha512-o9C3X27GLKbLeTYZ6HBOLU1tsAcBZsLis28wrVzddShCS16RujjHp9GDHKZqrB3meE0YjhawvMFsGb/igqiPzA==", + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/caniuse-lite" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "CC-BY-4.0" + }, + "node_modules/chalk": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", + "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/chalk/node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "license": "MIT", + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/chalk/node_modules/has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/chalk/node_modules/supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "license": "MIT", + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/char-regex": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/char-regex/-/char-regex-1.0.2.tgz", + "integrity": "sha512-kWWXztvZ5SBQV+eRgKFeh8q5sLuZY2+8WUIzlxWVTg+oGwY14qylx1KbKzHd8P6ZYkAg0xyIDU9JMHhyJMZ1jw==", + "license": "MIT", + "engines": { + "node": ">=10" + } + }, + "node_modules/chokidar": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.6.0.tgz", + "integrity": "sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw==", + "dev": true, + "dependencies": { + "anymatch": "~3.1.2", + "braces": "~3.0.2", + "glob-parent": "~5.1.2", + "is-binary-path": "~2.1.0", + "is-glob": "~4.0.1", + "normalize-path": "~3.0.0", + "readdirp": "~3.6.0" + }, + "engines": { + "node": ">= 8.10.0" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + }, + "optionalDependencies": { + "fsevents": "~2.3.2" + } + }, + "node_modules/ci-info": { + "version": "3.9.0", + "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-3.9.0.tgz", + "integrity": "sha512-NIxF55hv4nSqQswkAeiOi1r83xy8JldOFDTWiug55KBu9Jnblncd2U6ViHmYgHf01TPZS77NJBhBMKdWj9HQMQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/sibiraj-s" + } + ], + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/cjs-module-lexer": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/cjs-module-lexer/-/cjs-module-lexer-1.4.1.tgz", + "integrity": "sha512-cuSVIHi9/9E/+821Qjdvngor+xpnlwnuwIyZOaLmHBVdXL+gP+I6QQB9VkO7RI77YIcTV+S1W9AreJ5eN63JBA==", + "license": "MIT" + }, + "node_modules/cliui": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/cliui/-/cliui-8.0.1.tgz", + "integrity": "sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ==", + "license": "ISC", + "dependencies": { + "string-width": "^4.2.0", + "strip-ansi": "^6.0.1", + "wrap-ansi": "^7.0.0" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/cliui/node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/cliui/node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "license": "MIT", + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/cliui/node_modules/emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", + "license": "MIT" + }, + "node_modules/cliui/node_modules/string-width": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "license": "MIT", + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/cliui/node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "license": "MIT", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/cliui/node_modules/wrap-ansi": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", + "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, + "node_modules/co": { + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/co/-/co-4.6.0.tgz", + "integrity": "sha512-QVb0dM5HvG+uaxitm8wONl7jltx8dqhfU33DcqtOZcLSVIKSDDLDi7+0LbAKiyI8hD9u42m2YxXSkMGWThaecQ==", + "license": "MIT", + "engines": { + "iojs": ">= 1.0.0", + "node": ">= 0.12.0" + } + }, + "node_modules/collect-v8-coverage": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/collect-v8-coverage/-/collect-v8-coverage-1.0.2.tgz", + "integrity": "sha512-lHl4d5/ONEbLlJvaJNtsF/Lz+WvB07u2ycqTYbdrq7UypDXailES4valYb2eWiJFxZlVmpGekfqoxQhzyFdT4Q==", + "license": "MIT" + }, + "node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==" + }, + "node_modules/combined-stream": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", + "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==", + "license": "MIT", + "dependencies": { + "delayed-stream": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/commondir": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/commondir/-/commondir-1.0.1.tgz", + "integrity": "sha512-W9pAhw0ja1Edb5GVdIF1mjZw/ASI0AlShXM83UUGe2DVr5TdAPEA1OA8m/g8zWp9x6On7gqufY+FatDbC3MDQg==", + "license": "MIT" + }, + "node_modules/component-emitter": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/component-emitter/-/component-emitter-1.3.1.tgz", + "integrity": "sha512-T0+barUSQRTUQASh8bx02dl+DhF54GtIDY13Y3m9oWTklKbb3Wv974meRpeZ3lp1JpLVECWWNHC4vaG2XHXouQ==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/concat-map": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", + "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==" + }, + "node_modules/content-disposition": { + "version": "0.5.4", + "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.4.tgz", + "integrity": "sha512-FveZTNuGw04cxlAiWbzi6zTAL/lhehaWbTtgluJh4/E95DqMwTmha3KZN1aAWA8cFIhHzMZUvLevkw5Rqk+tSQ==", + "dependencies": { + "safe-buffer": "5.2.1" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/content-type": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz", + "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/convert-source-map": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz", + "integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==", + "license": "MIT" + }, + "node_modules/cookie": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.6.0.tgz", + "integrity": "sha512-U71cyTamuh1CRNCfpGY6to28lxvNwPG4Guz/EVjgf3Jmzv0vlDp1atT9eS5dDjMYHucpHbWns6Lwf3BKz6svdw==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie-signature": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.6.tgz", + "integrity": "sha512-QADzlaHc8icV8I7vbaJXJwod9HWYp8uCqf1xa4OfNu1T7JVxQIrUgOWtHdNDtPiywmFbiS12VjotIXLrKM3orQ==" + }, + "node_modules/cookiejar": { + "version": "2.1.4", + "resolved": "https://registry.npmjs.org/cookiejar/-/cookiejar-2.1.4.tgz", + "integrity": "sha512-LDx6oHrK+PhzLKJU9j5S7/Y3jM/mUHvD/DeI1WQmJn652iPC5Y4TBzC9l+5OMOXlyTTA+SmVUPm0HQUwpD5Jqw==", + "license": "MIT" + }, + "node_modules/cors": { + "version": "2.8.5", + "resolved": "https://registry.npmjs.org/cors/-/cors-2.8.5.tgz", + "integrity": "sha512-KIHbLJqu73RGr/hnbrO9uBeixNGuvSQjul/jdFvS/KFSIH1hWVd1ng7zOHx+YrEfInLG7q4n6GHQ9cDtxv/P6g==", + "dependencies": { + "object-assign": "^4", + "vary": "^1" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/create-jest": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/create-jest/-/create-jest-29.7.0.tgz", + "integrity": "sha512-Adz2bdH0Vq3F53KEMJOoftQFutWCukm6J24wbPWRO4k1kMY7gS7ds/uoJkNuV8wDCtWWnuwGcJwpWcih+zEW1Q==", + "license": "MIT", + "dependencies": { + "@jest/types": "^29.6.3", + "chalk": "^4.0.0", + "exit": "^0.1.2", + "graceful-fs": "^4.2.9", + "jest-config": "^29.7.0", + "jest-util": "^29.7.0", + "prompts": "^2.0.1" + }, + "bin": { + "create-jest": "bin/create-jest.js" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/create-require": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/create-require/-/create-require-1.1.1.tgz", + "integrity": "sha512-dcKFX3jn0MpIaXjisoRvexIJVEKzaq7z2rZKxf+MSr9TkdmHmsU4m2lcLojrj/FHl8mk5VxMmYA+ftRkP/3oKQ==" + }, + "node_modules/cross-env": { + "version": "7.0.3", + "resolved": "https://registry.npmjs.org/cross-env/-/cross-env-7.0.3.tgz", + "integrity": "sha512-+/HKd6EgcQCJGh2PSjZuUitQBQynKor4wrFbRg4DtAgS1aWO+gU52xpH7M9ScGgXSYmAVS9bIJ8EzuaGw0oNAw==", + "dev": true, + "license": "MIT", + "dependencies": { + "cross-spawn": "^7.0.1" + }, + "bin": { + "cross-env": "src/bin/cross-env.js", + "cross-env-shell": "src/bin/cross-env-shell.js" + }, + "engines": { + "node": ">=10.14", + "npm": ">=6", + "yarn": ">=1" + } + }, + "node_modules/cross-spawn": { + "version": "7.0.3", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.3.tgz", + "integrity": "sha512-iRDPJKUPVEND7dHPO8rkbOnPpyDygcDFtWjpeWNCgy8WP2rXcxXL8TskReQl6OrB2G7+UJrags1q15Fudc7G6w==", + "dependencies": { + "path-key": "^3.1.0", + "shebang-command": "^2.0.0", + "which": "^2.0.1" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "dependencies": { + "ms": "2.0.0" + } + }, + "node_modules/dedent": { + "version": "1.5.3", + "resolved": "https://registry.npmjs.org/dedent/-/dedent-1.5.3.tgz", + "integrity": "sha512-NHQtfOOW68WD8lgypbLA5oT+Bt0xXJhiYvoR6SmmNXZfpzOGXwdKWmcwG8N7PwVVWV3eF/68nmD9BaJSsTBhyQ==", + "license": "MIT", + "peerDependencies": { + "babel-plugin-macros": "^3.1.0" + }, + "peerDependenciesMeta": { + "babel-plugin-macros": { + "optional": true + } + } + }, + "node_modules/deepmerge": { + "version": "4.3.1", + "resolved": "https://registry.npmjs.org/deepmerge/-/deepmerge-4.3.1.tgz", + "integrity": "sha512-3sUqbMEc77XqpdNO7FRyRog+eW3ph+GYCbj+rK+uYyRMuwsVy0rMiVtPn+QJlKFvWP/1PYpapqYn0Me2knFn+A==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/define-data-property": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/define-data-property/-/define-data-property-1.1.4.tgz", + "integrity": "sha512-rBMvIzlpA8v6E+SJZoo++HAYqsLrkg7MSfIinMPFhmkorw7X+dOXVJQs+QT69zGkzMyfDnIMN2Wid1+NbL3T+A==", + "dependencies": { + "es-define-property": "^1.0.0", + "es-errors": "^1.3.0", + "gopd": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/delayed-stream": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", + "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==", + "license": "MIT", + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/depd": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", + "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/destroy": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/destroy/-/destroy-1.2.0.tgz", + "integrity": "sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg==", + "engines": { + "node": ">= 0.8", + "npm": "1.2.8000 || >= 1.4.16" + } + }, + "node_modules/detect-newline": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/detect-newline/-/detect-newline-3.1.0.tgz", + "integrity": "sha512-TLz+x/vEXm/Y7P7wn1EJFNLxYpUD4TgMosxY6fAVJUnJMbupHBOncxyWUG9OpTaH9EBD7uFI5LfEgmMOc54DsA==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/dezalgo": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/dezalgo/-/dezalgo-1.0.4.tgz", + "integrity": "sha512-rXSP0bf+5n0Qonsb+SVVfNfIsimO4HEtmnIpPHY8Q1UCzKlQrDMfdobr8nJOOsRgWCyMRqeSBQzmWUMq7zvVig==", + "license": "ISC", + "dependencies": { + "asap": "^2.0.0", + "wrappy": "1" + } + }, + "node_modules/diff": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/diff/-/diff-4.0.2.tgz", + "integrity": "sha512-58lmxKSA4BNyLz+HHMUzlOEpg09FV+ev6ZMe3vJihgdxzgcwZ8VoEEPmALCZG9LmqfVoNMMKpttIYTVG6uDY7A==", + "engines": { + "node": ">=0.3.1" + } + }, + "node_modules/diff-sequences": { + "version": "29.6.3", + "resolved": "https://registry.npmjs.org/diff-sequences/-/diff-sequences-29.6.3.tgz", + "integrity": "sha512-EjePK1srD3P08o2j4f0ExnylqRs5B9tJjcp9t1krH2qRi8CCdsYfwe9JgSLurFBWwq4uOlipzfk5fHNvwFKr8Q==", + "license": "MIT", + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/dotenv": { + "version": "16.4.5", + "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.4.5.tgz", + "integrity": "sha512-ZmdL2rui+eB2YwhsWzjInR8LldtZHGDoQ1ugH85ppHKwpUHL7j7rN0Ti9NCnGiQbhaZ11FpR+7ao1dNsmduNUg==", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://dotenvx.com" + } + }, + "node_modules/eastasianwidth": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/eastasianwidth/-/eastasianwidth-0.2.0.tgz", + "integrity": "sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA==", + "dev": true + }, + "node_modules/ee-first": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", + "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==" + }, + "node_modules/ejs": { + "version": "3.1.10", + "resolved": "https://registry.npmjs.org/ejs/-/ejs-3.1.10.tgz", + "integrity": "sha512-UeJmFfOrAQS8OJWPZ4qtgHyWExa088/MtK5UEyoJGFH67cDEXkZSviOiKRCZ4Xij0zxI3JECgYs3oKx+AizQBA==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "jake": "^10.8.5" + }, + "bin": { + "ejs": "bin/cli.js" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/electron-to-chromium": { + "version": "1.5.28", + "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.28.tgz", + "integrity": "sha512-VufdJl+rzaKZoYVUijN13QcXVF5dWPZANeFTLNy+OSpHdDL5ynXTF35+60RSBbaQYB1ae723lQXHCrf4pyLsMw==", + "license": "ISC" + }, + "node_modules/emittery": { + "version": "0.13.1", + "resolved": "https://registry.npmjs.org/emittery/-/emittery-0.13.1.tgz", + "integrity": "sha512-DeWwawk6r5yR9jFgnDKYt4sLS0LmHJJi3ZOnb5/JdbYwj3nW+FxQnHIjhBKz8YLC7oRNPVM9NQ47I3CVx34eqQ==", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sindresorhus/emittery?sponsor=1" + } + }, + "node_modules/emoji-regex": { + "version": "9.2.2", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-9.2.2.tgz", + "integrity": "sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg==", + "dev": true + }, + "node_modules/encodeurl": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz", + "integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/error-ex": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/error-ex/-/error-ex-1.3.2.tgz", + "integrity": "sha512-7dFHNmqeFSEt2ZBsCriorKnn3Z2pj+fd9kmI6QoWw4//DL+icEBfc0U7qJCisqrTsKTjw4fNFy2pW9OqStD84g==", + "license": "MIT", + "dependencies": { + "is-arrayish": "^0.2.1" + } + }, + "node_modules/es-define-property": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.0.tgz", + "integrity": "sha512-jxayLKShrEqqzJ0eumQbVhTYQM27CfT1T35+gCgDFoL82JLsXqTJ76zv6A0YLOgEnLUMvLzsDsGIrl8NFpT2gQ==", + "dependencies": { + "get-intrinsic": "^1.2.4" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/esbuild": { + "version": "0.23.1", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.23.1.tgz", + "integrity": "sha512-VVNz/9Sa0bs5SELtn3f7qhJCDPCF5oMEl5cO9/SSinpE9hbPVvxbd572HH5AKiP7WD8INO53GgfDDhRjkylHEg==", + "hasInstallScript": true, + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.23.1", + "@esbuild/android-arm": "0.23.1", + "@esbuild/android-arm64": "0.23.1", + "@esbuild/android-x64": "0.23.1", + "@esbuild/darwin-arm64": "0.23.1", + "@esbuild/darwin-x64": "0.23.1", + "@esbuild/freebsd-arm64": "0.23.1", + "@esbuild/freebsd-x64": "0.23.1", + "@esbuild/linux-arm": "0.23.1", + "@esbuild/linux-arm64": "0.23.1", + "@esbuild/linux-ia32": "0.23.1", + "@esbuild/linux-loong64": "0.23.1", + "@esbuild/linux-mips64el": "0.23.1", + "@esbuild/linux-ppc64": "0.23.1", + "@esbuild/linux-riscv64": "0.23.1", + "@esbuild/linux-s390x": "0.23.1", + "@esbuild/linux-x64": "0.23.1", + "@esbuild/netbsd-x64": "0.23.1", + "@esbuild/openbsd-arm64": "0.23.1", + "@esbuild/openbsd-x64": "0.23.1", + "@esbuild/sunos-x64": "0.23.1", + "@esbuild/win32-arm64": "0.23.1", + "@esbuild/win32-ia32": "0.23.1", + "@esbuild/win32-x64": "0.23.1" + } + }, + "node_modules/escalade": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz", + "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/escape-html": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", + "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==" + }, + "node_modules/escape-string-regexp": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-2.0.0.tgz", + "integrity": "sha512-UpzcLCXolUWcNu5HtVMHYdXJjArjsF9C0aNnquZYY4uW/Vu0miy5YoWvbV345HauVvcAUnpRuhMMcqTcGOY2+w==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/esprima": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.1.tgz", + "integrity": "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==", + "license": "BSD-2-Clause", + "bin": { + "esparse": "bin/esparse.js", + "esvalidate": "bin/esvalidate.js" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/etag": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", + "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/execa": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/execa/-/execa-5.1.1.tgz", + "integrity": "sha512-8uSpZZocAZRBAPIEINJj3Lo9HyGitllczc27Eh5YYojjMFMn8yHMDMaUHE2Jqfq05D/wucwI4JGURyXt1vchyg==", + "license": "MIT", + "dependencies": { + "cross-spawn": "^7.0.3", + "get-stream": "^6.0.0", + "human-signals": "^2.1.0", + "is-stream": "^2.0.0", + "merge-stream": "^2.0.0", + "npm-run-path": "^4.0.1", + "onetime": "^5.1.2", + "signal-exit": "^3.0.3", + "strip-final-newline": "^2.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sindresorhus/execa?sponsor=1" + } + }, + "node_modules/execa/node_modules/signal-exit": { + "version": "3.0.7", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz", + "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==", + "license": "ISC" + }, + "node_modules/exit": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/exit/-/exit-0.1.2.tgz", + "integrity": "sha512-Zk/eNKV2zbjpKzrsQ+n1G6poVbErQxJ0LBOJXaKZ1EViLzH+hrLu9cdXI4zw9dBQJslwBEpbQ2P1oS7nDxs6jQ==", + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/expect": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/expect/-/expect-29.7.0.tgz", + "integrity": "sha512-2Zks0hf1VLFYI1kbh0I5jP3KHHyCHpkfyHBzsSXRFgl/Bg9mWYfMW8oD+PdMPlEwy5HNsR9JutYy6pMeOh61nw==", + "license": "MIT", + "dependencies": { + "@jest/expect-utils": "^29.7.0", + "jest-get-type": "^29.6.3", + "jest-matcher-utils": "^29.7.0", + "jest-message-util": "^29.7.0", + "jest-util": "^29.7.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/express": { + "version": "4.21.0", + "resolved": "https://registry.npmjs.org/express/-/express-4.21.0.tgz", + "integrity": "sha512-VqcNGcj/Id5ZT1LZ/cfihi3ttTn+NJmkli2eZADigjq29qTlWi/hAQ43t/VLPq8+UX06FCEx3ByOYet6ZFblng==", + "dependencies": { + "accepts": "~1.3.8", + "array-flatten": "1.1.1", + "body-parser": "1.20.3", + "content-disposition": "0.5.4", + "content-type": "~1.0.4", + "cookie": "0.6.0", + "cookie-signature": "1.0.6", + "debug": "2.6.9", + "depd": "2.0.0", + "encodeurl": "~2.0.0", + "escape-html": "~1.0.3", + "etag": "~1.8.1", + "finalhandler": "1.3.1", + "fresh": "0.5.2", + "http-errors": "2.0.0", + "merge-descriptors": "1.0.3", + "methods": "~1.1.2", + "on-finished": "2.4.1", + "parseurl": "~1.3.3", + "path-to-regexp": "0.1.10", + "proxy-addr": "~2.0.7", + "qs": "6.13.0", + "range-parser": "~1.2.1", + "safe-buffer": "5.2.1", + "send": "0.19.0", + "serve-static": "1.16.2", + "setprototypeof": "1.2.0", + "statuses": "2.0.1", + "type-is": "~1.6.18", + "utils-merge": "1.0.1", + "vary": "~1.1.2" + }, + "engines": { + "node": ">= 0.10.0" + } + }, + "node_modules/express-validator": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/express-validator/-/express-validator-7.2.0.tgz", + "integrity": "sha512-I2ByKD8panjtr8Y05l21Wph9xk7kk64UMyvJCl/fFM/3CTJq8isXYPLeKW/aZBCdb/LYNv63PwhY8khw8VWocA==", + "dependencies": { + "lodash": "^4.17.21", + "validator": "~13.12.0" + }, + "engines": { + "node": ">= 8.0.0" + } + }, + "node_modules/fast-fifo": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/fast-fifo/-/fast-fifo-1.3.2.tgz", + "integrity": "sha512-/d9sfos4yxzpwkDkuN7k2SqFKtYNmCTzgfEpz82x34IM9/zc8KGxQoXg1liNC/izpRM/MBdt44Nmx41ZWqk+FQ==", + "license": "MIT" + }, + "node_modules/fast-json-stable-stringify": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz", + "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==", + "license": "MIT" + }, + "node_modules/fast-safe-stringify": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/fast-safe-stringify/-/fast-safe-stringify-2.1.1.tgz", + "integrity": "sha512-W+KJc2dmILlPplD/H4K9l9LcAHAfPtP6BY84uVLXQ6Evcz9Lcg33Y2z1IVblT6xdY54PXYVHEv+0Wpq8Io6zkA==", + "license": "MIT" + }, + "node_modules/fast-xml-parser": { + "version": "4.4.1", + "resolved": "https://registry.npmjs.org/fast-xml-parser/-/fast-xml-parser-4.4.1.tgz", + "integrity": "sha512-xkjOecfnKGkSsOwtZ5Pz7Us/T6mrbPQrq0nh+aCO5V9nk5NLWmasAHumTKjiPJPWANe+kAZ84Jc8ooJkzZ88Sw==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/NaturalIntelligence" + }, + { + "type": "paypal", + "url": "https://paypal.me/naturalintelligence" + } + ], + "optional": true, + "dependencies": { + "strnum": "^1.0.5" + }, + "bin": { + "fxparser": "src/cli/cli.js" + } + }, + "node_modules/fb-watchman": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/fb-watchman/-/fb-watchman-2.0.2.tgz", + "integrity": "sha512-p5161BqbuCaSnB8jIbzQHOlpgsPmK5rJVDfDKO91Axs5NC1uu3HRQm6wt9cd9/+GtQQIO53JdGXXoyDpTAsgYA==", + "license": "Apache-2.0", + "dependencies": { + "bser": "2.1.1" + } + }, + "node_modules/filelist": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/filelist/-/filelist-1.0.4.tgz", + "integrity": "sha512-w1cEuf3S+DrLCQL7ET6kz+gmlJdbq9J7yXCSjK/OZCPA+qEN1WyF4ZAf0YYJa4/shHJra2t/d/r8SV4Ji+x+8Q==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "minimatch": "^5.0.1" + } + }, + "node_modules/filelist/node_modules/brace-expansion": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.1.tgz", + "integrity": "sha512-XnAIvQ8eM+kC6aULx6wuQiwVsnzsi9d3WxzV3FpWTGA19F621kwdbsAcFKXgKUHZWsy+mY6iL1sHTxWEFCytDA==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0" + } + }, + "node_modules/filelist/node_modules/minimatch": { + "version": "5.1.6", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-5.1.6.tgz", + "integrity": "sha512-lKwV/1brpG6mBUFHtb7NUmtABCb2WZZmm2wNiOA5hAb8VdCS4B3dtMWyvcoViccwAW/COERjXLt0zP1zXUN26g==", + "dev": true, + "license": "ISC", + "dependencies": { + "brace-expansion": "^2.0.1" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/fill-range": { + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz", + "integrity": "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==", + "dependencies": { + "to-regex-range": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/finalhandler": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.3.1.tgz", + "integrity": "sha512-6BN9trH7bp3qvnrRyzsBz+g3lZxTNZTbVO2EV1CS0WIcDbawYVdYvGflME/9QP0h0pYlCDBCTjYa9nZzMDpyxQ==", + "dependencies": { + "debug": "2.6.9", + "encodeurl": "~2.0.0", + "escape-html": "~1.0.3", + "on-finished": "2.4.1", + "parseurl": "~1.3.3", + "statuses": "2.0.1", + "unpipe": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/find-cache-dir": { + "version": "3.3.2", + "resolved": "https://registry.npmjs.org/find-cache-dir/-/find-cache-dir-3.3.2.tgz", + "integrity": "sha512-wXZV5emFEjrridIgED11OoUKLxiYjAcqot/NJdAkOhlJ+vGzwhOAfcG5OX1jP+S0PcjEn8bdMJv+g2jwQ3Onig==", + "license": "MIT", + "dependencies": { + "commondir": "^1.0.1", + "make-dir": "^3.0.2", + "pkg-dir": "^4.1.0" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/avajs/find-cache-dir?sponsor=1" + } + }, + "node_modules/find-cache-dir/node_modules/make-dir": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-3.1.0.tgz", + "integrity": "sha512-g3FeP20LNwhALb/6Cz6Dd4F2ngze0jz7tbzrD2wAV+o9FeNHe4rL+yK2md0J/fiSf1sa1ADhXqi5+oVwOM/eGw==", + "license": "MIT", + "dependencies": { + "semver": "^6.0.0" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/find-cache-dir/node_modules/semver": { + "version": "6.3.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", + "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + } + }, + "node_modules/find-up": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz", + "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==", + "license": "MIT", + "dependencies": { + "locate-path": "^5.0.0", + "path-exists": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/follow-redirects": { + "version": "1.15.9", + "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.9.tgz", + "integrity": "sha512-gew4GsXizNgdoRyqmyfMHyAmXsZDk6mHkSxZFCzW9gwlbtOW44CDtYavM+y+72qD/Vq2l550kMF52DT8fOLJqQ==", + "funding": [ + { + "type": "individual", + "url": "https://github.com/sponsors/RubenVerborgh" + } + ], + "license": "MIT", + "engines": { + "node": ">=4.0" + }, + "peerDependenciesMeta": { + "debug": { + "optional": true + } + } + }, + "node_modules/foreground-child": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/foreground-child/-/foreground-child-3.3.0.tgz", + "integrity": "sha512-Ld2g8rrAyMYFXBhEqMz8ZAHBi4J4uS1i/CxGMDnjyFWddMXLVcDp051DZfu+t7+ab7Wv6SMqpWmyFIj5UbfFvg==", + "dev": true, + "dependencies": { + "cross-spawn": "^7.0.0", + "signal-exit": "^4.0.1" + }, + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/form-data": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.0.tgz", + "integrity": "sha512-ETEklSGi5t0QMZuiXoA/Q6vcnxcLQP5vdugSpuAyi6SVGi2clPPp+xgEhuMaHC+zGgn31Kd235W35f7Hykkaww==", + "license": "MIT", + "dependencies": { + "asynckit": "^0.4.0", + "combined-stream": "^1.0.8", + "mime-types": "^2.1.12" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/formidable": { + "version": "3.5.1", + "resolved": "https://registry.npmjs.org/formidable/-/formidable-3.5.1.tgz", + "integrity": "sha512-WJWKelbRHN41m5dumb0/k8TeAx7Id/y3a+Z7QfhxP/htI9Js5zYaEDtG8uMgG0vM0lOlqnmjE99/kfpOYi/0Og==", + "license": "MIT", + "dependencies": { + "dezalgo": "^1.0.4", + "hexoid": "^1.0.0", + "once": "^1.4.0" + }, + "funding": { + "url": "https://ko-fi.com/tunnckoCore/commissions" + } + }, + "node_modules/forwarded": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz", + "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/fresh": { + "version": "0.5.2", + "resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz", + "integrity": "sha512-zJ2mQYM18rEFOudeV4GShTGIQ7RbzA7ozbU9I/XBpm7kqgMywgmylMwXHxZJmkVoYkna9d2pVXVXPdYTP9ej8Q==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/fs.realpath": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", + "integrity": "sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==", + "license": "ISC" + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "hasInstallScript": true, + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/gensync": { + "version": "1.0.0-beta.2", + "resolved": "https://registry.npmjs.org/gensync/-/gensync-1.0.0-beta.2.tgz", + "integrity": "sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==", + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/get-caller-file": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", + "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==", + "license": "ISC", + "engines": { + "node": "6.* || 8.* || >= 10.*" + } + }, + "node_modules/get-intrinsic": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.2.4.tgz", + "integrity": "sha512-5uYhsJH8VJBTv7oslg4BznJYhDoRI6waYCxMmCdnTrcCrHA/fCFKoTFz2JKKE0HdDFUF7/oQuhzumXJK7paBRQ==", + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2", + "has-proto": "^1.0.1", + "has-symbols": "^1.0.3", + "hasown": "^2.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-package-type": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/get-package-type/-/get-package-type-0.1.0.tgz", + "integrity": "sha512-pjzuKtY64GYfWizNAJ0fr9VqttZkNiK2iS430LtIHzjBEr6bX8Am2zm4sW4Ro5wjWW5cAlRL1qAMTcXbjNAO2Q==", + "license": "MIT", + "engines": { + "node": ">=8.0.0" + } + }, + "node_modules/get-stream": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-6.0.1.tgz", + "integrity": "sha512-ts6Wi+2j3jQjqi70w5AlN8DFnkSwC+MqmxEzdEALB2qXZYV3X/b1CTfgPLGJNMeAWxdPfU8FO1ms3NUfaHCPYg==", + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/get-tsconfig": { + "version": "4.8.1", + "resolved": "https://registry.npmjs.org/get-tsconfig/-/get-tsconfig-4.8.1.tgz", + "integrity": "sha512-k9PN+cFBmaLWtVz29SkUoqU5O0slLuHJXt/2P+tMVFT+phsSGXGkp9t3rQIqdz0e+06EHNGs3oM6ZX1s2zHxRg==", + "dependencies": { + "resolve-pkg-maps": "^1.0.0" + }, + "funding": { + "url": "https://github.com/privatenumber/get-tsconfig?sponsor=1" + } + }, + "node_modules/glob": { + "version": "11.0.0", + "resolved": "https://registry.npmjs.org/glob/-/glob-11.0.0.tgz", + "integrity": "sha512-9UiX/Bl6J2yaBbxKoEBRm4Cipxgok8kQYcOPEhScPwebu2I0HoQOuYdIO6S3hLuWoZgpDpwQZMzTFxgpkyT76g==", + "dev": true, + "dependencies": { + "foreground-child": "^3.1.0", + "jackspeak": "^4.0.1", + "minimatch": "^10.0.0", + "minipass": "^7.1.2", + "package-json-from-dist": "^1.0.0", + "path-scurry": "^2.0.0" + }, + "bin": { + "glob": "dist/esm/bin.mjs" + }, + "engines": { + "node": "20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/glob-parent": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz", + "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==", + "dev": true, + "dependencies": { + "is-glob": "^4.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/glob/node_modules/brace-expansion": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.1.tgz", + "integrity": "sha512-XnAIvQ8eM+kC6aULx6wuQiwVsnzsi9d3WxzV3FpWTGA19F621kwdbsAcFKXgKUHZWsy+mY6iL1sHTxWEFCytDA==", + "dev": true, + "dependencies": { + "balanced-match": "^1.0.0" + } + }, + "node_modules/glob/node_modules/minimatch": { + "version": "10.0.1", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.0.1.tgz", + "integrity": "sha512-ethXTt3SGGR+95gudmqJ1eNhRO7eGEGIgYA9vnPatK4/etz2MEVDno5GMCibdMTuBMyElzIlgxMna3K94XDIDQ==", + "dev": true, + "dependencies": { + "brace-expansion": "^2.0.1" + }, + "engines": { + "node": "20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/globals": { + "version": "11.12.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-11.12.0.tgz", + "integrity": "sha512-WOBp/EEGUiIsJSp7wcv/y6MO+lV9UoncWqxuFfm8eBwzWNgyfBd6Gz+IeKQ9jCmyhoH99g15M3T+QaVHFjizVA==", + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/gopd": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.0.1.tgz", + "integrity": "sha512-d65bNlIadxvpb/A2abVdlqKqV563juRnZ1Wtk6s1sIR8uNsXR70xqIzVqxVf1eTqDunwT2MkczEeaezCKTZhwA==", + "dependencies": { + "get-intrinsic": "^1.1.3" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/graceful-fs": { + "version": "4.2.11", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz", + "integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==", + "license": "ISC" + }, + "node_modules/has-flag": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", + "integrity": "sha512-sKJf1+ceQBr4SMkvQnBDNDtf4TXpVhVGateu0t918bl30FnbE2m4vNLX+VWe/dpjlb+HugGYzW7uQXH98HPEYw==", + "engines": { + "node": ">=4" + } + }, + "node_modules/has-property-descriptors": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-property-descriptors/-/has-property-descriptors-1.0.2.tgz", + "integrity": "sha512-55JNKuIW+vq4Ke1BjOTjM2YctQIvCT7GFzHwmfZPGo5wnrgkid0YQtnAleFSqumZm4az3n2BS+erby5ipJdgrg==", + "dependencies": { + "es-define-property": "^1.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-proto": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/has-proto/-/has-proto-1.0.3.tgz", + "integrity": "sha512-SJ1amZAJUiZS+PhsVLf5tGydlaVB8EdFpaSO4gmiUKUOxk8qzn5AIy4ZeJUmh22znIdk/uMAUT2pl3FxzVUH+Q==", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-symbols": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.3.tgz", + "integrity": "sha512-l3LCuF6MgDNwTDKkdYGEihYjt5pRPbEg46rtlmnSPlUbgmB8LOIrKJbYYFBSbnPaJexMKtiPO8hmeRjRz2Td+A==", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/hasown": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz", + "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/hexoid": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/hexoid/-/hexoid-1.0.0.tgz", + "integrity": "sha512-QFLV0taWQOZtvIRIAdBChesmogZrtuXvVWsFHZTk2SU+anspqZ2vMnoLg7IE1+Uk16N19APic1BuF8bC8c2m5g==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/html-escaper": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/html-escaper/-/html-escaper-2.0.2.tgz", + "integrity": "sha512-H2iMtd0I4Mt5eYiapRdIDjp+XzelXQ0tFE4JS7YFwFevXXMmOp9myNrUvCg0D6ws8iqkRPBfKHgbwig1SmlLfg==", + "license": "MIT" + }, + "node_modules/http-errors": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.0.tgz", + "integrity": "sha512-FtwrG/euBzaEjYeRqOgly7G0qviiXoJWnvEH2Z1plBdXgbyjv34pHTSb9zoeHMyDy33+DWy5Wt9Wo+TURtOYSQ==", + "dependencies": { + "depd": "2.0.0", + "inherits": "2.0.4", + "setprototypeof": "1.2.0", + "statuses": "2.0.1", + "toidentifier": "1.0.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/https-proxy-agent": { + "version": "7.0.5", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.5.tgz", + "integrity": "sha512-1e4Wqeblerz+tMKPIq2EMGiiWW1dIjZOksyHWSUm1rmuvw/how9hBHZ38lAGj5ID4Ik6EdkOw7NmWPy6LAwalw==", + "license": "MIT", + "dependencies": { + "agent-base": "^7.0.2", + "debug": "4" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/https-proxy-agent/node_modules/debug": { + "version": "4.3.7", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.7.tgz", + "integrity": "sha512-Er2nc/H7RrMXZBFCEim6TCmMk02Z8vLC2Rbi1KEBggpo0fS6l0S1nnapwmIi3yW/+GOJap1Krg4w0Hg80oCqgQ==", + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/https-proxy-agent/node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "license": "MIT" + }, + "node_modules/human-signals": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/human-signals/-/human-signals-2.1.0.tgz", + "integrity": "sha512-B4FFZ6q/T2jhhksgkbEW3HBvWIfDW85snkQgawt07S7J5QXTk6BkNV+0yAeZrM5QpMAdYlocGoljn0sJ/WQkFw==", + "license": "Apache-2.0", + "engines": { + "node": ">=10.17.0" + } + }, + "node_modules/iconv-lite": { + "version": "0.4.24", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz", + "integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/ieee754": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz", + "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] + }, + "node_modules/ignore-by-default": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/ignore-by-default/-/ignore-by-default-1.0.1.tgz", + "integrity": "sha512-Ius2VYcGNk7T90CppJqcIkS5ooHUZyIQK+ClZfMfMNFEF9VSE73Fq+906u/CWu92x4gzZMWOwfFYckPObzdEbA==", + "dev": true + }, + "node_modules/import-local": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/import-local/-/import-local-3.2.0.tgz", + "integrity": "sha512-2SPlun1JUPWoM6t3F0dw0FkCF/jWY8kttcY4f599GLTSjh2OCuuhdTkJQsEcZzBqbXZGKMK2OqW1oZsjtf/gQA==", + "license": "MIT", + "dependencies": { + "pkg-dir": "^4.2.0", + "resolve-cwd": "^3.0.0" + }, + "bin": { + "import-local-fixture": "fixtures/cli.js" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/imurmurhash": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz", + "integrity": "sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==", + "license": "MIT", + "engines": { + "node": ">=0.8.19" + } + }, + "node_modules/inflight": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", + "integrity": "sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA==", + "deprecated": "This module is not supported, and leaks memory. Do not use it. Check out lru-cache if you want a good and tested way to coalesce async requests by a key value, which is much more comprehensive and powerful.", + "license": "ISC", + "dependencies": { + "once": "^1.3.0", + "wrappy": "1" + } + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==" + }, + "node_modules/ip-address": { + "version": "9.0.5", + "resolved": "https://registry.npmjs.org/ip-address/-/ip-address-9.0.5.tgz", + "integrity": "sha512-zHtQzGojZXTwZTHQqra+ETKd4Sn3vgi7uBmlPoXVWZqYvuKmtI0l/VZTjqGmJY9x88GGOaZ9+G9ES8hC4T4X8g==", + "devOptional": true, + "dependencies": { + "jsbn": "1.1.0", + "sprintf-js": "^1.1.3" + }, + "engines": { + "node": ">= 12" + } + }, + "node_modules/ipaddr.js": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz", + "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==", + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/is-arrayish": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.2.1.tgz", + "integrity": "sha512-zz06S8t0ozoDXMG+ube26zeCTNXcKIPJZJi8hBrF4idCLms4CG9QtK7qBl1boi5ODzFpjswb5JPmHCbMpjaYzg==", + "license": "MIT" + }, + "node_modules/is-binary-path": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/is-binary-path/-/is-binary-path-2.1.0.tgz", + "integrity": "sha512-ZMERYes6pDydyuGidse7OsHxtbI7WVeUEozgR/g7rd0xUimYNlvZRE/K2MgZTjWy725IfelLeVcEM97mmtRGXw==", + "dev": true, + "dependencies": { + "binary-extensions": "^2.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/is-core-module": { + "version": "2.15.1", + "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.15.1.tgz", + "integrity": "sha512-z0vtXSwucUJtANQWldhbtbt7BnL0vxiFjIdDLAatwhDYty2bad6s+rijD6Ri4YuYJubLzIJLUidCh09e1djEVQ==", + "license": "MIT", + "dependencies": { + "hasown": "^2.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-extglob": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", + "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-fullwidth-code-point": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", + "engines": { + "node": ">=8" + } + }, + "node_modules/is-generator-fn": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/is-generator-fn/-/is-generator-fn-2.1.0.tgz", + "integrity": "sha512-cTIB4yPYL/Grw0EaSzASzg6bBy9gqCofvWN8okThAYIxKJZC+udlRAmGbM0XLeniEJSs8uEgHPGuHSe1XsOLSQ==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/is-glob": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", + "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", + "dev": true, + "dependencies": { + "is-extglob": "^2.1.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-number": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", + "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", + "engines": { + "node": ">=0.12.0" + } + }, + "node_modules/is-stream": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-2.0.1.tgz", + "integrity": "sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg==", + "license": "MIT", + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/isexe": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", + "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==" + }, + "node_modules/istanbul-lib-coverage": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/istanbul-lib-coverage/-/istanbul-lib-coverage-3.2.2.tgz", + "integrity": "sha512-O8dpsF+r0WV/8MNRKfnmrtCWhuKjxrq2w+jpzBL5UZKTi2LeVWnWOmWRxFlesJONmc+wLAGvKQZEOanko0LFTg==", + "license": "BSD-3-Clause", + "engines": { + "node": ">=8" + } + }, + "node_modules/istanbul-lib-instrument": { + "version": "6.0.3", + "resolved": "https://registry.npmjs.org/istanbul-lib-instrument/-/istanbul-lib-instrument-6.0.3.tgz", + "integrity": "sha512-Vtgk7L/R2JHyyGW07spoFlB8/lpjiOLTjMdms6AFMraYt3BaJauod/NGrfnVG/y4Ix1JEuMRPDPEj2ua+zz1/Q==", + "license": "BSD-3-Clause", + "dependencies": { + "@babel/core": "^7.23.9", + "@babel/parser": "^7.23.9", + "@istanbuljs/schema": "^0.1.3", + "istanbul-lib-coverage": "^3.2.0", + "semver": "^7.5.4" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/istanbul-lib-report": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/istanbul-lib-report/-/istanbul-lib-report-3.0.1.tgz", + "integrity": "sha512-GCfE1mtsHGOELCU8e/Z7YWzpmybrx/+dSTfLrvY8qRmaY6zXTKWn6WQIjaAFw069icm6GVMNkgu0NzI4iPZUNw==", + "license": "BSD-3-Clause", + "dependencies": { + "istanbul-lib-coverage": "^3.0.0", + "make-dir": "^4.0.0", + "supports-color": "^7.1.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/istanbul-lib-report/node_modules/has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/istanbul-lib-report/node_modules/supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "license": "MIT", + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/istanbul-lib-source-maps": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/istanbul-lib-source-maps/-/istanbul-lib-source-maps-4.0.1.tgz", + "integrity": "sha512-n3s8EwkdFIJCG3BPKBYvskgXGoy88ARzvegkitk60NxRdwltLOTaH7CUiMRXvwYorl0Q712iEjcWB+fK/MrWVw==", + "license": "BSD-3-Clause", + "dependencies": { + "debug": "^4.1.1", + "istanbul-lib-coverage": "^3.0.0", + "source-map": "^0.6.1" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/istanbul-lib-source-maps/node_modules/debug": { + "version": "4.3.7", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.7.tgz", + "integrity": "sha512-Er2nc/H7RrMXZBFCEim6TCmMk02Z8vLC2Rbi1KEBggpo0fS6l0S1nnapwmIi3yW/+GOJap1Krg4w0Hg80oCqgQ==", + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/istanbul-lib-source-maps/node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "license": "MIT" + }, + "node_modules/istanbul-reports": { + "version": "3.1.7", + "resolved": "https://registry.npmjs.org/istanbul-reports/-/istanbul-reports-3.1.7.tgz", + "integrity": "sha512-BewmUXImeuRk2YY0PVbxgKAysvhRPUQE0h5QRM++nVWyubKGV0l8qQ5op8+B2DOmwSe63Jivj0BjkPQVf8fP5g==", + "license": "BSD-3-Clause", + "dependencies": { + "html-escaper": "^2.0.0", + "istanbul-lib-report": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/jackspeak": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/jackspeak/-/jackspeak-4.0.2.tgz", + "integrity": "sha512-bZsjR/iRjl1Nk1UkjGpAzLNfQtzuijhn2g+pbZb98HQ1Gk8vM9hfbxeMBP+M2/UUdwj0RqGG3mlvk2MsAqwvEw==", + "dev": true, + "dependencies": { + "@isaacs/cliui": "^8.0.2" + }, + "engines": { + "node": "20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/jake": { + "version": "10.9.2", + "resolved": "https://registry.npmjs.org/jake/-/jake-10.9.2.tgz", + "integrity": "sha512-2P4SQ0HrLQ+fw6llpLnOaGAvN2Zu6778SJMrCUwns4fOoG9ayrTiZk3VV8sCPkVZF8ab0zksVpS8FDY5pRCNBA==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "async": "^3.2.3", + "chalk": "^4.0.2", + "filelist": "^1.0.4", + "minimatch": "^3.1.2" + }, + "bin": { + "jake": "bin/cli.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/jest": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest/-/jest-29.7.0.tgz", + "integrity": "sha512-NIy3oAFp9shda19hy4HK0HRTWKtPJmGdnvywu01nOqNC2vZg+Z+fvJDxpMQA88eb2I9EcafcdjYgsDthnYTvGw==", + "license": "MIT", + "dependencies": { + "@jest/core": "^29.7.0", + "@jest/types": "^29.6.3", + "import-local": "^3.0.2", + "jest-cli": "^29.7.0" + }, + "bin": { + "jest": "bin/jest.js" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "peerDependencies": { + "node-notifier": "^8.0.1 || ^9.0.0 || ^10.0.0" + }, + "peerDependenciesMeta": { + "node-notifier": { + "optional": true + } + } + }, + "node_modules/jest-changed-files": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-changed-files/-/jest-changed-files-29.7.0.tgz", + "integrity": "sha512-fEArFiwf1BpQ+4bXSprcDc3/x4HSzL4al2tozwVpDFpsxALjLYdyiIK4e5Vz66GQJIbXJ82+35PtysofptNX2w==", + "license": "MIT", + "dependencies": { + "execa": "^5.0.0", + "jest-util": "^29.7.0", + "p-limit": "^3.1.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-circus": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-circus/-/jest-circus-29.7.0.tgz", + "integrity": "sha512-3E1nCMgipcTkCocFwM90XXQab9bS+GMsjdpmPrlelaxwD93Ad8iVEjX/vvHPdLPnFf+L40u+5+iutRdA1N9myw==", + "license": "MIT", + "dependencies": { + "@jest/environment": "^29.7.0", + "@jest/expect": "^29.7.0", + "@jest/test-result": "^29.7.0", + "@jest/types": "^29.6.3", + "@types/node": "*", + "chalk": "^4.0.0", + "co": "^4.6.0", + "dedent": "^1.0.0", + "is-generator-fn": "^2.0.0", + "jest-each": "^29.7.0", + "jest-matcher-utils": "^29.7.0", + "jest-message-util": "^29.7.0", + "jest-runtime": "^29.7.0", + "jest-snapshot": "^29.7.0", + "jest-util": "^29.7.0", + "p-limit": "^3.1.0", + "pretty-format": "^29.7.0", + "pure-rand": "^6.0.0", + "slash": "^3.0.0", + "stack-utils": "^2.0.3" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-cli": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-cli/-/jest-cli-29.7.0.tgz", + "integrity": "sha512-OVVobw2IubN/GSYsxETi+gOe7Ka59EFMR/twOU3Jb2GnKKeMGJB5SGUUrEz3SFVmJASUdZUzy83sLNNQ2gZslg==", + "license": "MIT", + "dependencies": { + "@jest/core": "^29.7.0", + "@jest/test-result": "^29.7.0", + "@jest/types": "^29.6.3", + "chalk": "^4.0.0", + "create-jest": "^29.7.0", + "exit": "^0.1.2", + "import-local": "^3.0.2", + "jest-config": "^29.7.0", + "jest-util": "^29.7.0", + "jest-validate": "^29.7.0", + "yargs": "^17.3.1" + }, + "bin": { + "jest": "bin/jest.js" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "peerDependencies": { + "node-notifier": "^8.0.1 || ^9.0.0 || ^10.0.0" + }, + "peerDependenciesMeta": { + "node-notifier": { + "optional": true + } + } + }, + "node_modules/jest-config": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-config/-/jest-config-29.7.0.tgz", + "integrity": "sha512-uXbpfeQ7R6TZBqI3/TxCU4q4ttk3u0PJeC+E0zbfSoSjq6bJ7buBPxzQPL0ifrkY4DNu4JUdk0ImlBUYi840eQ==", + "license": "MIT", + "dependencies": { + "@babel/core": "^7.11.6", + "@jest/test-sequencer": "^29.7.0", + "@jest/types": "^29.6.3", + "babel-jest": "^29.7.0", + "chalk": "^4.0.0", + "ci-info": "^3.2.0", + "deepmerge": "^4.2.2", + "glob": "^7.1.3", + "graceful-fs": "^4.2.9", + "jest-circus": "^29.7.0", + "jest-environment-node": "^29.7.0", + "jest-get-type": "^29.6.3", + "jest-regex-util": "^29.6.3", + "jest-resolve": "^29.7.0", + "jest-runner": "^29.7.0", + "jest-util": "^29.7.0", + "jest-validate": "^29.7.0", + "micromatch": "^4.0.4", + "parse-json": "^5.2.0", + "pretty-format": "^29.7.0", + "slash": "^3.0.0", + "strip-json-comments": "^3.1.1" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "peerDependencies": { + "@types/node": "*", + "ts-node": ">=9.0.0" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "ts-node": { + "optional": true + } + } + }, + "node_modules/jest-config/node_modules/glob": { + "version": "7.2.3", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz", + "integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==", + "deprecated": "Glob versions prior to v9 are no longer supported", + "license": "ISC", + "dependencies": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.1.1", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + }, + "engines": { + "node": "*" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/jest-diff": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-diff/-/jest-diff-29.7.0.tgz", + "integrity": "sha512-LMIgiIrhigmPrs03JHpxUh2yISK3vLFPkAodPeo0+BuF7wA2FoQbkEg1u8gBYBThncu7e1oEDUfIXVuTqLRUjw==", + "license": "MIT", + "dependencies": { + "chalk": "^4.0.0", + "diff-sequences": "^29.6.3", + "jest-get-type": "^29.6.3", + "pretty-format": "^29.7.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-docblock": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-docblock/-/jest-docblock-29.7.0.tgz", + "integrity": "sha512-q617Auw3A612guyaFgsbFeYpNP5t2aoUNLwBUbc/0kD1R4t9ixDbyFTHd1nok4epoVFpr7PmeWHrhvuV3XaJ4g==", + "license": "MIT", + "dependencies": { + "detect-newline": "^3.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-each": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-each/-/jest-each-29.7.0.tgz", + "integrity": "sha512-gns+Er14+ZrEoC5fhOfYCY1LOHHr0TI+rQUHZS8Ttw2l7gl+80eHc/gFf2Ktkw0+SIACDTeWvpFcv3B04VembQ==", + "license": "MIT", + "dependencies": { + "@jest/types": "^29.6.3", + "chalk": "^4.0.0", + "jest-get-type": "^29.6.3", + "jest-util": "^29.7.0", + "pretty-format": "^29.7.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-environment-node": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-environment-node/-/jest-environment-node-29.7.0.tgz", + "integrity": "sha512-DOSwCRqXirTOyheM+4d5YZOrWcdu0LNZ87ewUoywbcb2XR4wKgqiG8vNeYwhjFMbEkfju7wx2GYH0P2gevGvFw==", + "license": "MIT", + "dependencies": { + "@jest/environment": "^29.7.0", + "@jest/fake-timers": "^29.7.0", + "@jest/types": "^29.6.3", + "@types/node": "*", + "jest-mock": "^29.7.0", + "jest-util": "^29.7.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-get-type": { + "version": "29.6.3", + "resolved": "https://registry.npmjs.org/jest-get-type/-/jest-get-type-29.6.3.tgz", + "integrity": "sha512-zrteXnqYxfQh7l5FHyL38jL39di8H8rHoecLH3JNxH3BwOrBsNeabdap5e0I23lD4HHI8W5VFBZqG4Eaq5LNcw==", + "license": "MIT", + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-haste-map": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-haste-map/-/jest-haste-map-29.7.0.tgz", + "integrity": "sha512-fP8u2pyfqx0K1rGn1R9pyE0/KTn+G7PxktWidOBTqFPLYX0b9ksaMFkhK5vrS3DVun09pckLdlx90QthlW7AmA==", + "license": "MIT", + "dependencies": { + "@jest/types": "^29.6.3", + "@types/graceful-fs": "^4.1.3", + "@types/node": "*", + "anymatch": "^3.0.3", + "fb-watchman": "^2.0.0", + "graceful-fs": "^4.2.9", + "jest-regex-util": "^29.6.3", + "jest-util": "^29.7.0", + "jest-worker": "^29.7.0", + "micromatch": "^4.0.4", + "walker": "^1.0.8" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "optionalDependencies": { + "fsevents": "^2.3.2" + } + }, + "node_modules/jest-leak-detector": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-leak-detector/-/jest-leak-detector-29.7.0.tgz", + "integrity": "sha512-kYA8IJcSYtST2BY9I+SMC32nDpBT3J2NvWJx8+JCuCdl/CR1I4EKUJROiP8XtCcxqgTTBGJNdbB1A8XRKbTetw==", + "license": "MIT", + "dependencies": { + "jest-get-type": "^29.6.3", + "pretty-format": "^29.7.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-matcher-utils": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-matcher-utils/-/jest-matcher-utils-29.7.0.tgz", + "integrity": "sha512-sBkD+Xi9DtcChsI3L3u0+N0opgPYnCRPtGcQYrgXmR+hmt/fYfWAL0xRXYU8eWOdfuLgBe0YCW3AFtnRLagq/g==", + "license": "MIT", + "dependencies": { + "chalk": "^4.0.0", + "jest-diff": "^29.7.0", + "jest-get-type": "^29.6.3", + "pretty-format": "^29.7.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-message-util": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-message-util/-/jest-message-util-29.7.0.tgz", + "integrity": "sha512-GBEV4GRADeP+qtB2+6u61stea8mGcOT4mCtrYISZwfu9/ISHFJ/5zOMXYbpBE9RsS5+Gb63DW4FgmnKJ79Kf6w==", + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.12.13", + "@jest/types": "^29.6.3", + "@types/stack-utils": "^2.0.0", + "chalk": "^4.0.0", + "graceful-fs": "^4.2.9", + "micromatch": "^4.0.4", + "pretty-format": "^29.7.0", + "slash": "^3.0.0", + "stack-utils": "^2.0.3" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-mock": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-mock/-/jest-mock-29.7.0.tgz", + "integrity": "sha512-ITOMZn+UkYS4ZFh83xYAOzWStloNzJFO2s8DWrE4lhtGD+AorgnbkiKERe4wQVBydIGPx059g6riW5Btp6Llnw==", + "license": "MIT", + "dependencies": { + "@jest/types": "^29.6.3", + "@types/node": "*", + "jest-util": "^29.7.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-pnp-resolver": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/jest-pnp-resolver/-/jest-pnp-resolver-1.2.3.tgz", + "integrity": "sha512-+3NpwQEnRoIBtx4fyhblQDPgJI0H1IEIkX7ShLUjPGA7TtUTvI1oiKi3SR4oBR0hQhQR80l4WAe5RrXBwWMA8w==", + "license": "MIT", + "engines": { + "node": ">=6" + }, + "peerDependencies": { + "jest-resolve": "*" + }, + "peerDependenciesMeta": { + "jest-resolve": { + "optional": true + } + } + }, + "node_modules/jest-regex-util": { + "version": "29.6.3", + "resolved": "https://registry.npmjs.org/jest-regex-util/-/jest-regex-util-29.6.3.tgz", + "integrity": "sha512-KJJBsRCyyLNWCNBOvZyRDnAIfUiRJ8v+hOBQYGn8gDyF3UegwiP4gwRR3/SDa42g1YbVycTidUF3rKjyLFDWbg==", + "license": "MIT", + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-resolve": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-resolve/-/jest-resolve-29.7.0.tgz", + "integrity": "sha512-IOVhZSrg+UvVAshDSDtHyFCCBUl/Q3AAJv8iZ6ZjnZ74xzvwuzLXid9IIIPgTnY62SJjfuupMKZsZQRsCvxEgA==", + "license": "MIT", + "dependencies": { + "chalk": "^4.0.0", + "graceful-fs": "^4.2.9", + "jest-haste-map": "^29.7.0", + "jest-pnp-resolver": "^1.2.2", + "jest-util": "^29.7.0", + "jest-validate": "^29.7.0", + "resolve": "^1.20.0", + "resolve.exports": "^2.0.0", + "slash": "^3.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-resolve-dependencies": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-resolve-dependencies/-/jest-resolve-dependencies-29.7.0.tgz", + "integrity": "sha512-un0zD/6qxJ+S0et7WxeI3H5XSe9lTBBR7bOHCHXkKR6luG5mwDDlIzVQ0V5cZCuoTgEdcdwzTghYkTWfubi+nA==", + "license": "MIT", + "dependencies": { + "jest-regex-util": "^29.6.3", + "jest-snapshot": "^29.7.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-runner": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-runner/-/jest-runner-29.7.0.tgz", + "integrity": "sha512-fsc4N6cPCAahybGBfTRcq5wFR6fpLznMg47sY5aDpsoejOcVYFb07AHuSnR0liMcPTgBsA3ZJL6kFOjPdoNipQ==", + "license": "MIT", + "dependencies": { + "@jest/console": "^29.7.0", + "@jest/environment": "^29.7.0", + "@jest/test-result": "^29.7.0", + "@jest/transform": "^29.7.0", + "@jest/types": "^29.6.3", + "@types/node": "*", + "chalk": "^4.0.0", + "emittery": "^0.13.1", + "graceful-fs": "^4.2.9", + "jest-docblock": "^29.7.0", + "jest-environment-node": "^29.7.0", + "jest-haste-map": "^29.7.0", + "jest-leak-detector": "^29.7.0", + "jest-message-util": "^29.7.0", + "jest-resolve": "^29.7.0", + "jest-runtime": "^29.7.0", + "jest-util": "^29.7.0", + "jest-watcher": "^29.7.0", + "jest-worker": "^29.7.0", + "p-limit": "^3.1.0", + "source-map-support": "0.5.13" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-runtime": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-runtime/-/jest-runtime-29.7.0.tgz", + "integrity": "sha512-gUnLjgwdGqW7B4LvOIkbKs9WGbn+QLqRQQ9juC6HndeDiezIwhDP+mhMwHWCEcfQ5RUXa6OPnFF8BJh5xegwwQ==", + "license": "MIT", + "dependencies": { + "@jest/environment": "^29.7.0", + "@jest/fake-timers": "^29.7.0", + "@jest/globals": "^29.7.0", + "@jest/source-map": "^29.6.3", + "@jest/test-result": "^29.7.0", + "@jest/transform": "^29.7.0", + "@jest/types": "^29.6.3", + "@types/node": "*", + "chalk": "^4.0.0", + "cjs-module-lexer": "^1.0.0", + "collect-v8-coverage": "^1.0.0", + "glob": "^7.1.3", + "graceful-fs": "^4.2.9", + "jest-haste-map": "^29.7.0", + "jest-message-util": "^29.7.0", + "jest-mock": "^29.7.0", + "jest-regex-util": "^29.6.3", + "jest-resolve": "^29.7.0", + "jest-snapshot": "^29.7.0", + "jest-util": "^29.7.0", + "slash": "^3.0.0", + "strip-bom": "^4.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-runtime/node_modules/glob": { + "version": "7.2.3", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz", + "integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==", + "deprecated": "Glob versions prior to v9 are no longer supported", + "license": "ISC", + "dependencies": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.1.1", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + }, + "engines": { + "node": "*" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/jest-snapshot": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-snapshot/-/jest-snapshot-29.7.0.tgz", + "integrity": "sha512-Rm0BMWtxBcioHr1/OX5YCP8Uov4riHvKPknOGs804Zg9JGZgmIBkbtlxJC/7Z4msKYVbIJtfU+tKb8xlYNfdkw==", + "license": "MIT", + "dependencies": { + "@babel/core": "^7.11.6", + "@babel/generator": "^7.7.2", + "@babel/plugin-syntax-jsx": "^7.7.2", + "@babel/plugin-syntax-typescript": "^7.7.2", + "@babel/types": "^7.3.3", + "@jest/expect-utils": "^29.7.0", + "@jest/transform": "^29.7.0", + "@jest/types": "^29.6.3", + "babel-preset-current-node-syntax": "^1.0.0", + "chalk": "^4.0.0", + "expect": "^29.7.0", + "graceful-fs": "^4.2.9", + "jest-diff": "^29.7.0", + "jest-get-type": "^29.6.3", + "jest-matcher-utils": "^29.7.0", + "jest-message-util": "^29.7.0", + "jest-util": "^29.7.0", + "natural-compare": "^1.4.0", + "pretty-format": "^29.7.0", + "semver": "^7.5.3" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-util": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-util/-/jest-util-29.7.0.tgz", + "integrity": "sha512-z6EbKajIpqGKU56y5KBUgy1dt1ihhQJgWzUlZHArA/+X2ad7Cb5iF+AK1EWVL/Bo7Rz9uurpqw6SiBCefUbCGA==", + "license": "MIT", + "dependencies": { + "@jest/types": "^29.6.3", + "@types/node": "*", + "chalk": "^4.0.0", + "ci-info": "^3.2.0", + "graceful-fs": "^4.2.9", + "picomatch": "^2.2.3" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-validate": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-validate/-/jest-validate-29.7.0.tgz", + "integrity": "sha512-ZB7wHqaRGVw/9hST/OuFUReG7M8vKeq0/J2egIGLdvjHCmYqGARhzXmtgi+gVeZ5uXFF219aOc3Ls2yLg27tkw==", + "license": "MIT", + "dependencies": { + "@jest/types": "^29.6.3", + "camelcase": "^6.2.0", + "chalk": "^4.0.0", + "jest-get-type": "^29.6.3", + "leven": "^3.1.0", + "pretty-format": "^29.7.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-validate/node_modules/camelcase": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-6.3.0.tgz", + "integrity": "sha512-Gmy6FhYlCY7uOElZUSbxo2UCDH8owEk996gkbrpsgGtrJLM3J7jGxl9Ic7Qwwj4ivOE5AWZWRMecDdF7hqGjFA==", + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/jest-watcher": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-watcher/-/jest-watcher-29.7.0.tgz", + "integrity": "sha512-49Fg7WXkU3Vl2h6LbLtMQ/HyB6rXSIX7SqvBLQmssRBGN9I0PNvPmAmCWSOY6SOvrjhI/F7/bGAv9RtnsPA03g==", + "license": "MIT", + "dependencies": { + "@jest/test-result": "^29.7.0", + "@jest/types": "^29.6.3", + "@types/node": "*", + "ansi-escapes": "^4.2.1", + "chalk": "^4.0.0", + "emittery": "^0.13.1", + "jest-util": "^29.7.0", + "string-length": "^4.0.1" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-worker": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-worker/-/jest-worker-29.7.0.tgz", + "integrity": "sha512-eIz2msL/EzL9UFTFFx7jBTkeZfku0yUAyZZZmJ93H2TYEiroIx2PQjEXcwYtYl8zXCxb+PAmA2hLIt/6ZEkPHw==", + "license": "MIT", + "dependencies": { + "@types/node": "*", + "jest-util": "^29.7.0", + "merge-stream": "^2.0.0", + "supports-color": "^8.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-worker/node_modules/has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/jest-worker/node_modules/supports-color": { + "version": "8.1.1", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-8.1.1.tgz", + "integrity": "sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q==", + "license": "MIT", + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/supports-color?sponsor=1" + } + }, + "node_modules/js-tokens": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", + "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", + "license": "MIT" + }, + "node_modules/js-yaml": { + "version": "3.14.1", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.14.1.tgz", + "integrity": "sha512-okMH7OXXJ7YrN9Ok3/SXrnu4iX9yOk+25nqX4imS2npuvTYDmo/QEZoqwZkYaIDk3jVvBOTOIEgEhaLOynBS9g==", + "license": "MIT", + "dependencies": { + "argparse": "^1.0.7", + "esprima": "^4.0.0" + }, + "bin": { + "js-yaml": "bin/js-yaml.js" + } + }, + "node_modules/jsbn": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/jsbn/-/jsbn-1.1.0.tgz", + "integrity": "sha512-4bYVV3aAMtDTTu4+xsDYa6sy9GyJ69/amsu9sYF2zqjiEoZA5xJi3BrfX3uY+/IekIu7MwdObdbDWpoZdBv3/A==", + "devOptional": true + }, + "node_modules/jsesc": { + "version": "2.5.2", + "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-2.5.2.tgz", + "integrity": "sha512-OYu7XEzjkCQ3C5Ps3QIZsQfNpqoJyZZA99wd9aWd05NCtC5pWOkShK2mkL6HXQR6/Cy2lbNdPlZBpuQHXE63gA==", + "license": "MIT", + "bin": { + "jsesc": "bin/jsesc" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/json-parse-even-better-errors": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/json-parse-even-better-errors/-/json-parse-even-better-errors-2.3.1.tgz", + "integrity": "sha512-xyFwyhro/JEof6Ghe2iz2NcXoj2sloNsWr/XsERDK/oiPCfaNhl5ONfp+jQdAZRQQ0IJWNzH9zIZF7li91kh2w==", + "license": "MIT" + }, + "node_modules/json5": { + "version": "2.2.3", + "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz", + "integrity": "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==", + "license": "MIT", + "bin": { + "json5": "lib/cli.js" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/kareem": { + "version": "2.6.3", + "resolved": "https://registry.npmjs.org/kareem/-/kareem-2.6.3.tgz", + "integrity": "sha512-C3iHfuGUXK2u8/ipq9LfjFfXFxAZMQJJq7vLS45r3D9Y2xQ/m4S8zaR4zMLFWh9AsNPXmcFfUDhTEO8UIC/V6Q==", + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/kleur": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/kleur/-/kleur-3.0.3.tgz", + "integrity": "sha512-eTIzlVOSUR+JxdDFepEYcBMtZ9Qqdef+rnzWdRZuMbOywu5tO2w2N7rqjoANZ5k9vywhL6Br1VRjUIgTQx4E8w==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/leven": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/leven/-/leven-3.1.0.tgz", + "integrity": "sha512-qsda+H8jTaUaN/x5vzW2rzc+8Rw4TAQ/4KjB46IwK5VH+IlVeeeje/EoZRpiXvIqjFgK84QffqPztGI3VBLG1A==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/lines-and-columns": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/lines-and-columns/-/lines-and-columns-1.2.4.tgz", + "integrity": "sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==", + "license": "MIT" + }, + "node_modules/locate-path": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz", + "integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==", + "license": "MIT", + "dependencies": { + "p-locate": "^4.1.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/lodash": { + "version": "4.17.21", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz", + "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==" + }, + "node_modules/lodash.memoize": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/lodash.memoize/-/lodash.memoize-4.1.2.tgz", + "integrity": "sha512-t7j+NzmgnQzTAYXcsHYLgimltOV1MXHtlOWf6GjL9Kj8GK5FInw5JotxvbOs+IvV1/Dzo04/fCGfLVs7aXb4Ag==", + "dev": true, + "license": "MIT" + }, + "node_modules/lru-cache": { + "version": "11.0.1", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.0.1.tgz", + "integrity": "sha512-CgeuL5uom6j/ZVrg7G/+1IXqRY8JXX4Hghfy5YE0EhoYQWvndP1kufu58cmZLNIDKnRhZrXfdS9urVWx98AipQ==", + "dev": true, + "engines": { + "node": "20 || >=22" + } + }, + "node_modules/make-dir": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-4.0.0.tgz", + "integrity": "sha512-hXdUTZYIVOt1Ex//jAQi+wTZZpUpwBj/0QsOzqegb3rGMMeJiSEu5xLHnYfBrRV4RH2+OCSOO95Is/7x1WJ4bw==", + "license": "MIT", + "dependencies": { + "semver": "^7.5.3" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/make-error": { + "version": "1.3.6", + "resolved": "https://registry.npmjs.org/make-error/-/make-error-1.3.6.tgz", + "integrity": "sha512-s8UhlNe7vPKomQhC1qFelMokr/Sc3AgNbso3n74mVPA5LTZwkB9NlXf4XPamLxJE8h0gh73rM94xvwRT2CVInw==" + }, + "node_modules/makeerror": { + "version": "1.0.12", + "resolved": "https://registry.npmjs.org/makeerror/-/makeerror-1.0.12.tgz", + "integrity": "sha512-JmqCvUhmt43madlpFzG4BQzG2Z3m6tvQDNKdClZnO3VbIudJYmxsT0FNJMeiB2+JTSlTQTSbU8QdesVmwJcmLg==", + "license": "BSD-3-Clause", + "dependencies": { + "tmpl": "1.0.5" + } + }, + "node_modules/media-typer": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz", + "integrity": "sha512-dq+qelQ9akHpcOl/gUVRTxVIOkAJ1wR3QAvb4RsVjS8oVoFjDGTc679wJYmUmknUF5HwMLOgb5O+a3KxfWapPQ==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/memory-pager": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/memory-pager/-/memory-pager-1.5.0.tgz", + "integrity": "sha512-ZS4Bp4r/Zoeq6+NLJpP+0Zzm0pR8whtGPf1XExKLJBAczGMnSi3It14OiNCStjQjM6NU1okjQGSxgEZN8eBYKg==" + }, + "node_modules/merge-descriptors": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.3.tgz", + "integrity": "sha512-gaNvAS7TZ897/rVaZ0nMtAyxNyi/pdbjbAwUpFQpN70GqnVfOiXpeUUMKRBmzXaSQ8DdTX4/0ms62r2K+hE6mQ==", + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/merge-stream": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/merge-stream/-/merge-stream-2.0.0.tgz", + "integrity": "sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==", + "license": "MIT" + }, + "node_modules/methods": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/methods/-/methods-1.1.2.tgz", + "integrity": "sha512-iclAHeNqNm68zFtnZ0e+1L2yUIdvzNoauKU4WBA3VvH/vPFieF7qfRlwUZU+DA9P9bPXIS90ulxoUoCH23sV2w==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/micromatch": { + "version": "4.0.8", + "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.8.tgz", + "integrity": "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==", + "license": "MIT", + "dependencies": { + "braces": "^3.0.3", + "picomatch": "^2.3.1" + }, + "engines": { + "node": ">=8.6" + } + }, + "node_modules/mime": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/mime/-/mime-1.6.0.tgz", + "integrity": "sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg==", + "bin": { + "mime": "cli.js" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/mime-db": { + "version": "1.52.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", + "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "2.1.35", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", + "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", + "dependencies": { + "mime-db": "1.52.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mimic-fn": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-2.1.0.tgz", + "integrity": "sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/minimatch": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", + "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, + "node_modules/minipass": { + "version": "7.1.2", + "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.2.tgz", + "integrity": "sha512-qOOzS1cBTWYF4BH8fVePDBOO9iptMnGUEZwNc/cMWnTV2nVLZ7VoNWEPHkYczZA0pdoA7dl6e7FL659nX9S2aw==", + "dev": true, + "engines": { + "node": ">=16 || 14 >=14.17" + } + }, + "node_modules/mongodb": { + "version": "6.8.0", + "resolved": "https://registry.npmjs.org/mongodb/-/mongodb-6.8.0.tgz", + "integrity": "sha512-HGQ9NWDle5WvwMnrvUxsFYPd3JEbqD3RgABHBQRuoCEND0qzhsd0iH5ypHsf1eJ+sXmvmyKpP+FLOKY8Il7jMw==", + "dependencies": { + "@mongodb-js/saslprep": "^1.1.5", + "bson": "^6.7.0", + "mongodb-connection-string-url": "^3.0.0" + }, + "engines": { + "node": ">=16.20.1" + }, + "peerDependencies": { + "@aws-sdk/credential-providers": "^3.188.0", + "@mongodb-js/zstd": "^1.1.0", + "gcp-metadata": "^5.2.0", + "kerberos": "^2.0.1", + "mongodb-client-encryption": ">=6.0.0 <7", + "snappy": "^7.2.2", + "socks": "^2.7.1" + }, + "peerDependenciesMeta": { + "@aws-sdk/credential-providers": { + "optional": true + }, + "@mongodb-js/zstd": { + "optional": true + }, + "gcp-metadata": { + "optional": true + }, + "kerberos": { + "optional": true + }, + "mongodb-client-encryption": { + "optional": true + }, + "snappy": { + "optional": true + }, + "socks": { + "optional": true + } + } + }, + "node_modules/mongodb-connection-string-url": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/mongodb-connection-string-url/-/mongodb-connection-string-url-3.0.1.tgz", + "integrity": "sha512-XqMGwRX0Lgn05TDB4PyG2h2kKO/FfWJyCzYQbIhXUxz7ETt0I/FqHjUeqj37irJ+Dl1ZtU82uYyj14u2XsZKfg==", + "dependencies": { + "@types/whatwg-url": "^11.0.2", + "whatwg-url": "^13.0.0" + } + }, + "node_modules/mongodb-memory-server": { + "version": "10.0.1", + "resolved": "https://registry.npmjs.org/mongodb-memory-server/-/mongodb-memory-server-10.0.1.tgz", + "integrity": "sha512-Zoeel0Hn+vPuFESoLJvaHyblu7gWl7hwxsMljetzhEnR7NWaUIvaP7FIu/EKu55Owks8PiuxReKflJWqARbLDw==", + "hasInstallScript": true, + "license": "MIT", + "dependencies": { + "mongodb-memory-server-core": "10.0.1", + "tslib": "^2.6.3" + }, + "engines": { + "node": ">=16.20.1" + } + }, + "node_modules/mongodb-memory-server-core": { + "version": "10.0.1", + "resolved": "https://registry.npmjs.org/mongodb-memory-server-core/-/mongodb-memory-server-core-10.0.1.tgz", + "integrity": "sha512-sJGqoS3saNNJKQjocrqxRISUP6g2N6/D+k1JEqKYo2p9YzUOOvEopxROyvBlqkiVa67/vdf2FV4v+rOvNIHURg==", + "license": "MIT", + "dependencies": { + "async-mutex": "^0.5.0", + "camelcase": "^6.3.0", + "debug": "^4.3.5", + "find-cache-dir": "^3.3.2", + "follow-redirects": "^1.15.6", + "https-proxy-agent": "^7.0.5", + "mongodb": "^6.7.0", + "new-find-package-json": "^2.0.0", + "semver": "^7.6.3", + "tar-stream": "^3.1.7", + "tslib": "^2.6.3", + "yauzl": "^3.1.3" + }, + "engines": { + "node": ">=16.20.1" + } + }, + "node_modules/mongodb-memory-server-core/node_modules/camelcase": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-6.3.0.tgz", + "integrity": "sha512-Gmy6FhYlCY7uOElZUSbxo2UCDH8owEk996gkbrpsgGtrJLM3J7jGxl9Ic7Qwwj4ivOE5AWZWRMecDdF7hqGjFA==", + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/mongodb-memory-server-core/node_modules/debug": { + "version": "4.3.7", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.7.tgz", + "integrity": "sha512-Er2nc/H7RrMXZBFCEim6TCmMk02Z8vLC2Rbi1KEBggpo0fS6l0S1nnapwmIi3yW/+GOJap1Krg4w0Hg80oCqgQ==", + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/mongodb-memory-server-core/node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "license": "MIT" + }, + "node_modules/mongoose": { + "version": "8.6.3", + "resolved": "https://registry.npmjs.org/mongoose/-/mongoose-8.6.3.tgz", + "integrity": "sha512-++yRmm7hjMbqVA/8WeiygTnEfrFbiy+OBjQi49GFJIvCQuSYE56myyQWo4j5hbpcHjhHQU8NukMNGTwAWFWjIw==", + "dependencies": { + "bson": "^6.7.0", + "kareem": "2.6.3", + "mongodb": "6.8.0", + "mpath": "0.9.0", + "mquery": "5.0.0", + "ms": "2.1.3", + "sift": "17.1.3" + }, + "engines": { + "node": ">=16.20.1" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/mongoose" + } + }, + "node_modules/mongoose-sequence": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/mongoose-sequence/-/mongoose-sequence-6.0.1.tgz", + "integrity": "sha512-uXnLCW9pu2V49Xw8BmdXdeRugd2mv+ntu3nT2Bbm33pNRmmvHE2GKA+8BASKoQt960McLX4VL78wkb492f6MoQ==", + "dependencies": { + "async": "^3.2.5", + "lodash": "^4.17.21" + }, + "peerDependencies": { + "mongoose": ">=5" + } + }, + "node_modules/mongoose/node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==" + }, + "node_modules/mpath": { + "version": "0.9.0", + "resolved": "https://registry.npmjs.org/mpath/-/mpath-0.9.0.tgz", + "integrity": "sha512-ikJRQTk8hw5DEoFVxHG1Gn9T/xcjtdnOKIU1JTmGjZZlg9LST2mBLmcX3/ICIbgJydT2GOc15RnNy5mHmzfSew==", + "engines": { + "node": ">=4.0.0" + } + }, + "node_modules/mquery": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/mquery/-/mquery-5.0.0.tgz", + "integrity": "sha512-iQMncpmEK8R8ncT8HJGsGc9Dsp8xcgYMVSbs5jgnm1lFHTZqMJTUWTDx1LBO8+mK3tPNZWFLBghQEIOULSTHZg==", + "dependencies": { + "debug": "4.x" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/mquery/node_modules/debug": { + "version": "4.3.7", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.7.tgz", + "integrity": "sha512-Er2nc/H7RrMXZBFCEim6TCmMk02Z8vLC2Rbi1KEBggpo0fS6l0S1nnapwmIi3yW/+GOJap1Krg4w0Hg80oCqgQ==", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/mquery/node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==" + }, + "node_modules/ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==" + }, + "node_modules/natural-compare": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz", + "integrity": "sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==", + "license": "MIT" + }, + "node_modules/negotiator": { + "version": "0.6.3", + "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.3.tgz", + "integrity": "sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/new-find-package-json": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/new-find-package-json/-/new-find-package-json-2.0.0.tgz", + "integrity": "sha512-lDcBsjBSMlj3LXH2v/FW3txlh2pYTjmbOXPYJD93HI5EwuLzI11tdHSIpUMmfq/IOsldj4Ps8M8flhm+pCK4Ew==", + "license": "MIT", + "dependencies": { + "debug": "^4.3.4" + }, + "engines": { + "node": ">=12.22.0" + } + }, + "node_modules/new-find-package-json/node_modules/debug": { + "version": "4.3.7", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.7.tgz", + "integrity": "sha512-Er2nc/H7RrMXZBFCEim6TCmMk02Z8vLC2Rbi1KEBggpo0fS6l0S1nnapwmIi3yW/+GOJap1Krg4w0Hg80oCqgQ==", + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/new-find-package-json/node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "license": "MIT" + }, + "node_modules/node-int64": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/node-int64/-/node-int64-0.4.0.tgz", + "integrity": "sha512-O5lz91xSOeoXP6DulyHfllpq+Eg00MWitZIbtPfoSEvqIHdl5gfcY6hYzDWnj0qD5tz52PI08u9qUvSVeUBeHw==", + "license": "MIT" + }, + "node_modules/node-releases": { + "version": "2.0.18", + "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.18.tgz", + "integrity": "sha512-d9VeXT4SJ7ZeOqGX6R5EM022wpL+eWPooLI+5UpWn2jCT1aosUQEhQP214x33Wkwx3JQMvIm+tIoVOdodFS40g==", + "license": "MIT" + }, + "node_modules/nodemon": { + "version": "3.1.7", + "resolved": "https://registry.npmjs.org/nodemon/-/nodemon-3.1.7.tgz", + "integrity": "sha512-hLj7fuMow6f0lbB0cD14Lz2xNjwsyruH251Pk4t/yIitCFJbmY1myuLlHm/q06aST4jg6EgAh74PIBBrRqpVAQ==", + "dev": true, + "dependencies": { + "chokidar": "^3.5.2", + "debug": "^4", + "ignore-by-default": "^1.0.1", + "minimatch": "^3.1.2", + "pstree.remy": "^1.1.8", + "semver": "^7.5.3", + "simple-update-notifier": "^2.0.0", + "supports-color": "^5.5.0", + "touch": "^3.1.0", + "undefsafe": "^2.0.5" + }, + "bin": { + "nodemon": "bin/nodemon.js" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/nodemon" + } + }, + "node_modules/nodemon/node_modules/debug": { + "version": "4.3.7", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.7.tgz", + "integrity": "sha512-Er2nc/H7RrMXZBFCEim6TCmMk02Z8vLC2Rbi1KEBggpo0fS6l0S1nnapwmIi3yW/+GOJap1Krg4w0Hg80oCqgQ==", + "dev": true, + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/nodemon/node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "dev": true + }, + "node_modules/normalize-path": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz", + "integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/npm-run-path": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/npm-run-path/-/npm-run-path-4.0.1.tgz", + "integrity": "sha512-S48WzZW777zhNIrn7gxOlISNAqi9ZC/uQFnRdbeIHhZhCA6UqpkOT8T1G7BvfdgP4Er8gF4sUbaS0i7QvIfCWw==", + "license": "MIT", + "dependencies": { + "path-key": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/object-assign": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", + "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/object-inspect": { + "version": "1.13.2", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.2.tgz", + "integrity": "sha512-IRZSRuzJiynemAXPYtPe5BoI/RESNYR7TYm50MC5Mqbd3Jmw5y790sErYw3V6SryFJD64b74qQQs9wn5Bg/k3g==", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/on-finished": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz", + "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==", + "dependencies": { + "ee-first": "1.1.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", + "license": "ISC", + "dependencies": { + "wrappy": "1" + } + }, + "node_modules/onetime": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/onetime/-/onetime-5.1.2.tgz", + "integrity": "sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg==", + "license": "MIT", + "dependencies": { + "mimic-fn": "^2.1.0" + }, + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/p-limit": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz", + "integrity": "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==", + "license": "MIT", + "dependencies": { + "yocto-queue": "^0.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/p-locate": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-4.1.0.tgz", + "integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==", + "license": "MIT", + "dependencies": { + "p-limit": "^2.2.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/p-locate/node_modules/p-limit": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz", + "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==", + "license": "MIT", + "dependencies": { + "p-try": "^2.0.0" + }, + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/p-try": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/p-try/-/p-try-2.2.0.tgz", + "integrity": "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/package-json-from-dist": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/package-json-from-dist/-/package-json-from-dist-1.0.0.tgz", + "integrity": "sha512-dATvCeZN/8wQsGywez1mzHtTlP22H8OEfPrVMLNr4/eGa+ijtLn/6M5f0dY8UKNrC2O9UCU6SSoG3qRKnt7STw==", + "dev": true + }, + "node_modules/parse-json": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-5.2.0.tgz", + "integrity": "sha512-ayCKvm/phCGxOkYRSCM82iDwct8/EonSEgCSxWxD7ve6jHggsFl4fZVQBPRNgQoKiuV/odhFrGzQXZwbifC8Rg==", + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.0.0", + "error-ex": "^1.3.1", + "json-parse-even-better-errors": "^2.3.0", + "lines-and-columns": "^1.1.6" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/parseurl": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", + "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/path-exists": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", + "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/path-is-absolute": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", + "integrity": "sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/path-key": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", + "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", + "engines": { + "node": ">=8" + } + }, + "node_modules/path-parse": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz", + "integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==", + "license": "MIT" + }, + "node_modules/path-scurry": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-2.0.0.tgz", + "integrity": "sha512-ypGJsmGtdXUOeM5u93TyeIEfEhM6s+ljAhrk5vAvSx8uyY/02OvrZnA0YNGUrPXfpJMgI1ODd3nwz8Npx4O4cg==", + "dev": true, + "dependencies": { + "lru-cache": "^11.0.0", + "minipass": "^7.1.2" + }, + "engines": { + "node": "20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/path-to-regexp": { + "version": "0.1.10", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.10.tgz", + "integrity": "sha512-7lf7qcQidTku0Gu3YDPc8DJ1q7OOucfa/BSsIwjuh56VU7katFvuM8hULfkwB3Fns/rsVF7PwPKVw1sl5KQS9w==" + }, + "node_modules/pend": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/pend/-/pend-1.2.0.tgz", + "integrity": "sha512-F3asv42UuXchdzt+xXqfW1OGlVBe+mxa2mqI0pg5yAHZPvFmY3Y6drSf/GQ1A86WgWEN9Kzh/WrgKa6iGcHXLg==", + "license": "MIT" + }, + "node_modules/picocolors": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.0.tgz", + "integrity": "sha512-TQ92mBOW0l3LeMeyLV6mzy/kWr8lkd/hp3mTg7wYK7zJhuBStmGMBG0BdeDZS/dZx1IukaX6Bk11zcln25o1Aw==", + "license": "ISC" + }, + "node_modules/picomatch": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz", + "integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==", + "engines": { + "node": ">=8.6" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/pirates": { + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/pirates/-/pirates-4.0.6.tgz", + "integrity": "sha512-saLsH7WeYYPiD25LDuLRRY/i+6HaPYr6G1OUlN39otzkSTxKnubR9RTxS3/Kk50s1g2JTgFwWQDQyplC5/SHZg==", + "license": "MIT", + "engines": { + "node": ">= 6" + } + }, + "node_modules/pkg-dir": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/pkg-dir/-/pkg-dir-4.2.0.tgz", + "integrity": "sha512-HRDzbaKjC+AOWVXxAU/x54COGeIv9eb+6CkDSQoNTt4XyWoIJvuPsXizxu/Fr23EiekbtZwmh1IcIG/l/a10GQ==", + "license": "MIT", + "dependencies": { + "find-up": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/pretty-format": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-29.7.0.tgz", + "integrity": "sha512-Pdlw/oPxN+aXdmM9R00JVC9WVFoCLTKJvDVLgmJ+qAffBMxsV85l/Lu7sNx4zSzPyoL2euImuEwHhOXdEgNFZQ==", + "license": "MIT", + "dependencies": { + "@jest/schemas": "^29.6.3", + "ansi-styles": "^5.0.0", + "react-is": "^18.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/pretty-format/node_modules/ansi-styles": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-5.2.0.tgz", + "integrity": "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==", + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/prompts": { + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/prompts/-/prompts-2.4.2.tgz", + "integrity": "sha512-NxNv/kLguCA7p3jE8oL2aEBsrJWgAakBpgmgK6lpPWV+WuOmY6r2/zbAVnP+T8bQlA0nzHXSJSJW0Hq7ylaD2Q==", + "license": "MIT", + "dependencies": { + "kleur": "^3.0.3", + "sisteransi": "^1.0.5" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/proxy-addr": { + "version": "2.0.7", + "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz", + "integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==", + "dependencies": { + "forwarded": "0.2.0", + "ipaddr.js": "1.9.1" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/pstree.remy": { + "version": "1.1.8", + "resolved": "https://registry.npmjs.org/pstree.remy/-/pstree.remy-1.1.8.tgz", + "integrity": "sha512-77DZwxQmxKnu3aR542U+X8FypNzbfJ+C5XQDk3uWjWxn6151aIMGthWYRXTqT1E5oJvg+ljaa2OJi+VfvCOQ8w==", + "dev": true + }, + "node_modules/punycode": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", + "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==", + "engines": { + "node": ">=6" + } + }, + "node_modules/pure-rand": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/pure-rand/-/pure-rand-6.1.0.tgz", + "integrity": "sha512-bVWawvoZoBYpp6yIoQtQXHZjmz35RSVHnUOTefl8Vcjr8snTPY1wnpSPMWekcFwbxI6gtmT7rSYPFvz71ldiOA==", + "funding": [ + { + "type": "individual", + "url": "https://github.com/sponsors/dubzzz" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fast-check" + } + ], + "license": "MIT" + }, + "node_modules/qs": { + "version": "6.13.0", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.13.0.tgz", + "integrity": "sha512-+38qI9SOr8tfZ4QmJNplMUxqjbe7LKvvZgWdExBOmd+egZTtjLB67Gu0HRX3u/XOq7UU2Nx6nsjvS16Z9uwfpg==", + "dependencies": { + "side-channel": "^1.0.6" + }, + "engines": { + "node": ">=0.6" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/queue-tick": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/queue-tick/-/queue-tick-1.0.1.tgz", + "integrity": "sha512-kJt5qhMxoszgU/62PLP1CJytzd2NKetjSRnyuj31fDd3Rlcz3fzlFdFLD1SItunPwyqEOkca6GbV612BWfaBag==", + "license": "MIT" + }, + "node_modules/range-parser": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz", + "integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/raw-body": { + "version": "2.5.2", + "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.5.2.tgz", + "integrity": "sha512-8zGqypfENjCIqGhgXToC8aB2r7YrBX+AQAfIPs/Mlk+BtPTztOvTS01NRW/3Eh60J+a48lt8qsCzirQ6loCVfA==", + "dependencies": { + "bytes": "3.1.2", + "http-errors": "2.0.0", + "iconv-lite": "0.4.24", + "unpipe": "1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/react-is": { + "version": "18.3.1", + "resolved": "https://registry.npmjs.org/react-is/-/react-is-18.3.1.tgz", + "integrity": "sha512-/LLMVyas0ljjAtoYiPqYiL8VWXzUUdThrmU5+n20DZv+a+ClRoevUzw5JxU+Ieh5/c87ytoTBV9G1FiKfNJdmg==", + "license": "MIT" + }, + "node_modules/readdirp": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.6.0.tgz", + "integrity": "sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==", + "dev": true, + "dependencies": { + "picomatch": "^2.2.1" + }, + "engines": { + "node": ">=8.10.0" + } + }, + "node_modules/require-directory": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", + "integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/resolve": { + "version": "1.22.8", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.8.tgz", + "integrity": "sha512-oKWePCxqpd6FlLvGV1VU0x7bkPmmCNolxzjMf4NczoDnQcIWrAF+cPtZn5i6n+RfD2d9i0tzpKnG6Yk168yIyw==", + "license": "MIT", + "dependencies": { + "is-core-module": "^2.13.0", + "path-parse": "^1.0.7", + "supports-preserve-symlinks-flag": "^1.0.0" + }, + "bin": { + "resolve": "bin/resolve" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/resolve-cwd": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/resolve-cwd/-/resolve-cwd-3.0.0.tgz", + "integrity": "sha512-OrZaX2Mb+rJCpH/6CpSqt9xFVpN++x01XnN2ie9g6P5/3xelLAkXWVADpdz1IHD/KFfEXyE6V0U01OQ3UO2rEg==", + "license": "MIT", + "dependencies": { + "resolve-from": "^5.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/resolve-from": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-5.0.0.tgz", + "integrity": "sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/resolve-pkg-maps": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/resolve-pkg-maps/-/resolve-pkg-maps-1.0.0.tgz", + "integrity": "sha512-seS2Tj26TBVOC2NIc2rOe2y2ZO7efxITtLZcGSOnHHNOQ7CkiUBfw0Iw2ck6xkIhPwLhKNLS8BO+hEpngQlqzw==", + "funding": { + "url": "https://github.com/privatenumber/resolve-pkg-maps?sponsor=1" + } + }, + "node_modules/resolve.exports": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/resolve.exports/-/resolve.exports-2.0.2.tgz", + "integrity": "sha512-X2UW6Nw3n/aMgDVy+0rSqgHlv39WZAlZrXCdnbyEiKm17DSqHX4MmQMaST3FbeWR5FTuRcUwYAziZajji0Y7mg==", + "license": "MIT", + "engines": { + "node": ">=10" + } + }, + "node_modules/rimraf": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-6.0.1.tgz", + "integrity": "sha512-9dkvaxAsk/xNXSJzMgFqqMCuFgt2+KsOFek3TMLfo8NCPfWpBmqwyNn5Y+NX56QUYfCtsyhF3ayiboEoUmJk/A==", + "dev": true, + "dependencies": { + "glob": "^11.0.0", + "package-json-from-dist": "^1.0.0" + }, + "bin": { + "rimraf": "dist/esm/bin.mjs" + }, + "engines": { + "node": "20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] + }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==" + }, + "node_modules/semver": { + "version": "7.6.3", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.6.3.tgz", + "integrity": "sha512-oVekP1cKtI+CTDvHWYFUcMtsK/00wmAEfyqKfNdARm8u1wNVhSgaX7A8d4UuIlUI5e84iEwOhs7ZPYRmzU9U6A==", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/send": { + "version": "0.19.0", + "resolved": "https://registry.npmjs.org/send/-/send-0.19.0.tgz", + "integrity": "sha512-dW41u5VfLXu8SJh5bwRmyYUbAoSB3c9uQh6L8h/KtsFREPWpbX1lrljJo186Jc4nmci/sGUZ9a0a0J2zgfq2hw==", + "dependencies": { + "debug": "2.6.9", + "depd": "2.0.0", + "destroy": "1.2.0", + "encodeurl": "~1.0.2", + "escape-html": "~1.0.3", + "etag": "~1.8.1", + "fresh": "0.5.2", + "http-errors": "2.0.0", + "mime": "1.6.0", + "ms": "2.1.3", + "on-finished": "2.4.1", + "range-parser": "~1.2.1", + "statuses": "2.0.1" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/send/node_modules/encodeurl": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-1.0.2.tgz", + "integrity": "sha512-TPJXq8JqFaVYm2CWmPvnP2Iyo4ZSM7/QKcSmuMLDObfpH5fi7RUGmd/rTDf+rut/saiDiQEeVTNgAmJEdAOx0w==", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/send/node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==" + }, + "node_modules/serve-static": { + "version": "1.16.2", + "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.16.2.tgz", + "integrity": "sha512-VqpjJZKadQB/PEbEwvFdO43Ax5dFBZ2UECszz8bQ7pi7wt//PWe1P6MN7eCnjsatYtBT6EuiClbjSWP2WrIoTw==", + "dependencies": { + "encodeurl": "~2.0.0", + "escape-html": "~1.0.3", + "parseurl": "~1.3.3", + "send": "0.19.0" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/set-function-length": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/set-function-length/-/set-function-length-1.2.2.tgz", + "integrity": "sha512-pgRc4hJ4/sNjWCSS9AmnS40x3bNMDTknHgL5UaMBTMyJnU90EgWh1Rz+MC9eFu4BuN/UwZjKQuY/1v3rM7HMfg==", + "dependencies": { + "define-data-property": "^1.1.4", + "es-errors": "^1.3.0", + "function-bind": "^1.1.2", + "get-intrinsic": "^1.2.4", + "gopd": "^1.0.1", + "has-property-descriptors": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/setprototypeof": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", + "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==" + }, + "node_modules/shebang-command": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", + "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", + "dependencies": { + "shebang-regex": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/shebang-regex": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", + "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", + "engines": { + "node": ">=8" + } + }, + "node_modules/side-channel": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.0.6.tgz", + "integrity": "sha512-fDW/EZ6Q9RiO8eFG8Hj+7u/oW+XrPTIChwCOM2+th2A6OblDtYYIpve9m+KvI9Z4C9qSEXlaGR6bTEYHReuglA==", + "dependencies": { + "call-bind": "^1.0.7", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.4", + "object-inspect": "^1.13.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/sift": { + "version": "17.1.3", + "resolved": "https://registry.npmjs.org/sift/-/sift-17.1.3.tgz", + "integrity": "sha512-Rtlj66/b0ICeFzYTuNvX/EF1igRbbnGSvEyT79McoZa/DeGhMyC5pWKOEsZKnpkqtSeovd5FL/bjHWC3CIIvCQ==" + }, + "node_modules/signal-exit": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz", + "integrity": "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==", + "dev": true, + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/simple-update-notifier": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/simple-update-notifier/-/simple-update-notifier-2.0.0.tgz", + "integrity": "sha512-a2B9Y0KlNXl9u/vsW6sTIu9vGEpfKu2wRV6l1H3XEas/0gUIzGzBoP/IouTcUQbm9JWZLH3COxyn03TYlFax6w==", + "dev": true, + "dependencies": { + "semver": "^7.5.3" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/sisteransi": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/sisteransi/-/sisteransi-1.0.5.tgz", + "integrity": "sha512-bLGGlR1QxBcynn2d5YmDX4MGjlZvy2MRBDRNHLJ8VI6l6+9FUiyTFNJ0IveOSP0bcXgVDPRcfGqA0pjaqUpfVg==", + "license": "MIT" + }, + "node_modules/slash": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/slash/-/slash-3.0.0.tgz", + "integrity": "sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/smart-buffer": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/smart-buffer/-/smart-buffer-4.2.0.tgz", + "integrity": "sha512-94hK0Hh8rPqQl2xXc3HsaBoOXKV20MToPkcXvwbISWLEs+64sBq5kFgn2kJDHb1Pry9yrP0dxrCI9RRci7RXKg==", + "devOptional": true, + "engines": { + "node": ">= 6.0.0", + "npm": ">= 3.0.0" + } + }, + "node_modules/socks": { + "version": "2.8.3", + "resolved": "https://registry.npmjs.org/socks/-/socks-2.8.3.tgz", + "integrity": "sha512-l5x7VUUWbjVFbafGLxPWkYsHIhEvmF85tbIeFZWc8ZPtoMyybuEhL7Jye/ooC4/d48FgOjSJXgsF/AJPYCW8Zw==", + "devOptional": true, + "dependencies": { + "ip-address": "^9.0.5", + "smart-buffer": "^4.2.0" + }, + "engines": { + "node": ">= 10.0.0", + "npm": ">= 3.0.0" + } + }, + "node_modules/source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/source-map-support": { + "version": "0.5.13", + "resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.13.tgz", + "integrity": "sha512-SHSKFHadjVA5oR4PPqhtAVdcBWwRYVd6g6cAXnIbRiIwc2EhPrTuKUBdSLvlEKyIP3GCf89fltvcZiP9MMFA1w==", + "license": "MIT", + "dependencies": { + "buffer-from": "^1.0.0", + "source-map": "^0.6.0" + } + }, + "node_modules/sparse-bitfield": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/sparse-bitfield/-/sparse-bitfield-3.0.3.tgz", + "integrity": "sha512-kvzhi7vqKTfkh0PZU+2D2PIllw2ymqJKujUcyPMd9Y75Nv4nPbGJZXNhxsgdQab2BmlDct1YnfQCguEvHr7VsQ==", + "dependencies": { + "memory-pager": "^1.0.2" + } + }, + "node_modules/sprintf-js": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.1.3.tgz", + "integrity": "sha512-Oo+0REFV59/rz3gfJNKQiBlwfHaSESl1pcGyABQsnnIfWOFt6JNj5gCog2U6MLZ//IGYD+nA8nI+mTShREReaA==", + "devOptional": true + }, + "node_modules/stack-utils": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/stack-utils/-/stack-utils-2.0.6.tgz", + "integrity": "sha512-XlkWvfIm6RmsWtNJx+uqtKLS8eqFbxUg0ZzLXqY0caEy9l7hruX8IpiDnjsLavoBgqCCR71TqWO8MaXYheJ3RQ==", + "license": "MIT", + "dependencies": { + "escape-string-regexp": "^2.0.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/statuses": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.1.tgz", + "integrity": "sha512-RwNA9Z/7PrK06rYLIzFMlaF+l73iwpzsqRIFgbMLbTcLD6cOao82TaWefPXQvB2fOC4AjuYSEndS7N/mTCbkdQ==", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/streamx": { + "version": "2.20.1", + "resolved": "https://registry.npmjs.org/streamx/-/streamx-2.20.1.tgz", + "integrity": "sha512-uTa0mU6WUC65iUvzKH4X9hEdvSW7rbPxPtwfWiLMSj3qTdQbAiUboZTxauKfpFuGIGa1C2BYijZ7wgdUXICJhA==", + "license": "MIT", + "dependencies": { + "fast-fifo": "^1.3.2", + "queue-tick": "^1.0.1", + "text-decoder": "^1.1.0" + }, + "optionalDependencies": { + "bare-events": "^2.2.0" + } + }, + "node_modules/string-length": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/string-length/-/string-length-4.0.2.tgz", + "integrity": "sha512-+l6rNN5fYHNhZZy41RXsYptCjA2Igmq4EG7kZAYFQI1E1VTXarr6ZPXBg6eq7Y6eK4FEhY6AJlyuFIb/v/S0VQ==", + "license": "MIT", + "dependencies": { + "char-regex": "^1.0.2", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/string-length/node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/string-length/node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "license": "MIT", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/string-width": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-5.1.2.tgz", + "integrity": "sha512-HnLOCR3vjcY8beoNLtcjZ5/nxn2afmME6lhrDrebokqMap+XbeW8n9TXpPDOqdGK5qcI3oT0GKTW6wC7EMiVqA==", + "dev": true, + "dependencies": { + "eastasianwidth": "^0.2.0", + "emoji-regex": "^9.2.2", + "strip-ansi": "^7.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/string-width-cjs": { + "name": "string-width", + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "dev": true, + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/string-width-cjs/node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/string-width-cjs/node_modules/emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", + "dev": true + }, + "node_modules/string-width-cjs/node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "dev": true, + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-ansi": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.1.0.tgz", + "integrity": "sha512-iq6eVVI64nQQTRYq2KtEg2d2uU7LElhTJwsH4YzIHZshxlgZms/wIc4VoDQTlG/IvVIrBKG06CrZnp0qv7hkcQ==", + "dev": true, + "dependencies": { + "ansi-regex": "^6.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/strip-ansi?sponsor=1" + } + }, + "node_modules/strip-ansi-cjs": { + "name": "strip-ansi", + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "dev": true, + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-ansi-cjs/node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-bom": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-4.0.0.tgz", + "integrity": "sha512-3xurFv5tEgii33Zi8Jtp55wEIILR9eh34FAW00PZf+JnSsTmV/ioewSgQl97JHvgjoRGwPShsWm+IdrxB35d0w==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-final-newline": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/strip-final-newline/-/strip-final-newline-2.0.0.tgz", + "integrity": "sha512-BrpvfNAE3dcvq7ll3xVumzjKjZQ5tI1sEUIKr3Uoks0XUl45St3FlatVqef9prk4jRDzhW6WZg+3bk93y6pLjA==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/strip-json-comments": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.1.1.tgz", + "integrity": "sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==", + "license": "MIT", + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/strnum": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/strnum/-/strnum-1.0.5.tgz", + "integrity": "sha512-J8bbNyKKXl5qYcR36TIO8W3mVGVHrmmxsd5PAItGkmyzwJvybiw2IVq5nqd0i4LSNSkB/sx9VHllbfFdr9k1JA==", + "optional": true + }, + "node_modules/superagent": { + "version": "9.0.2", + "resolved": "https://registry.npmjs.org/superagent/-/superagent-9.0.2.tgz", + "integrity": "sha512-xuW7dzkUpcJq7QnhOsnNUgtYp3xRwpt2F7abdRYIpCsAt0hhUqia0EdxyXZQQpNmGtsCzYHryaKSV3q3GJnq7w==", + "license": "MIT", + "dependencies": { + "component-emitter": "^1.3.0", + "cookiejar": "^2.1.4", + "debug": "^4.3.4", + "fast-safe-stringify": "^2.1.1", + "form-data": "^4.0.0", + "formidable": "^3.5.1", + "methods": "^1.1.2", + "mime": "2.6.0", + "qs": "^6.11.0" + }, + "engines": { + "node": ">=14.18.0" + } + }, + "node_modules/superagent/node_modules/debug": { + "version": "4.3.7", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.7.tgz", + "integrity": "sha512-Er2nc/H7RrMXZBFCEim6TCmMk02Z8vLC2Rbi1KEBggpo0fS6l0S1nnapwmIi3yW/+GOJap1Krg4w0Hg80oCqgQ==", + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/superagent/node_modules/mime": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/mime/-/mime-2.6.0.tgz", + "integrity": "sha512-USPkMeET31rOMiarsBNIHZKLGgvKc/LrjofAnBlOttf5ajRvqiRA8QsenbcooctK6d6Ts6aqZXBA+XbkKthiQg==", + "license": "MIT", + "bin": { + "mime": "cli.js" + }, + "engines": { + "node": ">=4.0.0" + } + }, + "node_modules/superagent/node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "license": "MIT" + }, + "node_modules/supertest": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/supertest/-/supertest-7.0.0.tgz", + "integrity": "sha512-qlsr7fIC0lSddmA3tzojvzubYxvlGtzumcdHgPwbFWMISQwL22MhM2Y3LNt+6w9Yyx7559VW5ab70dgphm8qQA==", + "license": "MIT", + "dependencies": { + "methods": "^1.1.2", + "superagent": "^9.0.1" + }, + "engines": { + "node": ">=14.18.0" + } + }, + "node_modules/supports-color": { + "version": "5.5.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", + "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", + "dependencies": { + "has-flag": "^3.0.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/supports-preserve-symlinks-flag": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz", + "integrity": "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/tar-stream": { + "version": "3.1.7", + "resolved": "https://registry.npmjs.org/tar-stream/-/tar-stream-3.1.7.tgz", + "integrity": "sha512-qJj60CXt7IU1Ffyc3NJMjh6EkuCFej46zUqJ4J7pqYlThyd9bO0XBTmcOIhSzZJVWfsLks0+nle/j538YAW9RQ==", + "license": "MIT", + "dependencies": { + "b4a": "^1.6.4", + "fast-fifo": "^1.2.0", + "streamx": "^2.15.0" + } + }, + "node_modules/test-exclude": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/test-exclude/-/test-exclude-6.0.0.tgz", + "integrity": "sha512-cAGWPIyOHU6zlmg88jwm7VRyXnMN7iV68OGAbYDk/Mh/xC/pzVPlQtY6ngoIH/5/tciuhGfvESU8GrHrcxD56w==", + "license": "ISC", + "dependencies": { + "@istanbuljs/schema": "^0.1.2", + "glob": "^7.1.4", + "minimatch": "^3.0.4" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/test-exclude/node_modules/glob": { + "version": "7.2.3", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz", + "integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==", + "deprecated": "Glob versions prior to v9 are no longer supported", + "license": "ISC", + "dependencies": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.1.1", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + }, + "engines": { + "node": "*" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/text-decoder": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/text-decoder/-/text-decoder-1.2.0.tgz", + "integrity": "sha512-n1yg1mOj9DNpk3NeZOx7T6jchTbyJS3i3cucbNN6FcdPriMZx7NsgrGpWWdWZZGxD7ES1XB+3uoqHMgOKaN+fg==", + "license": "Apache-2.0", + "dependencies": { + "b4a": "^1.6.4" + } + }, + "node_modules/tmpl": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/tmpl/-/tmpl-1.0.5.tgz", + "integrity": "sha512-3f0uOEAQwIqGuWW2MVzYg8fV/QNnc/IpuJNG837rLuczAaLVHslWHZQj4IGiEl5Hs3kkbhwL9Ab7Hrsmuj+Smw==", + "license": "BSD-3-Clause" + }, + "node_modules/to-fast-properties": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/to-fast-properties/-/to-fast-properties-2.0.0.tgz", + "integrity": "sha512-/OaKK0xYrs3DmxRYqL/yDc+FxFUVYhDlXMhRmv3z915w2HF1tnN1omB354j8VUGO/hbRzyD6Y3sA7v7GS/ceog==", + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/to-regex-range": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", + "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", + "dependencies": { + "is-number": "^7.0.0" + }, + "engines": { + "node": ">=8.0" + } + }, + "node_modules/toidentifier": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz", + "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==", + "engines": { + "node": ">=0.6" + } + }, + "node_modules/touch": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/touch/-/touch-3.1.1.tgz", + "integrity": "sha512-r0eojU4bI8MnHr8c5bNo7lJDdI2qXlWWJk6a9EAFG7vbhTjElYhBVS3/miuE0uOuoLdb8Mc/rVfsmm6eo5o9GA==", + "dev": true, + "bin": { + "nodetouch": "bin/nodetouch.js" + } + }, + "node_modules/tr46": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-4.1.1.tgz", + "integrity": "sha512-2lv/66T7e5yNyhAAC4NaKe5nVavzuGJQVVtRYLyQ2OI8tsJ61PMLlelehb0wi2Hx6+hT/OJUWZcw8MjlSRnxvw==", + "dependencies": { + "punycode": "^2.3.0" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/ts-jest": { + "version": "29.2.5", + "resolved": "https://registry.npmjs.org/ts-jest/-/ts-jest-29.2.5.tgz", + "integrity": "sha512-KD8zB2aAZrcKIdGk4OwpJggeLcH1FgrICqDSROWqlnJXGCXK4Mn6FcdK2B6670Xr73lHMG1kHw8R87A0ecZ+vA==", + "dev": true, + "license": "MIT", + "dependencies": { + "bs-logger": "^0.2.6", + "ejs": "^3.1.10", + "fast-json-stable-stringify": "^2.1.0", + "jest-util": "^29.0.0", + "json5": "^2.2.3", + "lodash.memoize": "^4.1.2", + "make-error": "^1.3.6", + "semver": "^7.6.3", + "yargs-parser": "^21.1.1" + }, + "bin": { + "ts-jest": "cli.js" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || ^18.0.0 || >=20.0.0" + }, + "peerDependencies": { + "@babel/core": ">=7.0.0-beta.0 <8", + "@jest/transform": "^29.0.0", + "@jest/types": "^29.0.0", + "babel-jest": "^29.0.0", + "jest": "^29.0.0", + "typescript": ">=4.3 <6" + }, + "peerDependenciesMeta": { + "@babel/core": { + "optional": true + }, + "@jest/transform": { + "optional": true + }, + "@jest/types": { + "optional": true + }, + "babel-jest": { + "optional": true + }, + "esbuild": { + "optional": true + } + } + }, + "node_modules/ts-node": { + "version": "10.9.2", + "resolved": "https://registry.npmjs.org/ts-node/-/ts-node-10.9.2.tgz", + "integrity": "sha512-f0FFpIdcHgn8zcPSbf1dRevwt047YMnaiJM3u2w2RewrB+fob/zePZcrOyQoLMMO7aBIddLcQIEK5dYjkLnGrQ==", + "dependencies": { + "@cspotcode/source-map-support": "^0.8.0", + "@tsconfig/node10": "^1.0.7", + "@tsconfig/node12": "^1.0.7", + "@tsconfig/node14": "^1.0.0", + "@tsconfig/node16": "^1.0.2", + "acorn": "^8.4.1", + "acorn-walk": "^8.1.1", + "arg": "^4.1.0", + "create-require": "^1.1.0", + "diff": "^4.0.1", + "make-error": "^1.1.1", + "v8-compile-cache-lib": "^3.0.1", + "yn": "3.1.1" + }, + "bin": { + "ts-node": "dist/bin.js", + "ts-node-cwd": "dist/bin-cwd.js", + "ts-node-esm": "dist/bin-esm.js", + "ts-node-script": "dist/bin-script.js", + "ts-node-transpile-only": "dist/bin-transpile.js", + "ts-script": "dist/bin-script-deprecated.js" + }, + "peerDependencies": { + "@swc/core": ">=1.2.50", + "@swc/wasm": ">=1.2.50", + "@types/node": "*", + "typescript": ">=2.7" + }, + "peerDependenciesMeta": { + "@swc/core": { + "optional": true + }, + "@swc/wasm": { + "optional": true + } + } + }, + "node_modules/tslib": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.7.0.tgz", + "integrity": "sha512-gLXCKdN1/j47AiHiOkJN69hJmcbGTHI0ImLmbYLHykhgeN0jVGola9yVjFgzCUklsZQMW55o+dW7IXv3RCXDzA==" + }, + "node_modules/tsx": { + "version": "4.19.1", + "resolved": "https://registry.npmjs.org/tsx/-/tsx-4.19.1.tgz", + "integrity": "sha512-0flMz1lh74BR4wOvBjuh9olbnwqCPc35OOlfyzHba0Dc+QNUeWX/Gq2YTbnwcWPO3BMd8fkzRVrHcsR+a7z7rA==", + "dependencies": { + "esbuild": "~0.23.0", + "get-tsconfig": "^4.7.5" + }, + "bin": { + "tsx": "dist/cli.mjs" + }, + "engines": { + "node": ">=18.0.0" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + } + }, + "node_modules/type-detect": { + "version": "4.0.8", + "resolved": "https://registry.npmjs.org/type-detect/-/type-detect-4.0.8.tgz", + "integrity": "sha512-0fr/mIH1dlO+x7TlcMy+bIDqKPsw/70tVyeHW787goQjhmqaZe10uwLujubK9q9Lg6Fiho1KUKDYz0Z7k7g5/g==", + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/type-fest": { + "version": "0.21.3", + "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.21.3.tgz", + "integrity": "sha512-t0rzBq87m3fVcduHDUFhKmyyX+9eo6WQjZvf51Ea/M0Q7+T374Jp1aUiyUl0GKxp8M/OETVHSDvmkyPgvX+X2w==", + "license": "(MIT OR CC0-1.0)", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/type-is": { + "version": "1.6.18", + "resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz", + "integrity": "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==", + "dependencies": { + "media-typer": "0.3.0", + "mime-types": "~2.1.24" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/typescript": { + "version": "5.6.2", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.6.2.tgz", + "integrity": "sha512-NW8ByodCSNCwZeghjN3o+JX5OFH0Ojg6sadjEKY4huZ52TqbJTJnDo5+Tw98lSy63NZvi4n+ez5m2u5d4PkZyw==", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/undefsafe": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/undefsafe/-/undefsafe-2.0.5.tgz", + "integrity": "sha512-WxONCrssBM8TSPRqN5EmsjVrsv4A8X12J4ArBiiayv3DyyG3ZlIg6yysuuSYdZsVz3TKcTg2fd//Ujd4CHV1iA==", + "dev": true + }, + "node_modules/undici-types": { + "version": "6.19.8", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.19.8.tgz", + "integrity": "sha512-ve2KP6f/JnbPBFyobGHuerC9g1FYGn/F8n1LWTwNxCEzd6IfqTwUQcNXgEtmmQ6DlRrC1hrSrBnCZPokRrDHjw==" + }, + "node_modules/unpipe": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", + "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/update-browserslist-db": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.1.0.tgz", + "integrity": "sha512-EdRAaAyk2cUE1wOf2DkEhzxqOQvFOoRJFNS6NeyJ01Gp2beMRpBAINjM2iDXE3KCuKhwnvHIQCJm6ThL2Z+HzQ==", + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "escalade": "^3.1.2", + "picocolors": "^1.0.1" + }, + "bin": { + "update-browserslist-db": "cli.js" + }, + "peerDependencies": { + "browserslist": ">= 4.21.0" + } + }, + "node_modules/utils-merge": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz", + "integrity": "sha512-pMZTvIkT1d+TFGvDOqodOclx0QWkkgi6Tdoa8gC8ffGAAqz9pzPTZWAybbsHHoED/ztMtkv/VoYTYyShUn81hA==", + "engines": { + "node": ">= 0.4.0" + } + }, + "node_modules/uuid": { + "version": "9.0.1", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-9.0.1.tgz", + "integrity": "sha512-b+1eJOlsR9K8HJpow9Ok3fiWOWSIcIzXodvv0rQjVoOVNpWMpxf1wZNpt4y9h10odCNrqnYp1OBzRktckBe3sA==", + "funding": [ + "https://github.com/sponsors/broofa", + "https://github.com/sponsors/ctavan" + ], + "optional": true, + "bin": { + "uuid": "dist/bin/uuid" + } + }, + "node_modules/v8-compile-cache-lib": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/v8-compile-cache-lib/-/v8-compile-cache-lib-3.0.1.tgz", + "integrity": "sha512-wa7YjyUGfNZngI/vtK0UHAN+lgDCxBPCylVXGp0zu59Fz5aiGtNXaq3DhIov063MorB+VfufLh3JlF2KdTK3xg==" + }, + "node_modules/v8-to-istanbul": { + "version": "9.3.0", + "resolved": "https://registry.npmjs.org/v8-to-istanbul/-/v8-to-istanbul-9.3.0.tgz", + "integrity": "sha512-kiGUalWN+rgBJ/1OHZsBtU4rXZOfj/7rKQxULKlIzwzQSvMJUUNgPwJEEh7gU6xEVxC0ahoOBvN2YI8GH6FNgA==", + "license": "ISC", + "dependencies": { + "@jridgewell/trace-mapping": "^0.3.12", + "@types/istanbul-lib-coverage": "^2.0.1", + "convert-source-map": "^2.0.0" + }, + "engines": { + "node": ">=10.12.0" + } + }, + "node_modules/v8-to-istanbul/node_modules/@jridgewell/trace-mapping": { + "version": "0.3.25", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.25.tgz", + "integrity": "sha512-vNk6aEwybGtawWmy/PzwnGDOjCkLWSD2wqvjGGAgOAwCGWySYXfYoxt00IJkTF+8Lb57DwOb3Aa0o9CApepiYQ==", + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, + "node_modules/validator": { + "version": "13.12.0", + "resolved": "https://registry.npmjs.org/validator/-/validator-13.12.0.tgz", + "integrity": "sha512-c1Q0mCiPlgdTVVVIJIrBuxNicYE+t/7oKeI9MWLj3fh/uq2Pxh/3eeWbVZ4OcGW1TUf53At0njHw5SMdA3tmMg==", + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/vary": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", + "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/walker": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/walker/-/walker-1.0.8.tgz", + "integrity": "sha512-ts/8E8l5b7kY0vlWLewOkDXMmPdLcVV4GmOQLyxuSswIJsweeFZtAsMF7k1Nszz+TYBQrlYRmzOnr398y1JemQ==", + "license": "Apache-2.0", + "dependencies": { + "makeerror": "1.0.12" + } + }, + "node_modules/webidl-conversions": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-7.0.0.tgz", + "integrity": "sha512-VwddBukDzu71offAQR975unBIGqfKZpM+8ZX6ySk8nYhVoo5CYaZyzt3YBvYtRtO+aoGlqxPg/B87NGVZ/fu6g==", + "engines": { + "node": ">=12" + } + }, + "node_modules/whatwg-url": { + "version": "13.0.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-13.0.0.tgz", + "integrity": "sha512-9WWbymnqj57+XEuqADHrCJ2eSXzn8WXIW/YSGaZtb2WKAInQ6CHfaUUcTyyver0p8BDg5StLQq8h1vtZuwmOig==", + "dependencies": { + "tr46": "^4.1.1", + "webidl-conversions": "^7.0.0" + }, + "engines": { + "node": ">=16" + } + }, + "node_modules/which": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", + "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", + "dependencies": { + "isexe": "^2.0.0" + }, + "bin": { + "node-which": "bin/node-which" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/wrap-ansi": { + "version": "8.1.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-8.1.0.tgz", + "integrity": "sha512-si7QWI6zUMq56bESFvagtmzMdGOtoxfR+Sez11Mobfc7tm+VkUckk9bW2UeffTGVUbOksxmSw0AA2gs8g71NCQ==", + "dev": true, + "dependencies": { + "ansi-styles": "^6.1.0", + "string-width": "^5.0.1", + "strip-ansi": "^7.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, + "node_modules/wrap-ansi-cjs": { + "name": "wrap-ansi", + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", + "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", + "dev": true, + "dependencies": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, + "node_modules/wrap-ansi-cjs/node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/wrap-ansi-cjs/node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "dev": true, + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/wrap-ansi-cjs/node_modules/emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", + "dev": true + }, + "node_modules/wrap-ansi-cjs/node_modules/string-width": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "dev": true, + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/wrap-ansi-cjs/node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "dev": true, + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", + "license": "ISC" + }, + "node_modules/write-file-atomic": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-4.0.2.tgz", + "integrity": "sha512-7KxauUdBmSdWnmpaGFg+ppNjKF8uNLry8LyzjauQDOVONfFLNKrKvQOxZ/VuTIcS/gge/YNahf5RIIQWTSarlg==", + "license": "ISC", + "dependencies": { + "imurmurhash": "^0.1.4", + "signal-exit": "^3.0.7" + }, + "engines": { + "node": "^12.13.0 || ^14.15.0 || >=16.0.0" + } + }, + "node_modules/write-file-atomic/node_modules/signal-exit": { + "version": "3.0.7", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz", + "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==", + "license": "ISC" + }, + "node_modules/y18n": { + "version": "5.0.8", + "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz", + "integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==", + "license": "ISC", + "engines": { + "node": ">=10" + } + }, + "node_modules/yallist": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz", + "integrity": "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==", + "license": "ISC" + }, + "node_modules/yargs": { + "version": "17.7.2", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-17.7.2.tgz", + "integrity": "sha512-7dSzzRQ++CKnNI/krKnYRV7JKKPUXMEh61soaHKg9mrWEhzFWhFnxPxGl+69cD1Ou63C13NUPCnmIcrvqCuM6w==", + "license": "MIT", + "dependencies": { + "cliui": "^8.0.1", + "escalade": "^3.1.1", + "get-caller-file": "^2.0.5", + "require-directory": "^2.1.1", + "string-width": "^4.2.3", + "y18n": "^5.0.5", + "yargs-parser": "^21.1.1" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/yargs-parser": { + "version": "21.1.1", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-21.1.1.tgz", + "integrity": "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==", + "license": "ISC", + "engines": { + "node": ">=12" + } + }, + "node_modules/yargs/node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/yargs/node_modules/emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", + "license": "MIT" + }, + "node_modules/yargs/node_modules/string-width": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "license": "MIT", + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/yargs/node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "license": "MIT", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/yauzl": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/yauzl/-/yauzl-3.1.3.tgz", + "integrity": "sha512-JCCdmlJJWv7L0q/KylOekyRaUrdEoUxWkWVcgorosTROCFWiS9p2NNPE9Yb91ak7b1N5SxAZEliWpspbZccivw==", + "license": "MIT", + "dependencies": { + "buffer-crc32": "~0.2.3", + "pend": "~1.2.0" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/yn": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/yn/-/yn-3.1.1.tgz", + "integrity": "sha512-Ux4ygGWsu2c7isFWe8Yu1YluJmqVhxqK2cLXNQA5AcC3QfbGNpM7fu0Y8b/z16pXLnFxZYvWhd3fhBY9DLmC6Q==", + "engines": { + "node": ">=6" + } + }, + "node_modules/yocto-queue": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz", + "integrity": "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==", + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + } + } +} diff --git a/backend/question/package.json b/backend/question/package.json new file mode 100644 index 0000000000..dad9f35622 --- /dev/null +++ b/backend/question/package.json @@ -0,0 +1,43 @@ +{ + "name": "question", + "version": "1.0.0", + "description": "", + "main": "dist/server.js", + "scripts": { + "build": "rimraf dist && npx tsc", + "prestart": "npm run build", + "start": "npx tsc -w & nodemon dist/server.js", + "test": "cross-env NODE_ENV=TEST && jest src/tests/app.spec.ts" + }, + "author": "", + "license": "ISC", + "dependencies": { + "@types/cors": "^2.8.17", + "@types/express": "^4.17.21", + "@types/jest": "^29.5.13", + "@types/node": "^22.5.5", + "@types/supertest": "^6.0.2", + "cors": "^2.8.5", + "dotenv": "^16.4.5", + "express": "^4.21.0", + "express-validator": "^7.2.0", + "jest": "^29.7.0", + "mongodb-memory-server": "^10.0.1", + "mongoose": "^8.6.3", + "mongoose-sequence": "^6.0.1", + "supertest": "^7.0.0", + "ts-node": "^10.9.2", + "tsx": "^4.19.1", + "typescript": "^5.6.2" + }, + "devDependencies": { + "@types/express": "^4.17.21", + "@types/mongoose-sequence": "^3.0.11", + "@types/node": "^22.5.5", + "cross-env": "^7.0.3", + "nodemon": "^3.1.7", + "rimraf": "^6.0.1", + "ts-jest": "^29.2.5", + "typescript": "^5.6.2" + } +} diff --git a/backend/question/sample.env b/backend/question/sample.env new file mode 100644 index 0000000000..6a6881cb77 --- /dev/null +++ b/backend/question/sample.env @@ -0,0 +1,3 @@ +PORT= +MONGODB_URI= +NODE_ENV= \ No newline at end of file diff --git a/backend/question/src/models/Question.ts b/backend/question/src/models/Question.ts new file mode 100644 index 0000000000..74580e6ffa --- /dev/null +++ b/backend/question/src/models/Question.ts @@ -0,0 +1,104 @@ +import mongoose, { Document, Schema } from "mongoose"; +import mongooseAutoIncrement from "mongoose-sequence"; + +export type TQuestionExample = { + example_num: number; + expected_input: string; + expected_output: string; + explanation: string; +} + +/** + * Model for the Question Schema for TypeScript. + * Only includes the required fields as specified in the project document. + */ + +export type TQuestion = { + title: string; + description: string; + category: [string]; + complexity: string; + deleted: boolean; + examples: [TQuestionExample] + solution: string; + questionid?: number; +}; + +// Document provides an id field +export interface IQuestion extends TQuestion, Document {} + +const questionSchema: Schema = new Schema( + { + title: { + type: String, + required: true, + }, + description: { + type: String, + required: true, + }, + category: { + type: [String], + required: true, + }, + complexity: { + type: String, + required: true, + }, + examples: { + type: [ + { + example_num: Number, + expected_input: String, + expected_output: String, + explanation: String, + }, + ], + required: false, + }, + solution: { + type: String, + required: false, + }, + deleted: { + type: Boolean, + required: true, + }, + }, + { collection: "questions" } +); + +// Pre-middleware for findOneAndUpdate +questionSchema.pre("findOneAndUpdate", async function (next) { + const doc = await this.model.findOne(this.getQuery()); + if (!doc) { + return next(new Error("Document not found")); + } + next(); +}); + +//Pre-middleware for findOneAndDelete +questionSchema.pre("findOneAndDelete", async function (next) { + const doc = await this.model.findOne(this.getQuery()); + if (!doc) { + return next(new Error("Document not found")); + } + next(); +}); + +//questionid will be autoincrementing, starting from a large number to avoid conflicts with the existing data +// @ts-ignore +const AutoIncrement = mongooseAutoIncrement(mongoose); +// @ts-ignore +questionSchema.plugin(AutoIncrement, { + inc_field: "questionid", + start_seq: 1090, +}); +const QuestionBank = mongoose.connection.useDb("questionbank"); +const Question = QuestionBank.model( + "Question", + questionSchema, + "questions" +); + +export default Question; diff --git a/backend/question/src/routes/questionRoutes.ts b/backend/question/src/routes/questionRoutes.ts new file mode 100644 index 0000000000..41a35c6da5 --- /dev/null +++ b/backend/question/src/routes/questionRoutes.ts @@ -0,0 +1,342 @@ +import express, { Request, Response } from "express"; +import { validationResult } from "express-validator"; +import Question, { TQuestion } from "../models/Question"; +import { + countQuestionValidators, + createQuestionValidators, + idValidators, + pickQuestionValidators, + updateQuestionValidators, +} from "./validators"; + +/** + * Router for the question service. + */ + +const router = express.Router(); + +router.get("/", (req, res) => { + console.log("Sending Greetings!"); + res.send("Hello from question service!"); +}); + +// Create a new question +router.post( + "/create", + [...createQuestionValidators], + async (req: Request, res: Response) => { + const errors = validationResult(req); + if (!errors.isEmpty()) { + return res.status(400).json({ errors: errors.array() }); + } + try { + const { title, description, category, complexity, examples, solution } = req.body; + + const existingQuestion = await Question.findOne({ title: title.trim() }); + if (existingQuestion) { + return res.status(400).json({ + message: "A question with this title already exists", + }); + } + + const question = { + title, + description, + category, + complexity, + examples, + solution, + deleted: false, + }; + const newQuestion = new Question(question); + await newQuestion.save(); + return res.status(200).json({ + message: "Question created successfully", + question: newQuestion, + }); + } catch (error) { + return res.status(500).send("Internal server error"); + } + } +); + +// Retrieve all questions +router.post("/all", async (req: Request, res: Response) => { + let pagination = parseInt(req.body.pagination as string, 10) || 1; // Default page is 1 + const page_size = parseInt(req.body.page_size as string, 10) || 10; // Default limit is 10 + const skip = (pagination - 1) * page_size; // Calculate how many documents to skip + + const { title, complexity, category } = req.body; + + const query: any = { deleted: false }; + if (title && title !== "") query.title = { $regex: title, $options: "i" }; + if (complexity && complexity.length > 0) + query.complexity = { $in: complexity }; + if (category && category.length > 0) query.category = { $in: category }; + + try { + const questions = await Question.find(query, { + questionid: 1, + title: 1, + description: 1, + complexity: 1, + category: 1, + }) + .lean() + .sort({ questionid: "ascending" }) + .skip(skip) + .limit(page_size) + .exec(); + + const total = await Question.countDocuments(query).exec(); + const totalPages = Math.ceil(total / page_size); + if (totalPages < pagination) pagination = 1; + + return res.json({ + questions, + currentPage: pagination, + totalPages: totalPages, + totalQuestions: total, + }); + } catch (error) { + return res.status(500).send("Internal server error"); + } +}); + +// Retrieve all questions based on a list of question ids +router.post("/all-ids", async (req: Request, res: Response) => { + const questionIds = req.body.questionIds; + + try { + const questions = await Question.find( + { + questionid: { $in: questionIds }, + }, + { + questionid: 1, + title: 1, + description: 1, + complexity: 1, + examples: 1, + solution: 1, + category: 1, + }).lean().exec(); + return res.json(questions); + } catch (error) { + return res.status(500).send(error); + } +}); + +// Retrieve a specific question by id +router.get("/:id", [...idValidators], async (req: Request, res: Response) => { + const errors = validationResult(req); + if (!errors.isEmpty()) { + return res.status(400).json({ errors: errors.array() }); + } + const questionId = parseInt(req.params.id, 10); + try { + const question = await Question.findOne( + { questionid: questionId }, + { + questionid: 1, + title: 1, + description: 1, + complexity: 1, + category: 1, + deleted: 1, + examples: 1, + solution: 1, + } + ).exec(); + + if (!question) { + return res.status(404).json({ message: "Question not found" }); + } + + return res.json(question); + } catch (error) { + return res.status(500).send("Internal server error"); + } +}); + +// Retrieve the number of questions by complexity and category +router.post( + "/count-question", + [...countQuestionValidators], + async (req: Request, res: Response) => { + const errors = validationResult(req); + if (!errors.isEmpty()) { + return res.status(400).json({ errors: errors.array() }); + } + const { complexity, category } = req.body; + + try { + const countPromises = complexity.map((com: string, index: number) => { + const cat = category[index]; + const query: any = { + deleted: false, + complexity: com, + category: { $in: [cat] }, + }; + return Question.countDocuments(query).exec(); + }); + + const counts = await Promise.all(countPromises); + + return res.json({ counts }); + } catch (error) { + return res.status(500).send("Internal server error"); + } + } +); + +// Retrieve a random question by complexity and category +router.post( + "/pick-question", + [...pickQuestionValidators], + async (req: Request, res: Response) => { + const errors = validationResult(req); + if (!errors.isEmpty()) { + return res.status(400).json({ errors: errors.array() }); + } + const { complexity, category } = req.body; + + const query: any = { deleted: false }; + if (complexity) query.complexity = complexity; + if (category) query.category = { $in: [category] }; + + try { + let randomQuestion = await Question.aggregate([ + { $match: query }, // Filter by complexity and category + { $sample: { size: 1 } }, // Randomly select one document + { + $project: { + questionid: 1, + }, + }, + ]).exec(); + + if (!randomQuestion.length) { + query.deleted = true; // Adjust the query to allow deleted questions + randomQuestion = await Question.aggregate([ + { $match: query }, // Filter by complexity, category, and deleted + { $sample: { size: 1 } }, // Randomly select one document + { + $project: { + questionid: 1, + }, + }, + ]).exec(); + } + + if (!randomQuestion.length) { + return res.status(404).json({ message: "No questions found" }); + } + + return res.json(randomQuestion[0]); + } catch (error) { + return res.status(500).send("Internal server error"); + } + } +); + +// Update a specific question by id +router.post( + "/:id/update", + [...updateQuestionValidators], + async (req: Request, res: Response) => { + const errors = validationResult(req); + if (!errors.isEmpty()) { + return res.status(400).json({ errors: errors.array() }); + } + + const questionId = parseInt(req.params.id); + const updateData: Partial = {}; + console.log(req.body) + if (req.body.title) { + const existingQuestion = await Question.findOne({ + title: req.body.title.trim(), + }); + if (existingQuestion && existingQuestion.questionid && existingQuestion.questionid !== questionId) { + return res.status(400).json({ + message: "A question with this title already exists", + }); + } + + updateData.title = req.body.title; + } + if (req.body.description) { + updateData.description = req.body.description; + } + if (req.body.category) { + updateData.category = req.body.category; + } + if (req.body.complexity) { + updateData.complexity = req.body.complexity; + } + if (req.body.examples) { + updateData.examples = req.body.examples; + } + if (req.body.solution) { + updateData.solution = req.body.solution; + } + + try { + const question = await Question.findOne( + { questionid: questionId }, + { + questionid: 1, + title: 1, + description: 1, + complexity: 1, + category: 1, + examples: 1, + solution: 1, + deleted: 1, + } + ).exec(); + if (!question || question.deleted) { + return res.status(404).json({ message: "Question not found" }); + } + + const updatedQuestion = await Question.findOneAndUpdate( + { questionid: questionId }, + { $set: updateData }, + { new: true } + ); + return res.json(updatedQuestion); + } catch (error) { + return res.status(500).send("Internal server error"); + } + } +); + +// Delete a specific question by id +router.post( + "/:id/delete", + [...idValidators], + async (req: Request, res: Response) => { + const errors = validationResult(req); + if (!errors.isEmpty()) { + return res.status(400).json({ errors: errors.array() }); + } + + const questionId = parseInt(req.params.id); + try { + const deletedQuestion = await Question.findOneAndUpdate( + { questionid: questionId }, + { $set: { deleted: true } }, + { new: true } + ).exec(); + return res.json(deletedQuestion); + } catch (error) { + //to catch pre-middleware defined error + if (error instanceof Error) { + return res.status(404).json(error.message); + } + return res.status(500).send("Internal server error"); + } + } +); + +export default router; diff --git a/backend/question/src/routes/validators.ts b/backend/question/src/routes/validators.ts new file mode 100644 index 0000000000..4c9a6f49ed --- /dev/null +++ b/backend/question/src/routes/validators.ts @@ -0,0 +1,98 @@ +import { check, body } from "express-validator"; + +export const createQuestionValidators = [ + check("title").isString().isLength({ min: 1 }), + check("description").isString().isLength({ min: 1 }), + check("complexity").isString().isLength({ min: 1 }), + //custom validation for category + check("category").custom((category) => { + if (!Array.isArray(category) || category.length === 0) { + throw new Error("Category must be a non-empty array"); + } + //check if array contains only non-empty strings and trim whitespace + if ( + !category.every( + (element) => + typeof element === "string" && + element.length > 0 && + element.trim().length > 0 + ) + ) { + throw new Error("Category must contain only non-empty strings"); + } + return true; + }), +]; + +export const idValidators = [check("id").isInt({ min: 1 })]; + +export const countQuestionValidators = [ + check("complexity").custom((complexity) => { + if (!Array.isArray(complexity) || complexity.length === 0) { + throw new Error("Complexity must be a non-empty array"); + } + if ( + !complexity.every( + (element) => typeof element === "string" && element.trim().length > 0 + ) + ) { + throw new Error("Complexity must contain only non-empty strings"); + } + return true; + }), + check("category").custom((category) => { + if (!Array.isArray(category) || category.length === 0) { + throw new Error("Category must be a non-empty array"); + } + if ( + !category.every( + (element) => typeof element === "string" && element.trim().length > 0 + ) + ) { + throw new Error("Category must contain only non-empty strings"); + } + return true; + }), +]; + +export const pickQuestionValidators = [ + check("complexity").isString().isLength({ min: 1 }), + check("category").isString().isLength({ min: 1 }), +]; + +export const updateQuestionValidators = [ + check("id").isInt(), + body().custom((body) => { + const { title, description, category, complexity } = body; + if (!title && !description && !category && !complexity) { + throw new Error("At least one field must be provided"); + } + for (const field of [title, description, category, complexity]) { + if (field) { + //if field is cateogry + if (field === category) { + if (!Array.isArray(field) || field.length === 0) { + throw new Error("Category must be a non-empty array"); + } + //check if array contains only non-empty strings and trim whitespace + if ( + !field.every( + (element) => + typeof element === "string" && + element.length > 0 && + element.trim().length > 0 + ) + ) { + throw new Error("Category must contain only non-empty strings"); + } + } else { + //check that it is string + if (typeof field !== "string") { + throw new Error("Field must be a string"); + } + } + } + } + return true; + }), +]; diff --git a/backend/question/src/server.ts b/backend/question/src/server.ts new file mode 100644 index 0000000000..80a347e64c --- /dev/null +++ b/backend/question/src/server.ts @@ -0,0 +1,42 @@ +import cors from "cors"; +import dotenv from "dotenv"; +import express from "express"; +import mongoose from "mongoose"; +import questionRoutes from "./routes/questionRoutes"; +dotenv.config(); + +/** + * The URI for the MongoDB database is defined in the environment variable MONGODB_URI, inside your .env file. + * If you face the error "MongoParseError", check the naming of your env variable & check that the .env file exists (/question/.env). + */ +const uri = process.env.MONGODB_URI || ""; + +const app = express(); + +app.use(express.json()); +app.use(cors()); +app.use("/api/question", questionRoutes); + +const PORT = process.env.PORT || "3003"; + +async function connect() { + try { + await mongoose.connect(uri); + console.log("Connected to MongoDB"); + } catch (error) { + console.error(error); + } +} + +if (process.env.NODE_ENV === "DEV" || process.env.NODE_ENV === "PRODUCTION") { + connect(); +} + +const server = app.listen(PORT, (err?: Error) => { + if (err) { + return console.error(err); + } + return console.log(`App is running on port ${PORT}`); +}); + +export { app, server }; diff --git a/backend/question/src/tests/app.spec.ts b/backend/question/src/tests/app.spec.ts new file mode 100644 index 0000000000..a7fff22b95 --- /dev/null +++ b/backend/question/src/tests/app.spec.ts @@ -0,0 +1,712 @@ +import { app, server } from "../server"; +import * as db from "./db"; +import supertest from "supertest"; +const request = supertest(app); + +// Connect to DB and test /api/question/ +describe("Connect DB", () => { + beforeAll(async () => { + await db.connect(); + }); + + test("GET - /api/question/", async () => { + const res = await request.get("/api/question/").send(); + expect(res.statusCode).toBe(200); + expect(res.text).toBe("Hello from question service!"); + }); +}); + +// Test /api/question/create +describe("Test Question API", () => { + // Valid create + test("POST /api/question/create - should create a new question", async () => { + const newQuestion = { + title: "Sample Question", + description: "This is a sample question", + category: ["General"], + complexity: "Easy", + }; + + const res = await request.post("/api/question/create").send(newQuestion); + expect(res.statusCode).toBe(200); + expect(res.body.message).toBe("Question created successfully"); + expect(res.body.question).toHaveProperty("title", "Sample Question"); + expect(res.body.question).toHaveProperty( + "description", + "This is a sample question" + ); + expect(res.body.question).toHaveProperty("category", ["General"]); + expect(res.body.question).toHaveProperty("complexity", "Easy"); + }); + + // Empty title + test("POST /api/question/create - empty title", async () => { + const newQuestion = { + title: "", + description: "This is a sample question", + category: ["General"], + complexity: "Easy", + }; + + const res = await request.post("/api/question/create").send(newQuestion); + expect(res.statusCode).toBe(400); + expect(res.body.errors[0].msg).toBe("Invalid value"); + expect(res.body.errors[0].path).toBe("title"); + }); + + // Empty description + test("POST /api/question/create - empty description", async () => { + const newQuestion = { + title: "Sample Question", + description: "", + category: ["General"], + complexity: "Easy", + }; + + const res = await request.post("/api/question/create").send(newQuestion); + expect(res.statusCode).toBe(400); + expect(res.body.errors[0].msg).toBe("Invalid value"); + expect(res.body.errors[0].path).toBe("description"); + }); + + // Empty category + test("POST /api/question/create - empty category", async () => { + const newQuestion = { + title: "Sample Question", + description: "This is a sample question", + category: [], + complexity: "Easy", + }; + + const res = await request.post("/api/question/create").send(newQuestion); + expect(res.statusCode).toBe(400); + expect(res.body.errors[0].msg).toBe("Category must be a non-empty array"); + expect(res.body.errors[0].path).toBe("category"); + }); + + // Empty category with whitespace only + test("POST /api/question/create - empty category with whitespace string", async () => { + const newQuestion = { + title: "Sample Question", + description: "This is a sample question", + category: [" "], + complexity: "Easy", + }; + + const res = await request.post("/api/question/create").send(newQuestion); + expect(res.statusCode).toBe(400); + expect(res.body.errors[0].msg).toBe( + "Category must contain only non-empty strings" + ); + expect(res.body.errors[0].path).toBe("category"); + }); + + // Empty complexity + test("POST /api/question/create - empty complexity", async () => { + const newQuestion = { + title: "Sample Question", + description: "This is a sample question", + category: ["General"], + complexity: "", + }; + + const res = await request.post("/api/question/create").send(newQuestion); + expect(res.statusCode).toBe(400); + expect(res.body.errors[0].msg).toBe("Invalid value"); + expect(res.body.errors[0].path).toBe("complexity"); + }); + + // Invalid title + test("POST /api/question/create - invalid title", async () => { + const newQuestion = { + title: ["test"], + description: "This is a sample question", + category: "General", + complexity: "Easy", + }; + + const res = await request.post("/api/question/create").send(newQuestion); + expect(res.statusCode).toBe(400); + expect(res.body.errors[0].msg).toBe("Invalid value"); + expect(res.body.errors[0].path).toBe("title"); + }); + + // Invalid description + test("POST /api/question/create - invalid description", async () => { + const newQuestion = { + title: "Sample Question", + description: ["test"], + category: ["General"], + complexity: "Easy", + }; + + const res = await request.post("/api/question/create").send(newQuestion); + expect(res.statusCode).toBe(400); + expect(res.body.errors[0].msg).toBe("Invalid value"); + expect(res.body.errors[0].path).toBe("description"); + }); + + // Invalid category + test("POST /api/question/create - invalid category", async () => { + const newQuestion = { + title: "Sample Question", + description: "This is a sample question", + category: "test", + complexity: "Easy", + }; + + const res = await request.post("/api/question/create").send(newQuestion); + expect(res.statusCode).toBe(400); + expect(res.body.errors[0].msg).toBe("Category must be a non-empty array"); + expect(res.body.errors[0].path).toBe("category"); + }); + + // Invalid category + test("POST /api/question/create - invalid category", async () => { + const newQuestion = { + title: "Sample Question", + description: "This is a sample question", + category: [3, "test"], + complexity: "Easy", + }; + + const res = await request.post("/api/question/create").send(newQuestion); + expect(res.statusCode).toBe(400); + expect(res.body.errors[0].msg).toBe( + "Category must contain only non-empty strings" + ); + expect(res.body.errors[0].path).toBe("category"); + }); + + // Invalid category + test("POST /api/question/create - invalid category", async () => { + const newQuestion = { + title: "Sample Question", + description: "This is a sample question", + category: ["test", ""], + complexity: "Easy", + }; + + const res = await request.post("/api/question/create").send(newQuestion); + expect(res.statusCode).toBe(400); + expect(res.body.errors[0].msg).toBe( + "Category must contain only non-empty strings" + ); + expect(res.body.errors[0].path).toBe("category"); + }); + + // Invalid category + test("POST /api/question/create - invalid category with whitespace", async () => { + const newQuestion = { + title: "Sample Question", + description: "This is a sample question", + category: [" "], + complexity: "Easy", + }; + + const res = await request.post("/api/question/create").send(newQuestion); + expect(res.statusCode).toBe(400); + expect(res.body.errors[0].msg).toBe( + "Category must contain only non-empty strings" + ); + expect(res.body.errors[0].path).toBe("category"); + }); + + // Invalid complexity + test("POST /api/question/create - invalid complexity", async () => { + const newQuestion = { + title: "Sample Question", + description: "This is a sample question", + category: ["General"], + complexity: ["test"], + }; + + const res = await request.post("/api/question/create").send(newQuestion); + expect(res.statusCode).toBe(400); + expect(res.body.errors[0].msg).toBe("Invalid value"); + expect(res.body.errors[0].path).toBe("complexity"); + }); + + // Duplicate question + test("POST /api/question/create - duplicate question", async () => { + const newQuestion = { + title: "Sample Question", + description: "This is a sample question", + category: ["General"], + complexity: "test", + }; + + const res = await request.post("/api/question/create").send(newQuestion); + expect(res.statusCode).toBe(400); + expect(res.body.message).toBe("A question with this title already exists"); + }); +}); + +// Test /api/question/all +describe("Test Get All", () => { + // Get all with questions + test("POST /api/question/all - should retrieve all questions", async () => { + const res = await request.post("/api/question/all").send(); + const sampleQuestion = res.body.questions[0]; + expect(res.statusCode).toBe(200); + expect(Array.isArray(res.body.questions)).toBe(true); + expect(res.body.questions.length).toBe(1); + expect(res.body.currentPage).toBe(1); + expect(res.body.totalPages).toBe(1); + expect(res.body.totalQuestions).toBe(1); + expect(sampleQuestion).toHaveProperty("title", "Sample Question"); + expect(sampleQuestion).toHaveProperty( + "description", + "This is a sample question" + ); + expect(sampleQuestion).toHaveProperty("category", ["General"]); + expect(sampleQuestion).toHaveProperty("complexity", "Easy"); + }); + + test("POST /api/question/all - filter questions", async () => { + const searchQuestionTitle = { + title: "Sample Question", + }; + + const searchQuestionComplexity = { + complexity: ["Hard"], + }; + + const searchQuestionCategory = { + category: ["Dynamic Programming"], + }; + + const newQuestion = { + title: "Another Question", + description: "This is another sample question", + category: ["Dynamic Programming"], + complexity: "Hard", + }; + await request.post("/api/question/create").send(newQuestion); + const res = await request.post("/api/question/all").send(searchQuestionTitle); + const sampleQuestion = res.body.questions[0]; + expect(res.statusCode).toBe(200); + expect(Array.isArray(res.body.questions)).toBe(true); + expect(res.body.questions.length).toBe(1); + expect(res.body.currentPage).toBe(1); + expect(res.body.totalPages).toBe(1); + expect(res.body.totalQuestions).toBe(1); + expect(sampleQuestion).toHaveProperty("title", "Sample Question"); + expect(sampleQuestion).toHaveProperty( + "description", + "This is a sample question" + ); + expect(sampleQuestion).toHaveProperty("category", ["General"]); + expect(sampleQuestion).toHaveProperty("complexity", "Easy"); + + const res2 = await request.post("/api/question/all").send(searchQuestionComplexity); + const sampleQuestion2 = res2.body.questions[0]; + expect(res2.statusCode).toBe(200); + expect(Array.isArray(res2.body.questions)).toBe(true); + expect(res2.body.questions.length).toBe(1); + expect(res2.body.currentPage).toBe(1); + expect(res2.body.totalPages).toBe(1); + expect(res2.body.totalQuestions).toBe(1); + expect(sampleQuestion2).toHaveProperty("title", "Another Question"); + expect(sampleQuestion2).toHaveProperty( + "description", + "This is another sample question" + ); + expect(sampleQuestion2).toHaveProperty("category", ["Dynamic Programming"]); + expect(sampleQuestion2).toHaveProperty("complexity", "Hard"); + + const res3 = await request.post("/api/question/all").send(searchQuestionCategory); + const sampleQuestion3 = res3.body.questions[0]; + expect(res3.statusCode).toBe(200); + expect(Array.isArray(res3.body.questions)).toBe(true); + expect(res3.body.questions.length).toBe(1); + expect(res3.body.currentPage).toBe(1); + expect(res3.body.totalPages).toBe(1); + expect(res3.body.totalQuestions).toBe(1); + expect(sampleQuestion3).toHaveProperty("title", "Another Question"); + expect(sampleQuestion3).toHaveProperty( + "description", + "This is another sample question" + ); + expect(sampleQuestion3).toHaveProperty("category", ["Dynamic Programming"]); + expect(sampleQuestion3).toHaveProperty("complexity", "Hard"); + }); + + test("POST /api/question/all - No questions found", async () => { + const searchQuestionTitle = { + title: "Sample Question that doesn't exist", + }; + + const searchQuestionComplexity = { + complexity: ["Do not exist"], + }; + + const searchQuestionCategory = { + category: ["Do not exist"], + }; + + const res = await request.post("/api/question/all").send(searchQuestionTitle); + const res2 = await request.post("/api/question/all").send(searchQuestionComplexity); + const res3 = await request.post("/api/question/all").send(searchQuestionCategory); + expect(res.statusCode).toBe(200); + expect(res.body.questions.length).toBe(0); + expect(res.body.totalPages).toBe(0); + expect(res.body.totalQuestions).toBe(0); + + expect(res2.statusCode).toBe(200); + expect(res2.body.questions.length).toBe(0); + expect(res2.body.totalPages).toBe(0); + expect(res2.body.totalQuestions).toBe(0); + + expect(res3.statusCode).toBe(200); + expect(res3.body.questions.length).toBe(0); + expect(res3.body.totalPages).toBe(0); + expect(res3.body.totalQuestions).toBe(0); + }); +}); + +// Test /api/question/count-question +describe("Test count question", () => { + // Valid count question + test("POST - count question", async () => { + const countQuestionFilter = { + complexity: ["Hard"], + category: ["Dynamic Programming"], + }; + const res = await request + .post(`/api/question/count-question`) + .send(countQuestionFilter); + const sampleCount = res.body.counts[0]; + expect(res.statusCode).toBe(200); + expect(sampleCount).toBe(1); + }); + + // No question exists + test("POST - count question - none", async () => { + const countQuestionFilter = { + complexity: ["Medium"], + category: ["Dynamic Programming"], + }; + const res = await request + .post(`/api/question/count-question`) + .send(countQuestionFilter); + const sampleCount = res.body.counts[0]; + expect(res.statusCode).toBe(200); + expect(sampleCount).toBe(0); + }); + + // Batch read + test("POST - count question - batch read", async () => { + const countQuestionFilter = { + complexity: ["Hard", "Easy"], + category: ["Dynamic Programming", "General"], + }; + const res = await request + .post(`/api/question/count-question`) + .send(countQuestionFilter); + const sampleCount = res.body.counts; + expect(sampleCount.length).toBe(2); + expect(res.statusCode).toBe(200); + expect(sampleCount[0]).toBe(1); + expect(sampleCount[1]).toBe(1); + }); +}); + +// Test /api/question/pick-question +describe("Test pick question", () => { + // Valid pick question + test("POST - pick question", async () => { + const pickQuestionFilter = { + complexity: "Hard", + category: "Dynamic Programming", + }; + const res = await request + .post(`/api/question/pick-question`) + .send(pickQuestionFilter); + const sampleQuestion = res.body; + expect(res.statusCode).toBe(200); + expect(sampleQuestion).toHaveProperty("questionid", 1091); + }); + + test("POST - pick another question", async () => { + const pickQuestionFilter = { + complexity: "Easy", + category: "General", + }; + const res = await request + .post(`/api/question/pick-question`) + .send(pickQuestionFilter); + const sampleQuestion = res.body; + expect(res.statusCode).toBe(200); + expect(sampleQuestion).toHaveProperty("questionid", 1090); + }); + + // No question exists + test("POST - pick question that doesn't exist", async () => { + const pickQuestionFilter = { + complexity: "Medium", + category: "General", + }; + const res = await request + .post(`/api/question/pick-question`) + .send(pickQuestionFilter); + expect(res.statusCode).toBe(404); + expect(res.body.message).toBe("No questions found"); + }); + + // Empty complexity + test("POST - empty complexity", async () => { + const pickQuestionFilter = { + complexity: "", + category: "General", + }; + const res = await request + .post(`/api/question/pick-question`) + .send(pickQuestionFilter); + expect(res.statusCode).toBe(400); + expect(res.body.errors[0].msg).toBe("Invalid value"); + }); + + // Empty category + test("POST - empty category", async () => { + const pickQuestionFilter = { + complexity: "Easy", + category: "", + }; + const res = await request + .post(`/api/question/pick-question`) + .send(pickQuestionFilter); + expect(res.statusCode).toBe(400); + expect(res.body.errors[0].msg).toBe("Invalid value"); + }); + + // Valid pick question - deleted question + test("POST - pick question - deleted question if no non-deleted exists", async () => { + const pickQuestionFilter = { + complexity: "Hard", + category: "Dynamic Programming", + }; + const questionId = 1091; // We start with id 1091 + + await request.post(`/api/question/${questionId}/delete`); + const res = await request + .post(`/api/question/pick-question`) + .send(pickQuestionFilter); + const sampleQuestion = res.body; + expect(res.statusCode).toBe(200); + expect(sampleQuestion).toHaveProperty("questionid", 1091); + }); +}); + +// Test /api/question/{id} +describe("Test Get by Id", () => { + // Valid id + test("GET /api/question/:id - valid id", async () => { + const questionId = 1090; // We start with id 1090 + const res = await request.get(`/api/question/${questionId}`).send(); + expect(res.statusCode).toBe(200); + expect(res.body).toHaveProperty("questionid", questionId); + expect(res.body).toHaveProperty("title", "Sample Question"); + expect(res.body).toHaveProperty("description", "This is a sample question"); + expect(res.body).toHaveProperty("category", ["General"]); + expect(res.body).toHaveProperty("complexity", "Easy"); + }); + + // Negative id + test("GET /api/question/:id - negative id", async () => { + const questionId = -1; + const res = await request.get(`/api/question/${questionId}`).send(); + expect(res.statusCode).toBe(400); + expect(res.body.errors[0].msg).toBe("Invalid value"); + }); + + // Non-existent id + test("GET /api/question/:id - non existent id", async () => { + const questionId = 999999; + const res = await request.get(`/api/question/${questionId}`).send(); + expect(res.statusCode).toBe(404); + expect(res.body.message).toBe("Question not found"); + }); +}); + +// Test /api/question/{id}/update +describe("Test Update", () => { + // Valid update + test("POST - valid update", async () => { + const updateQuestion = { + title: "Update Title", + description: "Update Description", + category: ["Update Category"], + complexity: "Update Complexity", + }; + const questionId = 1090; + const res = await request + .post(`/api/question/${questionId}/update`) + .send(updateQuestion); + expect(res.statusCode).toBe(200); + expect(res.body).toHaveProperty("questionid", questionId); + expect(res.body).toHaveProperty("title", updateQuestion.title); + expect(res.body).toHaveProperty("description", updateQuestion.description); + expect(res.body).toHaveProperty("category", updateQuestion.category); + expect(res.body).toHaveProperty("complexity", updateQuestion.complexity); + }); + + // Empty update + test("POST - empty title update", async () => { + const updateQuestion = { + title: 3, + }; + const questionId = 1090; + const res = await request + .post(`/api/question/${questionId}/update`) + .send(updateQuestion); + expect(res.statusCode).toBe(400); + expect(res.body.errors[0].msg).toBe("Field must be a string"); + }); + + // Empty field update + test("POST - empty update", async () => { + const updateQuestion = { + title: "", + description: "", + category: "", + complexity: "", + }; + const questionId = 1090; + const res = await request + .post(`/api/question/${questionId}/update`) + .send(updateQuestion); + expect(res.statusCode).toBe(400); + expect(res.body.errors[0].msg).toBe("At least one field must be provided"); + }); + + // Update with invalid category + test("POST - empty category", async () => { + const updateQuestion = { + category: [], + }; + const questionId = 1090; + const res = await request + .post(`/api/question/${questionId}/update`) + .send(updateQuestion); + expect(res.statusCode).toBe(400); + expect(res.body.errors[0].msg).toBe("Category must be a non-empty array"); + }); + + // Update with invalid category + test("POST - category containing numbers", async () => { + const updateQuestion = { + category: [3], + complexity: ["test"], + }; + const questionId = 1090; + const res = await request + .post(`/api/question/${questionId}/update`) + .send(updateQuestion); + expect(res.statusCode).toBe(400); + expect(res.body.errors[0].msg).toBe( + "Category must contain only non-empty strings" + ); + }); + + // Update with invalid category + test("POST - category containing empty string", async () => { + const updateQuestion = { + description: "This is a sample question", + category: ["test", ""], + complexity: ["test"], + }; + const questionId = 1090; + const res = await request + .post(`/api/question/${questionId}/update`) + .send(updateQuestion); + expect(res.statusCode).toBe(400); + expect(res.body.errors[0].msg).toBe( + "Category must contain only non-empty strings" + ); + }); + + // Negative id + test("POST - negative id update", async () => { + const updateQuestion = { + title: "Update Title Again", + description: "Update Description", + category: ["Update Category"], + complexity: "Update Complexity", + }; + const questionId = -1; + const res = await request + .post(`/api/question/${questionId}/update`) + .send(updateQuestion); + expect(res.statusCode).toBe(404); + expect(res.body.message).toBe("Question not found"); + }); + + // Non-existent id + test("POST - non-existent id update", async () => { + const updateQuestion = { + title: "Update Title Again", + description: "Update Description", + category: ["Update Category"], + complexity: "Update Complexity", + }; + const questionId = 999999; + const res = await request + .post(`/api/question/${questionId}/update`) + .send(updateQuestion); + expect(res.statusCode).toBe(404); + expect(res.body.message).toBe("Question not found"); + }); + + // Duplicate question + test("POST - non-existent id update", async () => { + const updateQuestion = { + title: "Update Title", + description: "Update Description", + category: ["Update Category"], + complexity: "Update Complexity", + }; + const questionId = 1; + const res = await request + .post(`/api/question/${questionId}/update`) + .send(updateQuestion); + expect(res.statusCode).toBe(400); + expect(res.body.message).toBe("A question with this title already exists"); + }); +}); + +// Test /api/question/{id}/delete +describe("Test Delete", () => { + // Valid delete + test("POST - valid delete", async () => { + const questionId = 1090; + const res = await request.post(`/api/question/${questionId}/delete`).send(); + expect(res.statusCode).toBe(200); + const deleteRes = await request.get(`/api/question/${questionId}`).send(); + expect(deleteRes.statusCode).toBe(200); + const question = deleteRes.body; + expect(question.deleted).toBe(true); + }); + + // Negative id + test("POST - negative id delete", async () => { + const questionId = -1; + const res = await request.post(`/api/question/${questionId}/delete`).send(); + expect(res.statusCode).toBe(400); + expect(res.body.errors[0].msg).toBe("Invalid value"); + }); + + // Non-existent id + test("POST - non-existent id delete", async () => { + const questionId = 999999; + const res = await request.post(`/api/question/${questionId}/delete`).send(); + expect(res.statusCode).toBe(404); + expect(res.body).toBe("Document not found"); + }); +}); + +afterAll(async () => { + await db.clearDatabase(); + await db.closeDatabase(); + server.close(); +}); diff --git a/backend/question/src/tests/db.ts b/backend/question/src/tests/db.ts new file mode 100644 index 0000000000..13922872b2 --- /dev/null +++ b/backend/question/src/tests/db.ts @@ -0,0 +1,19 @@ +import mongoose from "mongoose"; +import { MongoMemoryServer } from "mongodb-memory-server"; +const mongod = MongoMemoryServer.create(); +export const connect = async () => { + const uri = await (await mongod).getUri(); + await mongoose.connect(uri); +}; +export const closeDatabase = async () => { + await mongoose.connection.dropDatabase(); + await mongoose.connection.close(); + await (await mongod).stop(); +}; +export const clearDatabase = async () => { + const collections = mongoose.connection.collections; + for (const key in collections) { + const collection = collections[key]; + await collection.deleteMany({}); + } +}; diff --git a/backend/question/tools/matchQuestionToAnswer.py b/backend/question/tools/matchQuestionToAnswer.py new file mode 100644 index 0000000000..03980e792e --- /dev/null +++ b/backend/question/tools/matchQuestionToAnswer.py @@ -0,0 +1,39 @@ +import os +import json +import re + +solutions_dir = "../../../../leetcode-js" + + +def main(): + with open("qn_full.json", "r") as f: + questions = json.load(f) + + for question in questions: + title_slug = question["slug"] + # Create a regex pattern to match files with a numerical prefix followed by the titleSlug + pattern = re.compile(rf"^\d+-{re.escape(title_slug)}\.\w+$") + + # Search for matching files in the solutions directory + matched_files = [f for f in os.listdir(solutions_dir) if pattern.match(f)] + + if matched_files: + # If multiple matches are found, you may need additional logic to select the correct one + solution_filename = matched_files[ + 0 + ] # Assuming the first match is the desired one + solution_path = os.path.join(solutions_dir, solution_filename) + with open(solution_path, "r") as sol_file: + solution_content = sol_file.read() + # Add the solution content to the question data + question["solution"] = solution_content + else: + question["solution"] = None # Or handle as needed + + # Save the updated questions with solutions + with open("questions_with_solutions.json", "w") as f: + json.dump(questions, f, indent=4) + + +if __name__ == "__main__": + main() diff --git a/backend/question/tools/package-lock.json b/backend/question/tools/package-lock.json new file mode 100644 index 0000000000..044a8de3fc --- /dev/null +++ b/backend/question/tools/package-lock.json @@ -0,0 +1,262 @@ +{ + "name": "tools", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "tools", + "version": "1.0.0", + "license": "ISC", + "dependencies": { + "dotenv": "^16.4.5", + "leetcode-query": "^1.2.3", + "mongodb": "^6.10.0" + } + }, + "node_modules/@fetch-impl/cross-fetch": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/@fetch-impl/cross-fetch/-/cross-fetch-1.0.0.tgz", + "integrity": "sha512-vNvwtCQ7yruvpYnp1i/4paVi/icrGYx9O4eHNDYorjTAFg78bhitO0l39opJSVfsTKqyWqj3+2+YenoGhZOCJA==", + "license": "MIT", + "peerDependencies": { + "@fetch-impl/fetcher": "^1.0.0", + "cross-fetch": "*" + } + }, + "node_modules/@fetch-impl/fetcher": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/@fetch-impl/fetcher/-/fetcher-1.0.0.tgz", + "integrity": "sha512-UPUN9Yfjnk513Vc08iNW8/9L1nSwQMsTx6nOvmjPNfU2Rtbew/2KgAbQDPuoL6PrNgEmEmmyeM29BkcVBpt3gQ==", + "license": "MIT" + }, + "node_modules/@mongodb-js/saslprep": { + "version": "1.1.9", + "resolved": "https://registry.npmjs.org/@mongodb-js/saslprep/-/saslprep-1.1.9.tgz", + "integrity": "sha512-tVkljjeEaAhCqTzajSdgbQ6gE6f3oneVwa3iXR6csiEwXXOFsiC6Uh9iAjAhXPtqa/XMDHWjjeNH/77m/Yq2dw==", + "license": "MIT", + "dependencies": { + "sparse-bitfield": "^3.0.3" + } + }, + "node_modules/@types/webidl-conversions": { + "version": "7.0.3", + "resolved": "https://registry.npmjs.org/@types/webidl-conversions/-/webidl-conversions-7.0.3.tgz", + "integrity": "sha512-CiJJvcRtIgzadHCYXw7dqEnMNRjhGZlYK05Mj9OyktqV8uVT8fD2BFOB7S1uwBE3Kj2Z+4UyPmFw/Ixgw/LAlA==", + "license": "MIT" + }, + "node_modules/@types/whatwg-url": { + "version": "11.0.5", + "resolved": "https://registry.npmjs.org/@types/whatwg-url/-/whatwg-url-11.0.5.tgz", + "integrity": "sha512-coYR071JRaHa+xoEvvYqvnIHaVqaYrLPbsufM9BF63HkwI5Lgmy2QR8Q5K/lYDYo5AK82wOvSOS0UsLTpTG7uQ==", + "license": "MIT", + "dependencies": { + "@types/webidl-conversions": "*" + } + }, + "node_modules/bson": { + "version": "6.9.0", + "resolved": "https://registry.npmjs.org/bson/-/bson-6.9.0.tgz", + "integrity": "sha512-X9hJeyeM0//Fus+0pc5dSUMhhrrmWwQUtdavaQeF3Ta6m69matZkGWV/MrBcnwUeLC8W9kwwc2hfkZgUuCX3Ig==", + "license": "Apache-2.0", + "engines": { + "node": ">=16.20.1" + } + }, + "node_modules/cross-fetch": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/cross-fetch/-/cross-fetch-4.0.0.tgz", + "integrity": "sha512-e4a5N8lVvuLgAWgnCrLr2PP0YyDOTHa9H/Rj54dirp61qXnNq46m82bRhNqIA5VccJtWBvPTFRV3TtvHUKPB1g==", + "license": "MIT", + "dependencies": { + "node-fetch": "^2.6.12" + } + }, + "node_modules/dotenv": { + "version": "16.4.5", + "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.4.5.tgz", + "integrity": "sha512-ZmdL2rui+eB2YwhsWzjInR8LldtZHGDoQ1ugH85ppHKwpUHL7j7rN0Ti9NCnGiQbhaZ11FpR+7ao1dNsmduNUg==", + "license": "BSD-2-Clause", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://dotenvx.com" + } + }, + "node_modules/eventemitter3": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-5.0.1.tgz", + "integrity": "sha512-GWkBvjiSZK87ELrYOSESUYeVIc9mvLLf/nXalMOS5dYrgZq9o5OVkbZAVM06CVxYsCwH9BDZFPlQTlPA1j4ahA==", + "license": "MIT" + }, + "node_modules/leetcode-query": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/leetcode-query/-/leetcode-query-1.2.3.tgz", + "integrity": "sha512-J73ehmjgIfDd3Ugg1ee83bDALNaGh78nQwDS5qyPOsgGahK55a2lcl9Q/iaByKi6AUMMxsHEyEsUNGBX4Lmn2Q==", + "license": "MIT", + "dependencies": { + "@fetch-impl/cross-fetch": "^1.0.0", + "@fetch-impl/fetcher": "^1.0.0", + "cross-fetch": "^4.0.0", + "eventemitter3": "^5.0.1" + } + }, + "node_modules/memory-pager": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/memory-pager/-/memory-pager-1.5.0.tgz", + "integrity": "sha512-ZS4Bp4r/Zoeq6+NLJpP+0Zzm0pR8whtGPf1XExKLJBAczGMnSi3It14OiNCStjQjM6NU1okjQGSxgEZN8eBYKg==", + "license": "MIT" + }, + "node_modules/mongodb": { + "version": "6.10.0", + "resolved": "https://registry.npmjs.org/mongodb/-/mongodb-6.10.0.tgz", + "integrity": "sha512-gP9vduuYWb9ZkDM546M+MP2qKVk5ZG2wPF63OvSRuUbqCR+11ZCAE1mOfllhlAG0wcoJY5yDL/rV3OmYEwXIzg==", + "license": "Apache-2.0", + "dependencies": { + "@mongodb-js/saslprep": "^1.1.5", + "bson": "^6.7.0", + "mongodb-connection-string-url": "^3.0.0" + }, + "engines": { + "node": ">=16.20.1" + }, + "peerDependencies": { + "@aws-sdk/credential-providers": "^3.188.0", + "@mongodb-js/zstd": "^1.1.0", + "gcp-metadata": "^5.2.0", + "kerberos": "^2.0.1", + "mongodb-client-encryption": ">=6.0.0 <7", + "snappy": "^7.2.2", + "socks": "^2.7.1" + }, + "peerDependenciesMeta": { + "@aws-sdk/credential-providers": { + "optional": true + }, + "@mongodb-js/zstd": { + "optional": true + }, + "gcp-metadata": { + "optional": true + }, + "kerberos": { + "optional": true + }, + "mongodb-client-encryption": { + "optional": true + }, + "snappy": { + "optional": true + }, + "socks": { + "optional": true + } + } + }, + "node_modules/mongodb-connection-string-url": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/mongodb-connection-string-url/-/mongodb-connection-string-url-3.0.1.tgz", + "integrity": "sha512-XqMGwRX0Lgn05TDB4PyG2h2kKO/FfWJyCzYQbIhXUxz7ETt0I/FqHjUeqj37irJ+Dl1ZtU82uYyj14u2XsZKfg==", + "license": "Apache-2.0", + "dependencies": { + "@types/whatwg-url": "^11.0.2", + "whatwg-url": "^13.0.0" + } + }, + "node_modules/node-fetch": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.7.0.tgz", + "integrity": "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==", + "license": "MIT", + "dependencies": { + "whatwg-url": "^5.0.0" + }, + "engines": { + "node": "4.x || >=6.0.0" + }, + "peerDependencies": { + "encoding": "^0.1.0" + }, + "peerDependenciesMeta": { + "encoding": { + "optional": true + } + } + }, + "node_modules/node-fetch/node_modules/tr46": { + "version": "0.0.3", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz", + "integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==", + "license": "MIT" + }, + "node_modules/node-fetch/node_modules/webidl-conversions": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz", + "integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==", + "license": "BSD-2-Clause" + }, + "node_modules/node-fetch/node_modules/whatwg-url": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz", + "integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==", + "license": "MIT", + "dependencies": { + "tr46": "~0.0.3", + "webidl-conversions": "^3.0.0" + } + }, + "node_modules/punycode": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", + "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/sparse-bitfield": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/sparse-bitfield/-/sparse-bitfield-3.0.3.tgz", + "integrity": "sha512-kvzhi7vqKTfkh0PZU+2D2PIllw2ymqJKujUcyPMd9Y75Nv4nPbGJZXNhxsgdQab2BmlDct1YnfQCguEvHr7VsQ==", + "license": "MIT", + "dependencies": { + "memory-pager": "^1.0.2" + } + }, + "node_modules/tr46": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-4.1.1.tgz", + "integrity": "sha512-2lv/66T7e5yNyhAAC4NaKe5nVavzuGJQVVtRYLyQ2OI8tsJ61PMLlelehb0wi2Hx6+hT/OJUWZcw8MjlSRnxvw==", + "license": "MIT", + "dependencies": { + "punycode": "^2.3.0" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/webidl-conversions": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-7.0.0.tgz", + "integrity": "sha512-VwddBukDzu71offAQR975unBIGqfKZpM+8ZX6ySk8nYhVoo5CYaZyzt3YBvYtRtO+aoGlqxPg/B87NGVZ/fu6g==", + "license": "BSD-2-Clause", + "engines": { + "node": ">=12" + } + }, + "node_modules/whatwg-url": { + "version": "13.0.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-13.0.0.tgz", + "integrity": "sha512-9WWbymnqj57+XEuqADHrCJ2eSXzn8WXIW/YSGaZtb2WKAInQ6CHfaUUcTyyver0p8BDg5StLQq8h1vtZuwmOig==", + "license": "MIT", + "dependencies": { + "tr46": "^4.1.1", + "webidl-conversions": "^7.0.0" + }, + "engines": { + "node": ">=16" + } + } + } +} diff --git a/backend/question/tools/package.json b/backend/question/tools/package.json new file mode 100644 index 0000000000..b70b4e15a2 --- /dev/null +++ b/backend/question/tools/package.json @@ -0,0 +1,17 @@ +{ + "name": "tools", + "version": "1.0.0", + "main": "index.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "keywords": [], + "author": "", + "license": "ISC", + "description": "", + "dependencies": { + "dotenv": "^16.4.5", + "leetcode-query": "^1.2.3", + "mongodb": "^6.10.0" + } +} diff --git a/backend/question/tools/populateQuestions.js b/backend/question/tools/populateQuestions.js new file mode 100644 index 0000000000..ee40e85591 --- /dev/null +++ b/backend/question/tools/populateQuestions.js @@ -0,0 +1,73 @@ +const { LeetCode } = require("leetcode-query"); +const { MongoClient } = require("mongodb"); +const dotenv = require("dotenv"); +const fs = require("fs"); +const path = require("path"); + +dotenv.config(); + +const leetcode = new LeetCode(); +const client = new MongoClient( + "mongodb+srv://cs3219:zpAKCgY8xDxgIz0z@questionbank.4xtdt.mongodb.net/", + { + useNewUrlParser: true, + useUnifiedTopology: true, + } +); + +async function fetchQuestionDetails(titleSlug) { + try { + const question = await leetcode.problem(titleSlug); + return question; + } catch (error) { + console.error(`Error fetching question ${titleSlug}:`, error); + return null; + } +} + +function parseExamples(content) { + const examplePattern = + /Example (\d+):<\/strong>.*?Input:<\/strong>\s*(.*?)\s*Output:<\/strong>\s*(.*?)\s*(?:Explanation:<\/strong>\s*(.*?))?<\/pre>/gs; + const matches = [...content.matchAll(examplePattern)]; + return matches.map((match, index) => ({ + example_num: index + 1, + expected_input: match[2].trim(), + expected_output: match[3].trim(), + explanation: match[4] ? match[4].trim() : "", + })); +} + +async function populateQuestionsWithExamples() { + try { + await client.connect(); + const db = client.db("questionbank"); + const collection = db.collection("questions"); + + const questions = await collection.find().toArray(); + const outputFilePath = path.join(__dirname, "qn_full.json"); + const outputStream = fs.createWriteStream(outputFilePath, { flags: "w" }); + + for (const [index, question] of questions.entries()) { + try { + console.log(`Processing question ${index + 1}: ${question.title}`); + const questionDetails = await fetchQuestionDetails(question.slug); + if (questionDetails) { + const examples = parseExamples(questionDetails.content); + question.examples = examples; + outputStream.write(JSON.stringify(question, null, 2) + ",\n"); + } + } catch (error) { + console.error(`Error processing question ${question.title}:`, error); + } + } + + outputStream.end(); + console.log("Processing completed."); + } catch (error) { + console.error("Error connecting to MongoDB:", error); + } finally { + await client.close(); + } +} + +populateQuestionsWithExamples(); diff --git a/backend/question/tools/qn_cleaner.py b/backend/question/tools/qn_cleaner.py new file mode 100644 index 0000000000..bdcfc2278c --- /dev/null +++ b/backend/question/tools/qn_cleaner.py @@ -0,0 +1,80 @@ +import html +import json +from typing import List +from pymongo import MongoClient +import re +from dotenv import load_dotenv +import os + +load_dotenv() + +client = MongoClient(os.getenv("MONGODB_URI")) +db = client["questionbank"] +collection = db["questions"] + +TARGET_FILE = "qn_full_with_soln.json" + + +def clean(): + with open(TARGET_FILE, "r") as f: + data = json.load(f) + for entry in data[1:]: + questionid = entry.get("questionid") + print("Processing questionid", questionid) + try: + if questionid is not None: + qn_doc = collection.find_one({"questionid": questionid}) + if qn_doc is None: + print(f"No document found with questionid {questionid}") + continue + examples = qn_doc.get("examples", []) + solution = entry.get("solution") + + cleaned_examples = [] + cleaned_solution = "" + if examples: + for example in examples: + new_example = {} + new_example["expected_input"] = html.unescape( + example.get("expected_input") + ) + new_example["expected_input"] = re.sub( + r"<[^>]+>", "", new_example["expected_input"] + ) + new_example["expected_output"] = html.unescape( + example.get("expected_output") + ) + new_example["expected_output"] = re.sub( + r"<[^>]+>", "", new_example["expected_output"] + ) + if example.get("explanation"): + new_example["explanation"] = html.unescape( + example.get("explanation") + ) + new_example["explanation"] = re.sub( + r"<[^>]+>", "", new_example["explanation"] + ) + + cleaned_examples.append(new_example) + if solution: + cleaned_solution = html.unescape(solution) + + result = collection.update_one( + {"questionid": questionid}, + { + "$set": { + "examples": cleaned_examples, + "solution": cleaned_solution, + } + }, + ) + if result.matched_count > 0: + print(f"Updated document with questionid {questionid}") + else: + print(f"No document found with questionid {questionid}") + except Exception as e: + print(f"Error: {e}") + + +if __name__ == "__main__": + clean() diff --git a/backend/question/tools/qn_full.json b/backend/question/tools/qn_full.json new file mode 100644 index 0000000000..facae9cdfb --- /dev/null +++ b/backend/question/tools/qn_full.json @@ -0,0 +1,39597 @@ +[ + { + "_id": "66f925ddfdfb8e1665720acc", + "questionid": 1, + "title": "Two Sum", + "slug": "two-sum", + "description": "Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not use the same element twice. You can return the answer in any order. ", + "category": [ + "Array", + "Hash Table" + ], + "complexity": "Easy", + "successrate": 48.5, + "totalsubmissions": 13207990, + "totalaccepted": 6403821, + "likes": 31242, + "dislikes": 988, + "hints": "A really brute force way would be to search for all possible pairs of numbers but that would be too slow. Again, it's best to try out brute force solutions for just for completeness. It is from these brute force solutions that you can come up with optimizations. So, if we fix one of the numbers, say x, we have to scan the entire array to find the next number y which is value - x where value is the input parameter. Can we change our array somehow so that this search becomes faster? The second train of thought is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [2,7,11,15], target = 9", + "expected_output": "[0,1]", + "explanation": "Because nums[0] + nums[1] == 9, we return [0, 1]." + }, + { + "example_num": 2, + "expected_input": "nums = [3,2,4], target = 6", + "expected_output": "[1,2]", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "nums = [3,3], target = 6", + "expected_output": "[0,1]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720acf", + "questionid": 4, + "title": "Median of Two Sorted Arrays", + "slug": "median-of-two-sorted-arrays", + "description": "Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)). ", + "category": [ + "Array", + "Binary Search", + "Divide and Conquer" + ], + "complexity": "Hard", + "successrate": 34, + "totalsubmissions": 3941694, + "totalaccepted": 1340565, + "likes": 15987, + "dislikes": 1964, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums1 = [1,3], nums2 = [2]", + "expected_output": "2.00000", + "explanation": "merged array = [1,2,3] and median is 2." + }, + { + "example_num": 2, + "expected_input": "nums1 = [1,2], nums2 = [3,4]", + "expected_output": "2.50000", + "explanation": "merged array = [1,2,3,4] and median is (2 + 3) / 2 = 2.5." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720ad2", + "questionid": 7, + "title": "Palindrome Number", + "slug": "palindrome-number", + "description": "Given an integer x, return true if x is palindrome integer. An integer is a palindrome when it reads the same backward as forward. ", + "category": [ + "Math" + ], + "complexity": "Easy", + "successrate": 52.3, + "totalsubmissions": 3823313, + "totalaccepted": 2000757, + "likes": 5593, + "dislikes": 2094, + "hints": "Beware of overflow when you reverse the integer.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "x = 121", + "expected_output": "true", + "explanation": "121 reads as 121 from left to right and from right to left." + }, + { + "example_num": 2, + "expected_input": "x = -121", + "expected_output": "false", + "explanation": "From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome." + }, + { + "example_num": 3, + "expected_input": "x = 10", + "expected_output": "false", + "explanation": "Reads 01 from right to left. Therefore it is not a palindrome." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720ad6", + "questionid": 11, + "title": "3Sum Closest", + "slug": "3sum-closest", + "description": "Given an integer array nums of length n and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution. ", + "category": [ + "Array", + "Two Pointers", + "Sorting" + ], + "complexity": "Medium", + "successrate": 47.1, + "totalsubmissions": 1665933, + "totalaccepted": 784188, + "likes": 5673, + "dislikes": 242, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [-1,2,1,-4], target = 1", + "expected_output": "2", + "explanation": "The sum that is closest to the target is 2. (-1 + 2 + 1 = 2)." + }, + { + "example_num": 2, + "expected_input": "nums = [0,0,0], target = 1", + "expected_output": "0", + "explanation": "The sum that is closest to the target is 0. (0 + 0 + 0 = 0)." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720ada", + "questionid": 15, + "title": "Generate Parentheses", + "slug": "generate-parentheses", + "description": "Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. ", + "category": [ + "String", + "Dynamic Programming", + "Backtracking" + ], + "complexity": "Medium", + "successrate": 69.9, + "totalsubmissions": 1475969, + "totalaccepted": 1032134, + "likes": 12456, + "dislikes": 483, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 3", + "expected_output": "[\"((()))\",\"(()())\",\"(())()\",\"()(())\",\"()()()\"]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "n = 1", + "expected_output": "[\"()\"]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720ae1", + "questionid": 22, + "title": "Search in Rotated Sorted Array", + "slug": "search-in-rotated-sorted-array", + "description": "There is an integer array nums sorted in ascending order (with distinct values). Prior to being passed to your function, nums is possibly rotated at an unknown pivot index k (1 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed). For example, [0,1,2,4,5,6,7] might be rotated at pivot index 3 and become [4,5,6,7,0,1,2]. Given the array nums after the possible rotation and an integer target, return the index of target if it is in nums, or -1 if it is not in nums. You must write an algorithm with O(log n) runtime complexity. ", + "category": [ + "Array", + "Binary Search" + ], + "complexity": "Medium", + "successrate": 37.7, + "totalsubmissions": 3795739, + "totalaccepted": 1431906, + "likes": 13769, + "dislikes": 879, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [4,5,6,7,0,1,2], target = 0", + "expected_output": "4", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "nums = [4,5,6,7,0,1,2], target = 3", + "expected_output": "-1", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "nums = [1], target = 0", + "expected_output": "-1", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720ae2", + "questionid": 23, + "title": "Find First and Last Position of Element in Sorted Array", + "slug": "find-first-and-last-position-of-element-in-sorted-array", + "description": "Given an array of integers nums sorted in non-decreasing order, find the starting and ending position of a given target value. If target is not found in the array, return [-1, -1]. You must write an algorithm with O(log n) runtime complexity. ", + "category": [ + "Array", + "Binary Search" + ], + "complexity": "Medium", + "successrate": 40, + "totalsubmissions": 2648073, + "totalaccepted": 1058127, + "likes": 10191, + "dislikes": 284, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [5,7,7,8,8,10], target = 8", + "expected_output": "[3,4]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "nums = [5,7,7,8,8,10], target = 6", + "expected_output": "[-1,-1]", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "nums = [], target = 0", + "expected_output": "[-1,-1]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720ae4", + "questionid": 25, + "title": "Combination Sum", + "slug": "combination-sum", + "description": "Given an array of distinct integers candidates and a target integer target, return a list of all unique combinations of candidates where the chosen numbers sum to target. You may return the combinations in any order. The same number may be chosen from candidates an unlimited number of times. Two combinations are unique if the frequency of at least one of the chosen numbers is different. It is guaranteed that the number of unique combinations that sum up to target is less than 150 combinations for the given input. ", + "category": [ + "Array", + "Backtracking" + ], + "complexity": "Medium", + "successrate": 65.3, + "totalsubmissions": 1614657, + "totalaccepted": 1054189, + "likes": 10510, + "dislikes": 224, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "candidates = [2,3,6,7], target = 7", + "expected_output": "[[2,2,3],[7]]", + "explanation": "2 and 3 are candidates, and 2 + 2 + 3 = 7. Note that 2 can be used multiple times.\n7 is a candidate, and 7 = 7.\nThese are the only two combinations." + }, + { + "example_num": 2, + "expected_input": "candidates = [2,3,5], target = 8", + "expected_output": "[[2,2,2,2],[2,3,3],[3,5]]", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "candidates = [2], target = 1", + "expected_output": "[]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720ae5", + "questionid": 26, + "title": "First Missing Positive", + "slug": "first-missing-positive", + "description": "Given an unsorted integer array nums, return the smallest missing positive integer. You must implement an algorithm that runs in O(n) time and uses constant extra space. ", + "category": [ + "Array", + "Hash Table" + ], + "complexity": "Hard", + "successrate": 35.9, + "totalsubmissions": 1845590, + "totalaccepted": 662571, + "likes": 9261, + "dislikes": 1303, + "hints": "Think about how you would solve the problem in non-constant space. Can you apply that logic to the existing space? We don't care about duplicates or non-positive integers Remember that O(2n) = O(n)", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,2,0]", + "expected_output": "3", + "explanation": "The numbers in the range [1,2] are all in the array." + }, + { + "example_num": 2, + "expected_input": "nums = [3,4,-1,1]", + "expected_output": "2", + "explanation": "1 is in the array but 2 is missing." + }, + { + "example_num": 3, + "expected_input": "nums = [7,8,9,11,12]", + "expected_output": "1", + "explanation": "The smallest positive integer 1 is missing." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720ae6", + "questionid": 27, + "title": "Trapping Rain Water", + "slug": "trapping-rain-water", + "description": "Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining. ", + "category": [ + "Array", + "Two Pointers", + "Dynamic Programming", + "Stack", + "Monotonic Stack" + ], + "complexity": "Hard", + "successrate": 56.3, + "totalsubmissions": 1933682, + "totalaccepted": 1089492, + "likes": 17879, + "dislikes": 252, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "height = [0,1,0,2,1,0,1,3,2,1,2,1]", + "expected_output": "6", + "explanation": "The above elevation map (black section) is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped." + }, + { + "example_num": 2, + "expected_input": "height = [4,2,0,3,2,5]", + "expected_output": "9", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720ae7", + "questionid": 28, + "title": "Jump Game II", + "slug": "jump-game-ii", + "description": "Given an array of non-negative integers nums, you are initially positioned at the first index of the array. Each element in the array represents your maximum jump length at that position. Your goal is to reach the last index in the minimum number of jumps. You can assume that you can always reach the last index. ", + "category": [ + "Array", + "Dynamic Programming", + "Greedy" + ], + "complexity": "Medium", + "successrate": 37, + "totalsubmissions": 1576789, + "totalaccepted": 583374, + "likes": 7769, + "dislikes": 291, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [2,3,1,1,4]", + "expected_output": "2", + "explanation": "The minimum number of jumps to reach the last index is 2. Jump 1 step from index 0 to 1, then 3 steps to the last index." + }, + { + "example_num": 2, + "expected_input": "nums = [2,3,0,1,4]", + "expected_output": "2", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720ae8", + "questionid": 29, + "title": "Permutations", + "slug": "permutations", + "description": "Given an array nums of distinct integers, return all the possible permutations. You can return the answer in any order. ", + "category": [ + "Array", + "Backtracking" + ], + "complexity": "Medium", + "successrate": 72.1, + "totalsubmissions": 1572570, + "totalaccepted": 1133403, + "likes": 9957, + "dislikes": 181, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,2,3]", + "expected_output": "[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "nums = [0,1]", + "expected_output": "[[0,1],[1,0]]", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "nums = [1]", + "expected_output": "[[1]]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720af0", + "questionid": 37, + "title": "Spiral Matrix", + "slug": "spiral-matrix", + "description": "Given an m x n matrix, return all elements of the matrix in spiral order. ", + "category": [ + "Array", + "Matrix", + "Simulation" + ], + "complexity": "Medium", + "successrate": 41.2, + "totalsubmissions": 1729035, + "totalaccepted": 713051, + "likes": 6929, + "dislikes": 818, + "hints": "Well for some problems, the best way really is to come up with some algorithms for simulation. Basically, you need to simulate what the problem asks us to do. We go boundary by boundary and move inwards. That is the essential operation. First row, last column, last row, first column and then we move inwards by 1 and then repeat. That's all, that is all the simulation that we need. Think about when you want to switch the progress on one of the indexes. If you progress on i out of [i, j], you'd be shifting in the same column. Similarly, by changing values for j, you'd be shifting in the same row.\r\nAlso, keep track of the end of a boundary so that you can move inwards and then keep repeating. It's always best to run the simulation on edge cases like a single column or a single row to see if anything breaks or not.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "matrix = [[1,2,3],[4,5,6],[7,8,9]]", + "expected_output": "[1,2,3,6,9,8,7,4,5]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]", + "expected_output": "[1,2,3,4,8,12,11,10,9,5,6,7]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720af2", + "questionid": 39, + "title": "Merge Intervals", + "slug": "merge-intervals", + "description": "Given an array of intervals where intervals[i] = [starti, endi], merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input. ", + "category": [ + "Array", + "Sorting" + ], + "complexity": "Medium", + "successrate": 44.8, + "totalsubmissions": 3102911, + "totalaccepted": 1390388, + "likes": 13083, + "dislikes": 513, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "intervals = [[1,3],[2,6],[8,10],[15,18]]", + "expected_output": "[[1,6],[8,10],[15,18]]", + "explanation": "Since intervals [1,3] and [2,6] overlap, merge them into [1,6]." + }, + { + "example_num": 2, + "expected_input": "intervals = [[1,4],[4,5]]", + "expected_output": "[[1,5]]", + "explanation": "Intervals [1,4] and [4,5] are considered overlapping." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720af3", + "questionid": 40, + "title": "Insert Interval", + "slug": "insert-interval", + "description": "You are given an array of non-overlapping intervals intervals where intervals[i] = [starti, endi] represent the start and the end of the ith interval and intervals is sorted in ascending order by starti. You are also given an interval newInterval = [start, end] that represents the start and end of another interval. Insert newInterval into intervals such that intervals is still sorted in ascending order by starti and intervals still does not have any overlapping intervals (merge overlapping intervals if necessary). Return intervals after the insertion. ", + "category": [ + "Array" + ], + "complexity": "Medium", + "successrate": 37.3, + "totalsubmissions": 1314450, + "totalaccepted": 490838, + "likes": 4631, + "dislikes": 334, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "intervals = [[1,3],[6,9]], newInterval = [2,5]", + "expected_output": "[[1,5],[6,9]]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8]", + "expected_output": "[[1,2],[3,10],[12,16]]", + "explanation": "Because the new interval [4,8] overlaps with [3,5],[6,7],[8,10]." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720af7", + "questionid": 44, + "title": "Unique Paths", + "slug": "unique-paths", + "description": "There is a robot on an m x n grid. The robot is initially located at the top-left corner (i.e., grid[0][0]). The robot tries to move to the bottom-right corner (i.e., grid[m - 1][n - 1]). The robot can only move either down or right at any point in time. Given the two integers m and n, return the number of possible unique paths that the robot can take to reach the bottom-right corner. The test cases are generated so that the answer will be less than or equal to 2 * 109. ", + "category": [ + "Math", + "Dynamic Programming", + "Combinatorics" + ], + "complexity": "Medium", + "successrate": 59.9, + "totalsubmissions": 1523012, + "totalaccepted": 912411, + "likes": 8532, + "dislikes": 294, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "m = 3, n = 7", + "expected_output": "28", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "m = 3, n = 2", + "expected_output": "3", + "explanation": "From the top-left corner, there are a total of 3 ways to reach the bottom-right corner:\n1. Right -> Down -> Down\n2. Down -> Down -> Right\n3. Down -> Right -> Down" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720af9", + "questionid": 46, + "title": "Plus One", + "slug": "plus-one", + "description": "You are given a large integer represented as an integer array digits, where each digits[i] is the ith digit of the integer. The digits are ordered from most significant to least significant in left-to-right order. The large integer does not contain any leading 0's. Increment the large integer by one and return the resulting array of digits. ", + "category": [ + "Array", + "Math" + ], + "complexity": "Easy", + "successrate": 42.8, + "totalsubmissions": 2719690, + "totalaccepted": 1162902, + "likes": 4014, + "dislikes": 4072, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "digits = [1,2,3]", + "expected_output": "[1,2,4]", + "explanation": "The array represents the integer 123.\nIncrementing by one gives 123 + 1 = 124.\nThus, the result should be [1,2,4]." + }, + { + "example_num": 2, + "expected_input": "digits = [4,3,2,1]", + "expected_output": "[4,3,2,2]", + "explanation": "The array represents the integer 4321.\nIncrementing by one gives 4321 + 1 = 4322.\nThus, the result should be [4,3,2,2]." + }, + { + "example_num": 3, + "expected_input": "digits = [9]", + "expected_output": "[1,0]", + "explanation": "The array represents the integer 9.\nIncrementing by one gives 9 + 1 = 10.\nThus, the result should be [1,0]." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720afb", + "questionid": 48, + "title": "Climbing Stairs", + "slug": "climbing-stairs", + "description": "You are climbing a staircase. It takes n steps to reach the top. Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? ", + "category": [ + "Math", + "Dynamic Programming", + "Memoization" + ], + "complexity": "Easy", + "successrate": 51, + "totalsubmissions": 2952667, + "totalaccepted": 1504735, + "likes": 11310, + "dislikes": 350, + "hints": "To reach nth step, what could have been your previous steps? (Think about the step sizes)", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 2", + "expected_output": "2", + "explanation": "There are two ways to climb to the top.\n1. 1 step + 1 step\n2. 2 steps" + }, + { + "example_num": 2, + "expected_input": "n = 3", + "expected_output": "3", + "explanation": "There are three ways to climb to the top.\n1. 1 step + 1 step + 1 step\n2. 1 step + 2 steps\n3. 2 steps + 1 step" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b00", + "questionid": 53, + "title": "Subsets", + "slug": "subsets", + "description": "Given an integer array nums of unique elements, return all possible subsets (the power set). The solution set must not contain duplicate subsets. Return the solution in any order. ", + "category": [ + "Array", + "Backtracking", + "Bit Manipulation" + ], + "complexity": "Medium", + "successrate": 71.2, + "totalsubmissions": 1493029, + "totalaccepted": 1063773, + "likes": 9680, + "dislikes": 153, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,2,3]", + "expected_output": "[[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "nums = [0]", + "expected_output": "[[],[0]]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b02", + "questionid": 55, + "title": "Search in Rotated Sorted Array II", + "slug": "search-in-rotated-sorted-array-ii", + "description": "There is an integer array nums sorted in non-decreasing order (not necessarily with distinct values). Before being passed to your function, nums is rotated at an unknown pivot index k (0 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed). For example, [0,1,2,4,4,4,5,6,6,7] might be rotated at pivot index 5 and become [4,5,6,6,7,0,1,2,4,4]. Given the array nums after the rotation and an integer target, return true if target is in nums, or false if it is not in nums. You must decrease the overall operation steps as much as possible. ", + "category": [ + "Array", + "Binary Search" + ], + "complexity": "Medium", + "successrate": 35.5, + "totalsubmissions": 1179147, + "totalaccepted": 419141, + "likes": 4331, + "dislikes": 718, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [2,5,6,0,0,1,2], target = 0", + "expected_output": "true", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "nums = [2,5,6,0,0,1,2], target = 3", + "expected_output": "false", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b05", + "questionid": 58, + "title": "Largest Rectangle in Histogram", + "slug": "largest-rectangle-in-histogram", + "description": "Given an array of integers heights representing the histogram's bar height where the width of each bar is 1, return the area of the largest rectangle in the histogram. ", + "category": [ + "Array", + "Stack", + "Monotonic Stack" + ], + "complexity": "Hard", + "successrate": 40.7, + "totalsubmissions": 1220391, + "totalaccepted": 496774, + "likes": 9616, + "dislikes": 142, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "heights = [2,1,5,6,2,3]", + "expected_output": "10", + "explanation": "The above is a histogram where width of each bar is 1.\nThe largest rectangle is shown in the red area, which has an area = 10 units." + }, + { + "example_num": 2, + "expected_input": "heights = [2,4]", + "expected_output": "4", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b0a", + "questionid": 63, + "title": "Reverse Linked List II", + "slug": "reverse-linked-list-ii", + "description": "Given the head of a singly linked list and two integers left and right where left <= right, reverse the nodes of the list from position left to position right, and return the reversed list. ", + "category": [ + "Linked List" + ], + "complexity": "Medium", + "successrate": 43.3, + "totalsubmissions": 1088239, + "totalaccepted": 471279, + "likes": 5945, + "dislikes": 278, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "head = [1,2,3,4,5], left = 2, right = 4", + "expected_output": "[1,4,3,2,5]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "head = [5], left = 1, right = 1", + "expected_output": "[5]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720ad0", + "questionid": 5, + "title": "Longest Palindromic Substring", + "slug": "longest-palindromic-substring", + "description": "Given a string s, return the longest palindromic substring in s. ", + "category": [ + "String", + "Dynamic Programming" + ], + "complexity": "Medium", + "successrate": 31.8, + "totalsubmissions": 5618701, + "totalaccepted": 1784028, + "likes": 17097, + "dislikes": 1005, + "hints": "How can we reuse a previously computed palindrome to compute a larger palindrome? If €œaba€ is a palindrome, is €œxabax€ a palindrome? Similarly is €œxabay€ a palindrome? Complexity based hint:\r\nIf we use brute-force and check whether for every start and end position a substring is a palindrome we have O(n^2) start - end pairs and O(n) palindromic checks. Can we reduce the time for palindromic checks to O(1) by reusing some previous computation.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "babad"", + "expected_output": ""bab"", + "explanation": ""aba" is also a valid answer." + }, + { + "example_num": 2, + "expected_input": "s = "cbbd"", + "expected_output": ""bb"", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720ad1", + "questionid": 6, + "title": "Reverse Integer", + "slug": "reverse-integer", + "description": "Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0. Assume the environment does not allow you to store 64-bit integers (signed or unsigned). ", + "category": [ + "Math" + ], + "complexity": "Medium", + "successrate": 26.7, + "totalsubmissions": 7589410, + "totalaccepted": 2022695, + "likes": 6971, + "dislikes": 9596, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "x = 123", + "expected_output": "321", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "x = -123", + "expected_output": "-321", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "x = 120", + "expected_output": "21", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720ad5", + "questionid": 10, + "title": "3Sum", + "slug": "3sum", + "description": "Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0. Notice that the solution set must not contain duplicate triplets. ", + "category": [ + "Array", + "Two Pointers", + "Sorting" + ], + "complexity": "Medium", + "successrate": 31, + "totalsubmissions": 6090299, + "totalaccepted": 1886780, + "likes": 17218, + "dislikes": 1653, + "hints": "So, we essentially need to find three numbers x, y, and z such that they add up to the given value. If we fix one of the numbers say x, we are left with the two-sum problem at hand! For the two-sum problem, if we fix one of the numbers, say x, we have to scan the entire array to find the next numbery which is value - x where value is the input parameter. Can we change our array somehow so that this search becomes faster? The second train of thought for two-sum is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [-1,0,1,2,-1,-4]", + "expected_output": "[[-1,-1,2],[-1,0,1]]", + "explanation": "nums[0] + nums[1] + nums[2] = (-1) + 0 + 1 = 0.\nnums[1] + nums[2] + nums[4] = 0 + 1 + (-1) = 0.\nnums[0] + nums[3] + nums[4] = (-1) + 2 + (-1) = 0.\nThe distinct triplets are [-1,0,1] and [-1,-1,2].\nNotice that the order of the output and the order of the triplets does not matter." + }, + { + "example_num": 2, + "expected_input": "nums = [0,1,1]", + "expected_output": "[]", + "explanation": "The only possible triplet does not sum up to 0." + }, + { + "example_num": 3, + "expected_input": "nums = [0,0,0]", + "expected_output": "[[0,0,0]]", + "explanation": "The only possible triplet sums up to 0." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720ad7", + "questionid": 12, + "title": "Letter Combinations of a Phone Number", + "slug": "letter-combinations-of-a-phone-number", + "description": "Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent. Return the answer in any order. A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters. ", + "category": [ + "Hash Table", + "String", + "Backtracking" + ], + "complexity": "Medium", + "successrate": 53.5, + "totalsubmissions": 2146094, + "totalaccepted": 1147569, + "likes": 9594, + "dislikes": 668, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "digits = "23"", + "expected_output": "["ad","ae","af","bd","be","bf","cd","ce","cf"]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "digits = """, + "expected_output": "[]", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "digits = "2"", + "expected_output": "["a","b","c"]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720add", + "questionid": 18, + "title": "Reverse Nodes in k-Group", + "slug": "reverse-nodes-in-k-group", + "description": "Given the head of a linked list, reverse the nodes of the list k at a time, and return the modified list. k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes, in the end, should remain as it is. You may not alter the values in the list's nodes, only nodes themselves may be changed. ", + "category": [ + "Linked List", + "Recursion" + ], + "complexity": "Hard", + "successrate": 50.9, + "totalsubmissions": 983085, + "totalaccepted": 500025, + "likes": 6837, + "dislikes": 485, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "head = [1,2,3,4,5], k = 2", + "expected_output": "[2,1,4,3,5]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "head = [1,2,3,4,5], k = 3", + "expected_output": "[3,2,1,4,5]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720ae3", + "questionid": 24, + "title": "Search Insert Position", + "slug": "search-insert-position", + "description": "Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. You must write an algorithm with O(log n) runtime complexity. ", + "category": [ + "Array", + "Binary Search" + ], + "complexity": "Easy", + "successrate": 42.3, + "totalsubmissions": 3247274, + "totalaccepted": 1374840, + "likes": 7432, + "dislikes": 401, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,3,5,6], target = 5", + "expected_output": "2", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "nums = [1,3,5,6], target = 2", + "expected_output": "1", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "nums = [1,3,5,6], target = 7", + "expected_output": "4", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720af4", + "questionid": 41, + "title": "Length of Last Word", + "slug": "length-of-last-word", + "description": "Given a string s consisting of some words separated by some number of spaces, return the length of the last word in the string. A word is a maximal substring consisting of non-space characters only. ", + "category": [ + "String" + ], + "complexity": "Easy", + "successrate": 37.4, + "totalsubmissions": 1916299, + "totalaccepted": 716989, + "likes": 875, + "dislikes": 70, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "Hello World"", + "expected_output": "5", + "explanation": "The last word is "World" with length 5." + }, + { + "example_num": 2, + "expected_input": "s = " fly me to the moon "", + "expected_output": "4", + "explanation": "The last word is "moon" with length 4." + }, + { + "example_num": 3, + "expected_input": "s = "luffy is still joyboy"", + "expected_output": "6", + "explanation": "The last word is "joyboy" with length 6." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720af6", + "questionid": 43, + "title": "Rotate List", + "slug": "rotate-list", + "description": "Given the head of a linked list, rotate the list to the right by k places. ", + "category": [ + "Linked List", + "Two Pointers" + ], + "complexity": "Medium", + "successrate": 34.8, + "totalsubmissions": 1566873, + "totalaccepted": 545760, + "likes": 4972, + "dislikes": 1265, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "head = [1,2,3,4,5], k = 2", + "expected_output": "[4,5,1,2,3]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "head = [0,1,2], k = 4", + "expected_output": "[2,0,1]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720afa", + "questionid": 47, + "title": "Add Binary", + "slug": "add-binary", + "description": "Given two binary strings a and b, return their sum as a binary string. ", + "category": [ + "Math", + "String", + "Bit Manipulation", + "Simulation" + ], + "complexity": "Easy", + "successrate": 50.4, + "totalsubmissions": 1625914, + "totalaccepted": 819020, + "likes": 4851, + "dislikes": 533, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "a = \"11\", b = \"1\"", + "expected_output": "\"100\"", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "a = \"1010\", b = \"1011\"", + "expected_output": "\"10101\"", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720aff", + "questionid": 52, + "title": "Combinations", + "slug": "combinations", + "description": "Given two integers n and k, return all possible combinations of k numbers out of the range [1, n]. You may return the answer in any order. ", + "category": [ + "Backtracking" + ], + "complexity": "Medium", + "successrate": 63.7, + "totalsubmissions": 799662, + "totalaccepted": 509584, + "likes": 4032, + "dislikes": 136, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 4, k = 2", + "expected_output": "[[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]", + "explanation": "There are 4 choose 2 = 6 total combinations.\nNote that combinations are unordered, i.e., [1,2] and [2,1] are considered to be the same combination." + }, + { + "example_num": 2, + "expected_input": "n = 1, k = 1", + "expected_output": "[[1]]", + "explanation": "There is 1 choose 1 = 1 total combination." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b01", + "questionid": 54, + "title": "Word Search", + "slug": "word-search", + "description": "Given an m x n grid of characters board and a string word, return true if word exists in the grid. The word can be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once. ", + "category": [ + "Array", + "Backtracking", + "Matrix" + ], + "complexity": "Medium", + "successrate": 39.6, + "totalsubmissions": 2376458, + "totalaccepted": 940859, + "likes": 8999, + "dislikes": 344, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED"", + "expected_output": "true", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "SEE"", + "expected_output": "true", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCB"", + "expected_output": "false", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b03", + "questionid": 56, + "title": "Remove Duplicates from Sorted List II", + "slug": "remove-duplicates-from-sorted-list-ii", + "description": "Given the head of a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. Return the linked list sorted as well. ", + "category": [ + "Linked List", + "Two Pointers" + ], + "complexity": "Medium", + "successrate": 44.2, + "totalsubmissions": 1085754, + "totalaccepted": 480084, + "likes": 5610, + "dislikes": 164, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "head = [1,2,3,3,4,4,5]", + "expected_output": "[1,2,5]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "head = [1,1,1,2,3]", + "expected_output": "[2,3]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b04", + "questionid": 57, + "title": "Remove Duplicates from Sorted List", + "slug": "remove-duplicates-from-sorted-list", + "description": "Given the head of a sorted linked list, delete all duplicates such that each element appears only once. Return the linked list sorted as well. ", + "category": [ + "Linked List" + ], + "complexity": "Easy", + "successrate": 49, + "totalsubmissions": 1714235, + "totalaccepted": 839133, + "likes": 4634, + "dislikes": 183, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "head = [1,1,2]", + "expected_output": "[1,2]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "head = [1,1,2,3,3]", + "expected_output": "[1,2,3]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b06", + "questionid": 59, + "title": "Maximal Rectangle", + "slug": "maximal-rectangle", + "description": "Given a rows x cols binary matrix filled with 0's and 1's, find the largest rectangle containing only 1's and return its area. ", + "category": [ + "Array", + "Dynamic Programming", + "Stack", + "Matrix", + "Monotonic Stack" + ], + "complexity": "Hard", + "successrate": 42.7, + "totalsubmissions": 682660, + "totalaccepted": 291357, + "likes": 6471, + "dislikes": 106, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]]", + "expected_output": "6", + "explanation": "The maximal rectangle is shown in the above picture." + }, + { + "example_num": 2, + "expected_input": "matrix = [["0"]]", + "expected_output": "0", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "matrix = [["1"]]", + "expected_output": "1", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720ad9", + "questionid": 14, + "title": "Merge Two Sorted Lists", + "slug": "merge-two-sorted-lists", + "description": "You are given the heads of two sorted linked lists list1 and list2. Merge the two lists in a one sorted list. The list should be made by splicing together the nodes of the first two lists. Return the head of the merged linked list. ", + "category": [ + "Linked List", + "Recursion" + ], + "complexity": "Easy", + "successrate": 60.2, + "totalsubmissions": 3519901, + "totalaccepted": 2118031, + "likes": 11753, + "dislikes": 1070, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "list1 = [1,2,4], list2 = [1,3,4]", + "expected_output": "[1,1,2,3,4,4]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "list1 = [], list2 = []", + "expected_output": "[]", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "list1 = [], list2 = [0]", + "expected_output": "[0]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720adf", + "questionid": 20, + "title": "Next Permutation", + "slug": "next-permutation", + "description": "A permutation of an array of integers is an arrangement of its members into a sequence or linear order. The next permutation of an array of integers is the next lexicographically greater permutation of its integer. More formally, if all the permutations of the array are sorted in one container according to their lexicographical order, then the next permutation of that array is the permutation that follows it in the sorted container. If such arrangement is not possible, the array must be rearranged as the lowest possible order (i.e., sorted in ascending order). Given an array of integers nums, find the next permutation of nums. The replacement must be in place and use only constant extra memory. ", + "category": [ + "Array", + "Two Pointers" + ], + "complexity": "Medium", + "successrate": 36.3, + "totalsubmissions": 2166111, + "totalaccepted": 787106, + "likes": 10346, + "dislikes": 3360, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,2,3]", + "expected_output": "[1,3,2]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "nums = [3,2,1]", + "expected_output": "[1,2,3]", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "nums = [1,1,5]", + "expected_output": "[1,5,1]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720ae0", + "questionid": 21, + "title": "Longest Valid Parentheses", + "slug": "longest-valid-parentheses", + "description": "Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring. ", + "category": [ + "String", + "Dynamic Programming", + "Stack" + ], + "complexity": "Hard", + "successrate": 31.2, + "totalsubmissions": 1518755, + "totalaccepted": 474545, + "likes": 7527, + "dislikes": 256, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "(()"", + "expected_output": "2", + "explanation": "The longest valid parentheses substring is "()"." + }, + { + "example_num": 2, + "expected_input": "s = ")()())"", + "expected_output": "4", + "explanation": "The longest valid parentheses substring is "()()"." + }, + { + "example_num": 3, + "expected_input": "s = """, + "expected_output": "0", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720aeb", + "questionid": 32, + "title": "Group Anagrams", + "slug": "group-anagrams", + "description": "Given an array of strings strs, group the anagrams together. You can return the answer in any order. An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. ", + "category": [ + "Hash Table", + "String", + "Sorting" + ], + "complexity": "Medium", + "successrate": 64, + "totalsubmissions": 2043076, + "totalaccepted": 1307071, + "likes": 8945, + "dislikes": 308, + "hints": "", + "deleted": false, + "examples": [] + }, + { + "_id": "66f925ddfdfb8e1665720aec", + "questionid": 33, + "title": "Pow(x, n)", + "slug": "powx-n", + "description": "Implement pow(x, n), which calculates x raised to the power n (i.e., xn). ", + "category": [ + "Math", + "Recursion" + ], + "complexity": "Medium", + "successrate": 32.3, + "totalsubmissions": 2733809, + "totalaccepted": 883674, + "likes": 4323, + "dislikes": 5309, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "x = 2.00000, n = 10", + "expected_output": "1024.00000", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "x = 2.10000, n = 3", + "expected_output": "9.26100", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "x = 2.00000, n = -2", + "expected_output": "0.25000", + "explanation": "2-2 = 1/22 = 1/4 = 0.25" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720aed", + "questionid": 34, + "title": "N-Queens", + "slug": "n-queens", + "description": "The n-queens puzzle is the problem of placing n queens on an n x n chessboard such that no two queens attack each other. Given an integer n, return all distinct solutions to the n-queens puzzle. You may return the answer in any order. Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space, respectively. ", + "category": [ + "Array", + "Backtracking" + ], + "complexity": "Hard", + "successrate": 57.2, + "totalsubmissions": 625138, + "totalaccepted": 357360, + "likes": 5603, + "dislikes": 152, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 4", + "expected_output": "[[".Q..","...Q","Q...","..Q."],["..Q.","Q...","...Q",".Q.."]]", + "explanation": "There exist two distinct solutions to the 4-queens puzzle as shown above" + }, + { + "example_num": 2, + "expected_input": "n = 1", + "expected_output": "[["Q"]]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720aee", + "questionid": 35, + "title": "N-Queens II", + "slug": "n-queens-ii", + "description": "The n-queens puzzle is the problem of placing n queens on an n x n chessboard such that no two queens attack each other. Given an integer n, return the number of distinct solutions to the n-queens puzzle. ", + "category": [ + "Backtracking" + ], + "complexity": "Hard", + "successrate": 66.1, + "totalsubmissions": 327225, + "totalaccepted": 216188, + "likes": 1670, + "dislikes": 209, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 4", + "expected_output": "2", + "explanation": "There are two distinct solutions to the 4-queens puzzle as shown." + }, + { + "example_num": 2, + "expected_input": "n = 1", + "expected_output": "1", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720af5", + "questionid": 42, + "title": "Spiral Matrix II", + "slug": "spiral-matrix-ii", + "description": "Given a positive integer n, generate an n x n matrix filled with elements from 1 to n2 in spiral order. ", + "category": [ + "Array", + "Matrix", + "Simulation" + ], + "complexity": "Medium", + "successrate": 64.7, + "totalsubmissions": 549056, + "totalaccepted": 355230, + "likes": 3579, + "dislikes": 180, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 3", + "expected_output": "[[1,2,3],[8,9,4],[7,6,5]]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "n = 1", + "expected_output": "[[1]]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720af8", + "questionid": 45, + "title": "Unique Paths II", + "slug": "unique-paths-ii", + "description": "You are given an m x n integer array grid. There is a robot initially located at the top-left corner (i.e., grid[0][0]). The robot tries to move to the bottom-right corner (i.e., grid[m-1][n-1]). The robot can only move either down or right at any point in time. An obstacle and space are marked as 1 or 0 respectively in grid. A path that the robot takes cannot include any square that is an obstacle. Return the number of possible unique paths that the robot can take to reach the bottom-right corner. The testcases are generated so that the answer will be less than or equal to 2 * 109. ", + "category": [ + "Array", + "Dynamic Programming", + "Matrix" + ], + "complexity": "Medium", + "successrate": 37.5, + "totalsubmissions": 1331781, + "totalaccepted": 499048, + "likes": 4533, + "dislikes": 371, + "hints": "The robot can only move either down or right. Hence any cell in the first row can only be reached from the cell left to it. However, if any cell has an obstacle, you don't let that cell contribute to any path. So, for the first row, the number of ways will simply be \r\n\r\n\r\nif obstacleGrid[i][j] is not an obstacle\r\n obstacleGrid[i,j] = obstacleGrid[i,j - 1] \r\nelse\r\n obstacleGrid[i,j] = 0\r\n\r\n\r\nYou can do a similar processing for finding out the number of ways of reaching the cells in the first column. For any other cell, we can find out the number of ways of reaching it, by making use of the number of ways of reaching the cell directly above it and the cell to the left of it in the grid. This is because these are the only two directions from which the robot can come to the current cell. Since we are making use of pre-computed values along the iteration, this becomes a dynamic programming problem.\r\n\r\n\r\nif obstacleGrid[i][j] is not an obstacle\r\n obstacleGrid[i,j] = obstacleGrid[i,j - 1] + obstacleGrid[i - 1][j]\r\nelse\r\n obstacleGrid[i,j] = 0", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "obstacleGrid = [[0,0,0],[0,1,0],[0,0,0]]", + "expected_output": "2", + "explanation": "There is one obstacle in the middle of the 3x3 grid above.\nThere are two ways to reach the bottom-right corner:\n1. Right -> Right -> Down -> Down\n2. Down -> Down -> Right -> Right" + }, + { + "example_num": 2, + "expected_input": "obstacleGrid = [[0,1],[0,0]]", + "expected_output": "1", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720afc", + "questionid": 49, + "title": "Set Matrix Zeroes", + "slug": "set-matrix-zeroes", + "description": "Given an m x n integer matrix matrix, if an element is 0, set its entire row and column to 0's. You must do it in place. ", + "category": [ + "Array", + "Hash Table", + "Matrix" + ], + "complexity": "Medium", + "successrate": 48.2, + "totalsubmissions": 1379982, + "totalaccepted": 664738, + "likes": 6658, + "dislikes": 481, + "hints": "If any cell of the matrix has a zero we can record its row and column number using additional memory.\r\nBut if you don't want to use extra memory then you can manipulate the array instead. i.e. simulating exactly what the question says. Setting cell values to zero on the fly while iterating might lead to discrepancies. What if you use some other integer value as your marker?\r\nThere is still a better approach for this problem with 0(1) space. We could have used 2 sets to keep a record of rows/columns which need to be set to zero. But for an O(1) space solution, you can use one of the rows and and one of the columns to keep track of this information. We can use the first cell of every row and column as a flag. This flag would determine whether a row or column has been set to zero.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "matrix = [[1,1,1],[1,0,1],[1,1,1]]", + "expected_output": "[[1,0,1],[0,0,0],[1,0,1]]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "matrix = [[0,1,2,0],[3,4,5,2],[1,3,1,5]]", + "expected_output": "[[0,0,0,0],[0,4,5,0],[0,3,1,0]]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720afe", + "questionid": 51, + "title": "Minimum Window Substring", + "slug": "minimum-window-substring", + "description": "Given two strings s and t of lengths m and n respectively, return the minimum window substring of s such that every character in t (including duplicates) is included in the window. If there is no such substring, return the empty string \"\". The testcases will be generated such that the answer is unique. A substring is a contiguous sequence of characters within the string. ", + "category": [ + "Hash Table", + "String", + "Sliding Window" + ], + "complexity": "Hard", + "successrate": 38.9, + "totalsubmissions": 1890669, + "totalaccepted": 735482, + "likes": 9964, + "dislikes": 529, + "hints": "Use two pointers to create a window of letters in S, which would have all the characters from T. Since you have to find the minimum window in S which has all the characters from T, you need to expand and contract the window using the two pointers and keep checking the window for all the characters. This approach is also called Sliding Window Approach.\r\n\r\n\n\r\nL ------------------------ R , Suppose this is the window that contains all characters of T \r\n \r\n        L----------------- R , this is the contracted window. We found a smaller window that still contains all the characters in T\r\n\r\nWhen the window is no longer valid, start expanding again using the right pointer.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "ADOBECODEBANC", t = "ABC"", + "expected_output": ""BANC"", + "explanation": "The minimum window substring "BANC" includes 'A', 'B', and 'C' from string t." + }, + { + "example_num": 2, + "expected_input": "s = "a", t = "a"", + "expected_output": ""a"", + "explanation": "The entire string s is the minimum window." + }, + { + "example_num": 3, + "expected_input": "s = "a", t = "aa"", + "expected_output": """", + "explanation": "Both 'a's from t must be included in the window.\nSince the largest window of s only has one 'a', return empty string." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b07", + "questionid": 60, + "title": "Partition List", + "slug": "partition-list", + "description": "Given the head of a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x. You should preserve the original relative order of the nodes in each of the two partitions. ", + "category": [ + "Linked List", + "Two Pointers" + ], + "complexity": "Medium", + "successrate": 47.8, + "totalsubmissions": 703320, + "totalaccepted": 335965, + "likes": 3376, + "dislikes": 474, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "head = [1,4,3,2,5,2], x = 3", + "expected_output": "[1,2,2,4,3,5]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "head = [2,1], x = 2", + "expected_output": "[1,2]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b09", + "questionid": 62, + "title": "Subsets II", + "slug": "subsets-ii", + "description": "Given an integer array nums that may contain duplicates, return all possible subsets (the power set). The solution set must not contain duplicate subsets. Return the solution in any order. ", + "category": [ + "Array", + "Backtracking", + "Bit Manipulation" + ], + "complexity": "Medium", + "successrate": 53.1, + "totalsubmissions": 924788, + "totalaccepted": 491045, + "likes": 4830, + "dislikes": 149, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,2,2]", + "expected_output": "[[],[1],[1,2],[1,2,2],[2],[2,2]]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "nums = [0]", + "expected_output": "[[],[0]]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b0b", + "questionid": 64, + "title": "Restore IP Addresses", + "slug": "restore-ip-addresses", + "description": "A valid IP address consists of exactly four integers separated by single dots. Each integer is between 0 and 255 (inclusive) and cannot have leading zeros. Given a string s containing only digits, return all possible valid IP addresses that can be formed by inserting dots into s. You are not allowed to reorder or remove any digits in s. You may return the valid IP addresses in any order. ", + "category": [ + "String", + "Backtracking" + ], + "complexity": "Medium", + "successrate": 41.7, + "totalsubmissions": 705550, + "totalaccepted": 294170, + "likes": 2649, + "dislikes": 624, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "25525511135"", + "expected_output": "["255.255.11.135","255.255.111.35"]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "s = "0000"", + "expected_output": "["0.0.0.0"]", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "s = "101023"", + "expected_output": "["1.0.10.23","1.0.102.3","10.1.0.23","10.10.2.3","101.0.2.3"]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720acd", + "questionid": 2, + "title": "Add Two Numbers", + "slug": "add-two-numbers", + "description": "You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list. You may assume the two numbers do not contain any leading zero, except the number 0 itself. ", + "category": [ + "Linked List", + "Math", + "Recursion" + ], + "complexity": "Medium", + "successrate": 38.5, + "totalsubmissions": 6987977, + "totalaccepted": 2690949, + "likes": 17799, + "dislikes": 3682, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "l1 = [2,4,3], l2 = [5,6,4]", + "expected_output": "[7,0,8]", + "explanation": "342 + 465 = 807." + }, + { + "example_num": 2, + "expected_input": "l1 = [0], l2 = [0]", + "expected_output": "[0]", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]", + "expected_output": "[8,9,9,9,0,0,0,1]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720ace", + "questionid": 3, + "title": "Longest Substring Without Repeating Characters", + "slug": "longest-substring-without-repeating-characters", + "description": "Given a string s, find the length of the longest substring without repeating characters. ", + "category": [ + "Hash Table", + "String", + "Sliding Window" + ], + "complexity": "Medium", + "successrate": 33, + "totalsubmissions": 9621884, + "totalaccepted": 3175843, + "likes": 22941, + "dislikes": 1027, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "abcabcbb"", + "expected_output": "3", + "explanation": "The answer is "abc", with the length of 3." + }, + { + "example_num": 2, + "expected_input": "s = "bbbbb"", + "expected_output": "1", + "explanation": "The answer is "b", with the length of 1." + }, + { + "example_num": 3, + "expected_input": "s = "pwwkew"", + "expected_output": "3", + "explanation": "The answer is "wke", with the length of 3.\nNotice that the answer must be a substring, "pwke" is a subsequence and not a substring." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720ad3", + "questionid": 8, + "title": "Container With Most Water", + "slug": "container-with-most-water", + "description": "You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the ith line are (i, 0) and (i, height[i]). Find two lines that together with the x-axis form a container, such that the container contains the most water. Return the maximum amount of water a container can store. Notice that you may not slant the container. ", + "category": [ + "Array", + "Two Pointers", + "Greedy" + ], + "complexity": "Medium", + "successrate": 53.9, + "totalsubmissions": 2673605, + "totalaccepted": 1441824, + "likes": 16437, + "dislikes": 930, + "hints": "The aim is to maximize the area formed between the vertical lines. The area of any container is calculated using the shorter line as length and the distance between the lines as the width of the rectangle.\r\n\r\n\r\nArea = length of shorter vertical line * distance between lines\r\n\r\n\r\nWe can definitely get the maximum width container as the outermost lines have the maximum distance between them. However, this container might not be the maximum in size as one of the vertical lines of this container could be really short. Start with the maximum width container and go to a shorter width container if there is a vertical line longer than the current containers shorter line. This way we are compromising on the width but we are looking forward to a longer length container.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "height = [1,8,6,2,5,4,8,3,7]", + "expected_output": "49", + "explanation": "The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49." + }, + { + "example_num": 2, + "expected_input": "height = [1,1]", + "expected_output": "1", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720ad4", + "questionid": 9, + "title": "Longest Common Prefix", + "slug": "longest-common-prefix", + "description": "Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string \"\". ", + "category": [ + "String" + ], + "complexity": "Easy", + "successrate": 39.3, + "totalsubmissions": 3891029, + "totalaccepted": 1529495, + "likes": 7636, + "dislikes": 2930, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "strs = ["flower","flow","flight"]", + "expected_output": ""fl"", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "strs = ["dog","racecar","car"]", + "expected_output": """", + "explanation": "There is no common prefix among the input strings." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720ad8", + "questionid": 13, + "title": "Remove Nth Node From End of List", + "slug": "remove-nth-node-from-end-of-list", + "description": "Given the head of a linked list, remove the nth node from the end of the list and return its head. ", + "category": [ + "Linked List", + "Two Pointers" + ], + "complexity": "Medium", + "successrate": 38.2, + "totalsubmissions": 3510223, + "totalaccepted": 1340984, + "likes": 9607, + "dislikes": 457, + "hints": "Maintain two pointers and update one with a delay of n steps.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "head = [1,2,3,4,5], n = 2", + "expected_output": "[1,2,3,5]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "head = [1], n = 1", + "expected_output": "[]", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "head = [1,2], n = 1", + "expected_output": "[1]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720adb", + "questionid": 16, + "title": "Merge k Sorted Lists", + "slug": "merge-k-sorted-lists", + "description": "You are given an array of k linked-lists lists, each linked-list is sorted in ascending order. Merge all the linked-lists into one sorted linked-list and return it. ", + "category": [ + "Linked List", + "Divide and Conquer", + "Heap (Priority Queue)", + "Merge Sort" + ], + "complexity": "Hard", + "successrate": 46.9, + "totalsubmissions": 2627265, + "totalaccepted": 1233044, + "likes": 11827, + "dislikes": 462, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "lists = [[1,4,5],[1,3,4],[2,6]]", + "expected_output": "[1,1,2,3,4,4,5,6]", + "explanation": "The linked-lists are:\n[\n 1->4->5,\n 1->3->4,\n 2->6\n]\nmerging them into one sorted list:\n1->1->2->3->4->4->5->6" + }, + { + "example_num": 2, + "expected_input": "lists = []", + "expected_output": "[]", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "lists = [[]]", + "expected_output": "[]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720adc", + "questionid": 17, + "title": "Swap Nodes in Pairs", + "slug": "swap-nodes-in-pairs", + "description": "Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.) ", + "category": [ + "Linked List", + "Recursion" + ], + "complexity": "Medium", + "successrate": 58.6, + "totalsubmissions": 1452282, + "totalaccepted": 851081, + "likes": 6765, + "dislikes": 289, + "hints": "", + "deleted": false, + "examples": [] + }, + { + "_id": "66f925ddfdfb8e1665720ade", + "questionid": 19, + "title": "Substring with Concatenation of All Words", + "slug": "substring-with-concatenation-of-all-words", + "description": "You are given a string s and an array of strings words of the same length. Return all starting indices of substring(s) in s that is a concatenation of each word in words exactly once, in any order, and without any intervening characters. You can return the answer in any order. ", + "category": [ + "Hash Table", + "String", + "Sliding Window" + ], + "complexity": "Hard", + "successrate": 28, + "totalsubmissions": 894344, + "totalaccepted": 250616, + "likes": 1893, + "dislikes": 1828, + "hints": "", + "deleted": false, + "examples": [] + }, + { + "_id": "66f925ddfdfb8e1665720ae9", + "questionid": 30, + "title": "Permutations II", + "slug": "permutations-ii", + "description": "Given a collection of numbers, nums, that might contain duplicates, return all possible unique permutations in any order. ", + "category": [ + "Array", + "Backtracking" + ], + "complexity": "Medium", + "successrate": 54, + "totalsubmissions": 1105821, + "totalaccepted": 596907, + "likes": 4794, + "dislikes": 90, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,1,2]", + "expected_output": "[[1,1,2],\n [1,2,1],\n [2,1,1]]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "nums = [1,2,3]", + "expected_output": "[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720aea", + "questionid": 31, + "title": "Rotate Image", + "slug": "rotate-image", + "description": "You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise). You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation. ", + "category": [ + "Array", + "Math", + "Matrix" + ], + "complexity": "Medium", + "successrate": 66.4, + "totalsubmissions": 1295324, + "totalaccepted": 860014, + "likes": 8777, + "dislikes": 473, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "matrix = [[1,2,3],[4,5,6],[7,8,9]]", + "expected_output": "[[7,4,1],[8,5,2],[9,6,3]]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "matrix = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]]", + "expected_output": "[[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720aef", + "questionid": 36, + "title": "Maximum Subarray", + "slug": "maximum-subarray", + "description": "Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. A subarray is a contiguous part of an array. ", + "category": [ + "Array", + "Divide and Conquer", + "Dynamic Programming" + ], + "complexity": "Easy", + "successrate": 49.5, + "totalsubmissions": 4544146, + "totalaccepted": 2249144, + "likes": 19877, + "dislikes": 969, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [-2,1,-3,4,-1,2,1,-5,4]", + "expected_output": "6", + "explanation": "The subarray [4,-1,2,1] has the largest sum 6." + }, + { + "example_num": 2, + "expected_input": "nums = [1]", + "expected_output": "1", + "explanation": "The subarray [1] has the largest sum 1." + }, + { + "example_num": 3, + "expected_input": "nums = [5,4,-1,7,8]", + "expected_output": "23", + "explanation": "The subarray [5,4,-1,7,8] has the largest sum 23." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720af1", + "questionid": 38, + "title": "Jump Game", + "slug": "jump-game", + "description": "You are given an integer array nums. You are initially positioned at the array's first index, and each element in the array represents your maximum jump length at that position. Return true if you can reach the last index, or false otherwise. ", + "category": [ + "Array", + "Dynamic Programming", + "Greedy" + ], + "complexity": "Medium", + "successrate": 37.7, + "totalsubmissions": 2575216, + "totalaccepted": 971160, + "likes": 10627, + "dislikes": 612, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [2,3,1,1,4]", + "expected_output": "true", + "explanation": "Jump 1 step from index 0 to 1, then 3 steps to the last index." + }, + { + "example_num": 2, + "expected_input": "nums = [3,2,1,0,4]", + "expected_output": "false", + "explanation": "You will always arrive at index 3 no matter what. Its maximum jump length is 0, which makes it impossible to reach the last index." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720afd", + "questionid": 50, + "title": "Sort Colors", + "slug": "sort-colors", + "description": "Given an array nums with n objects colored red, white, or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue. We will use the integers 0, 1, and 2 to represent the color red, white, and blue, respectively. You must solve this problem without using the library's sort function. ", + "category": [ + "Array", + "Two Pointers", + "Sorting" + ], + "complexity": "Medium", + "successrate": 54.6, + "totalsubmissions": 1791336, + "totalaccepted": 978245, + "likes": 9434, + "dislikes": 408, + "hints": "A rather straight forward solution is a two-pass algorithm using counting sort. Iterate the array counting number of 0's, 1's, and 2's. Overwrite array with the total number of 0's, then 1's and followed by 2's.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [2,0,2,1,1,0]", + "expected_output": "[0,0,1,1,2,2]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "nums = [2,0,1]", + "expected_output": "[0,1,2]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b08", + "questionid": 61, + "title": "Merge Sorted Array", + "slug": "merge-sorted-array", + "description": "You are given two integer arrays nums1 and nums2, sorted in non-decreasing order, and two integers m and n, representing the number of elements in nums1 and nums2 respectively. Merge nums1 and nums2 into a single array sorted in non-decreasing order. The final sorted array should not be returned by the function, but instead be stored inside the array nums1. To accommodate this, nums1 has a length of m + n, where the first m elements denote the elements that should be merged, and the last n elements are set to 0 and should be ignored. nums2 has a length of n. ", + "category": [ + "Array", + "Two Pointers", + "Sorting" + ], + "complexity": "Easy", + "successrate": 43.7, + "totalsubmissions": 3069815, + "totalaccepted": 1342555, + "likes": 4189, + "dislikes": 401, + "hints": "You can easily solve this problem if you simply think about two elements at a time rather than two arrays. We know that each of the individual arrays is sorted. What we don't know is how they will intertwine. Can we take a local decision and arrive at an optimal solution? If you simply consider one element each at a time from the two arrays and make a decision and proceed accordingly, you will arrive at the optimal solution.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3", + "expected_output": "[1,2,2,3,5,6]", + "explanation": "The arrays we are merging are [1,2,3] and [2,5,6].\nThe result of the merge is [1,2,2,3,5,6] with the underlined elements coming from nums1." + }, + { + "example_num": 2, + "expected_input": "nums1 = [1], m = 1, nums2 = [], n = 0", + "expected_output": "[1]", + "explanation": "The arrays we are merging are [1] and [].\nThe result of the merge is [1]." + }, + { + "example_num": 3, + "expected_input": "nums1 = [0], m = 0, nums2 = [1], n = 1", + "expected_output": "[1]", + "explanation": "The arrays we are merging are [] and [1].\nThe result of the merge is [1].\nNote that because m = 0, there are no elements in nums1. The 0 is only there to ensure the merge result can fit in nums1." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b11", + "questionid": 70, + "title": "Symmetric Tree", + "slug": "symmetric-tree", + "description": "Given the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center). ", + "category": [ + "Tree", + "Depth-First Search", + "Breadth-First Search", + "Binary Tree" + ], + "complexity": "Easy", + "successrate": 51.5, + "totalsubmissions": 2345643, + "totalaccepted": 1207686, + "likes": 9140, + "dislikes": 225, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [1,2,2,3,4,4,3]", + "expected_output": "true", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "root = [1,2,2,null,3,null,3]", + "expected_output": "false", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b12", + "questionid": 71, + "title": "Binary Tree Level Order Traversal", + "slug": "binary-tree-level-order-traversal", + "description": "Given the root of a binary tree, return the level order traversal of its nodes' values. (i.e., from left to right, level by level). ", + "category": [ + "Tree", + "Breadth-First Search", + "Binary Tree" + ], + "complexity": "Medium", + "successrate": 60.8, + "totalsubmissions": 1979250, + "totalaccepted": 1203028, + "likes": 7903, + "dislikes": 156, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [3,9,20,null,null,15,7]", + "expected_output": "[[3],[9,20],[15,7]]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "root = [1]", + "expected_output": "[[1]]", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "root = []", + "expected_output": "[]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b17", + "questionid": 76, + "title": "Binary Tree Level Order Traversal II", + "slug": "binary-tree-level-order-traversal-ii", + "description": "Given the root of a binary tree, return the bottom-up level order traversal of its nodes' values. (i.e., from left to right, level by level from leaf to root). ", + "category": [ + "Tree", + "Breadth-First Search", + "Binary Tree" + ], + "complexity": "Medium", + "successrate": 58.6, + "totalsubmissions": 841912, + "totalaccepted": 493042, + "likes": 3118, + "dislikes": 276, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [3,9,20,null,null,15,7]", + "expected_output": "[[15,7],[9,20],[3]]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "root = [1]", + "expected_output": "[[1]]", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "root = []", + "expected_output": "[]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b1a", + "questionid": 79, + "title": "Path Sum", + "slug": "path-sum", + "description": "Given the root of a binary tree and an integer targetSum, return true if the tree has a root-to-leaf path such that adding up all the values along the path equals targetSum. A leaf is a node with no children. ", + "category": [ + "Tree", + "Depth-First Search", + "Breadth-First Search", + "Binary Tree" + ], + "complexity": "Easy", + "successrate": 45.4, + "totalsubmissions": 1884955, + "totalaccepted": 856231, + "likes": 5299, + "dislikes": 779, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22", + "expected_output": "true", + "explanation": "The root-to-leaf path with the target sum is shown." + }, + { + "example_num": 2, + "expected_input": "root = [1,2,3], targetSum = 5", + "expected_output": "false", + "explanation": "There are two root-to-leaf paths in the tree:\n(1 --> 2): The sum is 3.\n(1 --> 3): The sum is 4.\nThere is no root-to-leaf path with sum = 5." + }, + { + "example_num": 3, + "expected_input": "root = [], targetSum = 0", + "expected_output": "false", + "explanation": "Since the tree is empty, there are no root-to-leaf paths." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b1d", + "questionid": 82, + "title": "Populating Next Right Pointers in Each Node II", + "slug": "populating-next-right-pointers-in-each-node-ii", + "description": "Given a binary tree Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL. Initially, all next pointers are set to NULL. ", + "category": [ + "Linked List", + "Tree", + "Depth-First Search", + "Breadth-First Search", + "Binary Tree" + ], + "complexity": "Medium", + "successrate": 46.5, + "totalsubmissions": 923889, + "totalaccepted": 429180, + "likes": 3606, + "dislikes": 237, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [1,2,3,4,5,null,7]", + "expected_output": "[1,#,2,3,#,4,5,7,#]\nExplanation: Given the above binary tree (Figure A), your function should populate each next pointer to point to its next right node, just like in Figure B. The serialized output is in level order as connected by the next pointers, with '#' signifying the end of each level.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "root = []", + "expected_output": "[]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b1e", + "questionid": 83, + "title": "Triangle", + "slug": "triangle", + "description": "Given a triangle array, return the minimum path sum from top to bottom. For each step, you may move to an adjacent number of the row below. More formally, if you are on index i on the current row, you may move to either index i or index i + 1 on the next row. ", + "category": [ + "Array", + "Dynamic Programming" + ], + "complexity": "Medium", + "successrate": 50.6, + "totalsubmissions": 807721, + "totalaccepted": 409106, + "likes": 4786, + "dislikes": 380, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "triangle = [[2],[3,4],[6,5,7],[4,1,8,3]]", + "expected_output": "11", + "explanation": "The triangle looks like:\n 2\n 3 4\n 6 5 7\n4 1 8 3\nThe minimum path sum from top to bottom is 2 + 3 + 5 + 1 = 11 (underlined above)." + }, + { + "example_num": 2, + "expected_input": "triangle = [[-10]]", + "expected_output": "-10", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b21", + "questionid": 86, + "title": "Binary Tree Maximum Path Sum", + "slug": "binary-tree-maximum-path-sum", + "description": "A path in a binary tree is a sequence of nodes where each pair of adjacent nodes in the sequence has an edge connecting them. A node can only appear in the sequence at most once. Note that the path does not need to pass through the root. The path sum of a path is the sum of the node's values in the path. Given the root of a binary tree, return the maximum path sum of any non-empty path. ", + "category": [ + "Dynamic Programming", + "Tree", + "Depth-First Search", + "Binary Tree" + ], + "complexity": "Hard", + "successrate": 37.6, + "totalsubmissions": 1899960, + "totalaccepted": 714542, + "likes": 9151, + "dislikes": 529, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [1,2,3]", + "expected_output": "6", + "explanation": "The optimal path is 2 -> 1 -> 3 with a path sum of 2 + 1 + 3 = 6." + }, + { + "example_num": 2, + "expected_input": "root = [-10,9,20,null,null,15,7]", + "expected_output": "42", + "explanation": "The optimal path is 15 -> 20 -> 7 with a path sum of 15 + 20 + 7 = 42." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b24", + "questionid": 89, + "title": "Sum Root to Leaf Numbers", + "slug": "sum-root-to-leaf-numbers", + "description": "You are given the root of a binary tree containing digits from 0 to 9 only. Each root-to-leaf path in the tree represents a number. Return the total sum of all root-to-leaf numbers. Test cases are generated so that the answer will fit in a 32-bit integer. A leaf node is a node with no children. ", + "category": [ + "Tree", + "Depth-First Search", + "Binary Tree" + ], + "complexity": "Medium", + "successrate": 56.8, + "totalsubmissions": 795340, + "totalaccepted": 451675, + "likes": 4097, + "dislikes": 78, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [1,2,3]", + "expected_output": "25", + "explanation": "The root-to-leaf path 1->2 represents the number 12.\nThe root-to-leaf path 1->3 represents the number 13.\nTherefore, sum = 12 + 13 = 25." + }, + { + "example_num": 2, + "expected_input": "root = [4,9,0,5,1]", + "expected_output": "1026", + "explanation": "The root-to-leaf path 4->9->5 represents the number 495.\nThe root-to-leaf path 4->9->1 represents the number 491.\nThe root-to-leaf path 4->0 represents the number 40.\nTherefore, sum = 495 + 491 + 40 = 1026." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b29", + "questionid": 94, + "title": "Single Number", + "slug": "single-number", + "description": "Given a non-empty array of integers nums, every element appears twice except for one. Find that single one. You must implement a solution with a linear runtime complexity and use only constant extra space. ", + "category": [ + "Array", + "Bit Manipulation" + ], + "complexity": "Easy", + "successrate": 69.3, + "totalsubmissions": 2321213, + "totalaccepted": 1608367, + "likes": 9569, + "dislikes": 339, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [2,2,1]", + "expected_output": "1", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "nums = [4,1,2,1,2]", + "expected_output": "4", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "nums = [1]", + "expected_output": "1", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b30", + "questionid": 101, + "title": "Binary Tree Postorder Traversal", + "slug": "binary-tree-postorder-traversal", + "description": "Given the root of a binary tree, return the postorder traversal of its nodes' values. ", + "category": [ + "Stack", + "Tree", + "Depth-First Search", + "Binary Tree" + ], + "complexity": "Easy", + "successrate": 63.9, + "totalsubmissions": 1095333, + "totalaccepted": 699695, + "likes": 4035, + "dislikes": 136, + "hints": "", + "deleted": false, + "examples": [] + }, + { + "_id": "66f925ddfdfb8e1665720b3a", + "questionid": 111, + "title": "Majority Element", + "slug": "majority-element", + "description": "Given an array nums of size n, return the majority element. The majority element is the element that appears more than n / 2 times. You may assume that the majority element always exists in the array. ", + "category": [ + "Array", + "Hash Table", + "Divide and Conquer", + "Sorting", + "Counting" + ], + "complexity": "Easy", + "successrate": 62.8, + "totalsubmissions": 1906897, + "totalaccepted": 1198357, + "likes": 9327, + "dislikes": 333, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [3,2,3]", + "expected_output": "3", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "nums = [2,2,1,1,1,2,2]", + "expected_output": "2", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b3d", + "questionid": 114, + "title": "Largest Number", + "slug": "largest-number", + "description": "Given a list of non-negative integers nums, arrange them such that they form the largest number and return it. Since the result may be very large, so you need to return a string instead of an integer. ", + "category": [ + "String", + "Greedy", + "Sorting" + ], + "complexity": "Medium", + "successrate": 32.8, + "totalsubmissions": 950354, + "totalaccepted": 312186, + "likes": 4751, + "dislikes": 400, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [10,2]", + "expected_output": ""210"", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "nums = [3,30,34,5,9]", + "expected_output": ""9534330"", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b3f", + "questionid": 116, + "title": "Rotate Array", + "slug": "rotate-array", + "description": "Given an array, rotate the array to the right by k steps, where k is non-negative. ", + "category": [ + "Array", + "Math", + "Two Pointers" + ], + "complexity": "Medium", + "successrate": 38.5, + "totalsubmissions": 2796554, + "totalaccepted": 1077386, + "likes": 9117, + "dislikes": 1268, + "hints": "The easiest solution would use additional memory and that is perfectly fine. The actual trick comes when trying to solve this problem without using any additional memory. This means you need to use the original array somehow to move the elements around. Now, we can place each element in its original location and shift all the elements around it to adjust as that would be too costly and most likely will time out on larger input arrays. One line of thought is based on reversing the array (or parts of it) to obtain the desired result. Think about how reversal might potentially help us out by using an example. The other line of thought is a tad bit complicated but essentially it builds on the idea of placing each element in its original position while keeping track of the element originally in that position. Basically, at every step, we place an element in its rightful position and keep track of the element already there or the one being overwritten in an additional variable. We can't do this in one linear pass and the idea here is based on cyclic-dependencies between elements.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,2,3,4,5,6,7], k = 3", + "expected_output": "[5,6,7,1,2,3,4]", + "explanation": "rotate 1 steps to the right: [7,1,2,3,4,5,6]\nrotate 2 steps to the right: [6,7,1,2,3,4,5]\nrotate 3 steps to the right: [5,6,7,1,2,3,4]" + }, + { + "example_num": 2, + "expected_input": "nums = [-1,-100,3,99], k = 2", + "expected_output": "[3,99,-1,-100]", + "explanation": "rotate 1 steps to the right: [99,-1,-100,3]\nrotate 2 steps to the right: [3,99,-1,-100]" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b42", + "questionid": 119, + "title": "Number of Islands", + "slug": "number-of-islands", + "description": "Given an m x n 2D binary grid grid which represents a map of '1's (land) and '0's (water), return the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water. ", + "category": [ + "Array", + "Depth-First Search", + "Breadth-First Search", + "Union Find", + "Matrix" + ], + "complexity": "Medium", + "successrate": 53.8, + "totalsubmissions": 2825342, + "totalaccepted": 1518896, + "likes": 13254, + "dislikes": 320, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "grid = [\n ["1","1","1","1","0"],\n ["1","1","0","1","0"],\n ["1","1","0","0","0"],\n ["0","0","0","0","0"]\n]", + "expected_output": "1", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "grid = [\n ["1","1","0","0","0"],\n ["1","1","0","0","0"],\n ["0","0","1","0","0"],\n ["0","0","0","1","1"]\n]", + "expected_output": "3", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b0d", + "questionid": 66, + "title": "Unique Binary Search Trees II", + "slug": "unique-binary-search-trees-ii", + "description": "Given an integer n, return all the structurally unique BST's (binary search trees), which has exactly n nodes of unique values from 1 to n. Return the answer in any order. ", + "category": [ + "Dynamic Programming", + "Backtracking", + "Tree", + "Binary Search Tree", + "Binary Tree" + ], + "complexity": "Medium", + "successrate": 49.3, + "totalsubmissions": 612378, + "totalaccepted": 301936, + "likes": 4623, + "dislikes": 302, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 3", + "expected_output": "[[1,null,2,null,3],[1,null,3,2],[2,1,3],[3,1,null,null,2],[3,2,null,1]]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "n = 1", + "expected_output": "[[1]]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b0f", + "questionid": 68, + "title": "Recover Binary Search Tree", + "slug": "recover-binary-search-tree", + "description": "You are given the root of a binary search tree (BST), where the values of exactly two nodes of the tree were swapped by mistake. Recover the tree without changing its structure. ", + "category": [ + "Tree", + "Depth-First Search", + "Binary Search Tree", + "Binary Tree" + ], + "complexity": "Medium", + "successrate": 46.3, + "totalsubmissions": 603807, + "totalaccepted": 279687, + "likes": 4150, + "dislikes": 154, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [1,3,null,null,2]", + "expected_output": "[3,1,null,null,2]", + "explanation": "3 cannot be a left child of 1 because 3 > 1. Swapping 1 and 3 makes the BST valid." + }, + { + "example_num": 2, + "expected_input": "root = [3,1,4,null,null,2]", + "expected_output": "[2,1,4,null,null,3]", + "explanation": "2 cannot be in the right subtree of 3 because 2 < 3. Swapping 2 and 3 makes the BST valid." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b13", + "questionid": 72, + "title": "Binary Tree Zigzag Level Order Traversal", + "slug": "binary-tree-zigzag-level-order-traversal", + "description": "Given the root of a binary tree, return the zigzag level order traversal of its nodes' values. (i.e., from left to right, then right to left for the next level and alternate between). ", + "category": [ + "Tree", + "Breadth-First Search", + "Binary Tree" + ], + "complexity": "Medium", + "successrate": 53.5, + "totalsubmissions": 1299175, + "totalaccepted": 694977, + "likes": 5665, + "dislikes": 168, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [3,9,20,null,null,15,7]", + "expected_output": "[[3],[20,9],[15,7]]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "root = [1]", + "expected_output": "[[1]]", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "root = []", + "expected_output": "[]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b19", + "questionid": 78, + "title": "Convert Sorted List to Binary Search Tree", + "slug": "convert-sorted-list-to-binary-search-tree", + "description": "Given the head of a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST. For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1. ", + "category": [ + "Linked List", + "Divide and Conquer", + "Tree", + "Binary Search Tree", + "Binary Tree" + ], + "complexity": "Medium", + "successrate": 55.4, + "totalsubmissions": 664109, + "totalaccepted": 367942, + "likes": 4468, + "dislikes": 113, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "head = [-10,-3,0,5,9]", + "expected_output": "[0,-3,9,-10,null,5]", + "explanation": "One possible answer is [0,-3,9,-10,null,5], which represents the shown height balanced BST." + }, + { + "example_num": 2, + "expected_input": "head = []", + "expected_output": "[]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b1c", + "questionid": 81, + "title": "Distinct Subsequences", + "slug": "distinct-subsequences", + "description": "Given two strings s and t, return the number of distinct subsequences of s which equals t. A string's subsequence is a new string formed from the original string by deleting some (can be none) of the characters without disturbing the remaining characters' relative positions. (i.e., \"ACE\" is a subsequence of \"ABCDE\" while \"AEC\" is not). The test cases are generated so that the answer fits on a 32-bit signed integer. ", + "category": [ + "String", + "Dynamic Programming" + ], + "complexity": "Hard", + "successrate": 42.2, + "totalsubmissions": 509853, + "totalaccepted": 215300, + "likes": 3321, + "dislikes": 146, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "rabbbit", t = "rabbit"", + "expected_output": "3", + "explanation": "As shown below, there are 3 ways you can generate "rabbit" from s.\nrabbbit\nrabbbit\nrabbbit" + }, + { + "example_num": 2, + "expected_input": "s = "babgbag", t = "bag"", + "expected_output": "5", + "explanation": "As shown below, there are 5 ways you can generate "bag" from s.\nbabgbag\nbabgbag\nbabgbag\nbabgbag\nbabgbag" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b25", + "questionid": 90, + "title": "Surrounded Regions", + "slug": "surrounded-regions", + "description": "Given an m x n matrix board containing 'X' and 'O', capture all regions that are 4-directionally surrounded by 'X'. A region is captured by flipping all 'O's into 'X's in that surrounded region. ", + "category": [ + "Array", + "Depth-First Search", + "Breadth-First Search", + "Union Find", + "Matrix" + ], + "complexity": "Medium", + "successrate": 33.9, + "totalsubmissions": 1196214, + "totalaccepted": 405287, + "likes": 4684, + "dislikes": 1164, + "hints": "", + "deleted": false, + "examples": [] + }, + { + "_id": "66f925ddfdfb8e1665720b28", + "questionid": 93, + "title": "Gas Station", + "slug": "gas-station", + "description": "There are n gas stations along a circular route, where the amount of gas at the ith station is gas[i]. You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from the ith station to its next (i + 1)th station. You begin the journey with an empty tank at one of the gas stations. Given two integer arrays gas and cost, return the starting gas station's index if you can travel around the circuit once in the clockwise direction, otherwise return -1. If there exists a solution, it is guaranteed to be unique ", + "category": [ + "Array", + "Greedy" + ], + "complexity": "Medium", + "successrate": 44.4, + "totalsubmissions": 899594, + "totalaccepted": 399619, + "likes": 5703, + "dislikes": 595, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "gas = [1,2,3,4,5], cost = [3,4,5,1,2]", + "expected_output": "3", + "explanation": "Start at station 3 (index 3) and fill up with 4 unit of gas. Your tank = 0 + 4 = 4\nTravel to station 4. Your tank = 4 - 1 + 5 = 8\nTravel to station 0. Your tank = 8 - 2 + 1 = 7\nTravel to station 1. Your tank = 7 - 3 + 2 = 6\nTravel to station 2. Your tank = 6 - 4 + 3 = 5\nTravel to station 3. The cost is 5. Your gas is just enough to travel back to station 3.\nTherefore, return 3 as the starting index." + }, + { + "example_num": 2, + "expected_input": "gas = [2,3,4], cost = [3,4,3]", + "expected_output": "-1", + "explanation": "You can't start at station 0 or 1, as there is not enough gas to travel to the next station.\nLet's start at station 2 and fill up with 4 unit of gas. Your tank = 0 + 4 = 4\nTravel to station 0. Your tank = 4 - 3 + 2 = 3\nTravel to station 1. Your tank = 3 - 3 + 3 = 3\nYou cannot travel back to station 2, as it requires 4 unit of gas but you only have 3.\nTherefore, you can't travel around the circuit once no matter where you start." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b2b", + "questionid": 96, + "title": "Word Break", + "slug": "word-break", + "description": "Given a string s and a dictionary of strings wordDict, return true if s can be segmented into a space-separated sequence of one or more dictionary words. Note that the same word in the dictionary may be reused multiple times in the segmentation. ", + "category": [ + "Hash Table", + "String", + "Dynamic Programming", + "Trie", + "Memoization" + ], + "complexity": "Medium", + "successrate": 44.5, + "totalsubmissions": 2363412, + "totalaccepted": 1051065, + "likes": 10183, + "dislikes": 448, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "leetcode", wordDict = ["leet","code"]", + "expected_output": "true", + "explanation": "Return true because "leetcode" can be segmented as "leet code"." + }, + { + "example_num": 2, + "expected_input": "s = "applepenapple", wordDict = ["apple","pen"]", + "expected_output": "true", + "explanation": "Return true because "applepenapple" can be segmented as "apple pen apple".\nNote that you are allowed to reuse a dictionary word." + }, + { + "example_num": 3, + "expected_input": "s = "catsandog", wordDict = ["cats","dog","sand","and","cat"]", + "expected_output": "false", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b2d", + "questionid": 98, + "title": "Linked List Cycle", + "slug": "linked-list-cycle", + "description": "Given head, the head of a linked list, determine if the linked list has a cycle in it. There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail's next pointer is connected to. Note that pos is not passed as a parameter. Return true if there is a cycle in the linked list. Otherwise, return false. ", + "category": [ + "Hash Table", + "Linked List", + "Two Pointers" + ], + "complexity": "Easy", + "successrate": 45.8, + "totalsubmissions": 3048390, + "totalaccepted": 1395560, + "likes": 7823, + "dislikes": 773, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "head = [3,2,0,-4], pos = 1", + "expected_output": "true", + "explanation": "There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed)." + }, + { + "example_num": 2, + "expected_input": "head = [1,2], pos = 0", + "expected_output": "true", + "explanation": "There is a cycle in the linked list, where the tail connects to the 0th node." + }, + { + "example_num": 3, + "expected_input": "head = [1], pos = -1", + "expected_output": "false", + "explanation": "There is no cycle in the linked list." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b31", + "questionid": 102, + "title": "Sort List", + "slug": "sort-list", + "description": "Given the head of a linked list, return the list after sorting it in ascending order. ", + "category": [ + "Linked List", + "Two Pointers", + "Divide and Conquer", + "Sorting", + "Merge Sort" + ], + "complexity": "Medium", + "successrate": 51.9, + "totalsubmissions": 930950, + "totalaccepted": 483584, + "likes": 6985, + "dislikes": 229, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "head = [4,2,1,3]", + "expected_output": "[1,2,3,4]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "head = [-1,5,3,4,0]", + "expected_output": "[-1,0,3,4,5]", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "head = []", + "expected_output": "[]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b32", + "questionid": 103, + "title": "Max Points on a Line", + "slug": "max-points-on-a-line", + "description": "Given an array of points where points[i] = [xi, yi] represents a point on the X-Y plane, return the maximum number of points that lie on the same straight line. ", + "category": [ + "Array", + "Hash Table", + "Math", + "Geometry" + ], + "complexity": "Hard", + "successrate": 20.4, + "totalsubmissions": 1113777, + "totalaccepted": 226781, + "likes": 997, + "dislikes": 176, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "points = [[1,1],[2,2],[3,3]]", + "expected_output": "3", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "points = [[1,1],[3,2],[5,3],[4,1],[2,3],[1,4]]", + "expected_output": "4", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b36", + "questionid": 107, + "title": "Find Peak Element", + "slug": "find-peak-element", + "description": "A peak element is an element that is strictly greater than its neighbors. Given an integer array nums, find a peak element, and return its index. If the array contains multiple peaks, return the index to any of the peaks. You may imagine that nums[-1] = nums[n] = -ˆž. You must write an algorithm that runs in O(log n) time. ", + "category": [ + "Array", + "Binary Search" + ], + "complexity": "Medium", + "successrate": 45.9, + "totalsubmissions": 1665853, + "totalaccepted": 764441, + "likes": 5815, + "dislikes": 3661, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,2,3,1]", + "expected_output": "2", + "explanation": "3 is a peak element and your function should return the index number 2." + }, + { + "example_num": 2, + "expected_input": "nums = [1,2,1,3,5,6,4]", + "expected_output": "5", + "explanation": "Your function can return either index number 1 where the peak element is 2, or index number 5 where the peak element is 6." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b3e", + "questionid": 115, + "title": "Repeated DNA Sequences", + "slug": "repeated-dna-sequences", + "description": "The DNA sequence is composed of a series of nucleotides abbreviated as 'A', 'C', 'G', and 'T'. When studying DNA, it is useful to identify repeated sequences within the DNA. Given a string s that represents a DNA sequence, return all the 10-letter-long sequences (substrings) that occur more than once in a DNA molecule. You may return the answer in any order. ", + "category": [ + "Hash Table", + "String", + "Bit Manipulation", + "Sliding Window", + "Rolling Hash", + "Hash Function" + ], + "complexity": "Medium", + "successrate": 44.6, + "totalsubmissions": 587059, + "totalaccepted": 261815, + "likes": 1945, + "dislikes": 406, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = \"AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT\"", + "expected_output": "[\"AAAAACCCCC\",\"CCCCCAAAAA\"]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "s = \"AAAAAAAAAAAAA\"", + "expected_output": "[\"AAAAAAAAAA\"]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b41", + "questionid": 118, + "title": "Binary Tree Right Side View", + "slug": "binary-tree-right-side-view", + "description": "Given the root of a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom. ", + "category": [ + "Tree", + "Depth-First Search", + "Breadth-First Search", + "Binary Tree" + ], + "complexity": "Medium", + "successrate": 59.5, + "totalsubmissions": 1098642, + "totalaccepted": 653709, + "likes": 6288, + "dislikes": 337, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [1,2,3,null,5,null,4]", + "expected_output": "[1,3,4]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "root = [1,null,3]", + "expected_output": "[1,3]", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "root = []", + "expected_output": "[]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b45", + "questionid": 122, + "title": "Count Primes", + "slug": "count-primes", + "description": "Given an integer n, return the number of prime numbers that are strictly less than n. ", + "category": [ + "Array", + "Math", + "Enumeration", + "Number Theory" + ], + "complexity": "Medium", + "successrate": 33, + "totalsubmissions": 1819491, + "totalaccepted": 600270, + "likes": 4703, + "dislikes": 985, + "hints": "Let's start with a isPrime function. To determine if a number is prime, we need to check if it is not divisible by any number less than n. The runtime complexity of isPrime function would be O(n) and hence counting the total prime numbers up to n would be O(n2). Could we do better? As we know the number must not be divisible by any number > n / 2, we can immediately cut the total iterations half by dividing only up to n / 2. Could we still do better? Let's write down all of 12's factors:\n\r\n2 × 6 = 12\r\n3 × 4 = 12\r\n4 × 3 = 12\r\n6 × 2 = 12\r\n\nAs you can see, calculations of 4 × 3 and 6 × 2 are not necessary. Therefore, we only need to consider factors up to ˆšn because, if n is divisible by some number p, then n = p × q and since p ‰¤ q, we could derive that p ‰¤ ˆšn.\nOur total runtime has now improved to O(n1.5), which is slightly better. Is there a faster approach?\n\r\npublic int countPrimes(int n) {\r\n int count = 0;\r\n for (int i = 1; i < n; i++) {\r\n if (isPrime(i)) count++;\r\n }\r\n return count;\r\n}\r\n\r\nprivate boolean isPrime(int num) {\r\n if (num <= 1) return false;\r\n // Loop's ending condition is i * i <= num instead of i <= sqrt(num)\r\n // to avoid repeatedly calling an expensive function sqrt().\r\n for (int i = 2; i * i <= num; i++) {\r\n if (num % i == 0) return false;\r\n }\r\n return true;\r\n} The Sieve of Eratosthenes is one of the most efficient ways to find all prime numbers up to n. But don't let that name scare you, I promise that the concept is surprisingly simple.\n\n\nSieve of Eratosthenes: algorithm steps for primes below 121. \"Sieve of Eratosthenes Animation\" by SKopp is licensed under CC BY 2.0.\n\nWe start off with a table of n numbers. Let's look at the first number, 2. We know all multiples of 2 must not be primes, so we mark them off as non-primes. Then we look at the next number, 3. Similarly, all multiples of 3 such as 3 × 2 = 6, 3 × 3 = 9, ... must not be primes, so we mark them off as well. Now we look at the next number, 4, which was already marked off. What does this tell you? Should you mark off all multiples of 4 as well? 4 is not a prime because it is divisible by 2, which means all multiples of 4 must also be divisible by 2 and were already marked off. So we can skip 4 immediately and go to the next number, 5. Now, all multiples of 5 such as 5 × 2 = 10, 5 × 3 = 15, 5 × 4 = 20, 5 × 5 = 25, ... can be marked off. There is a slight optimization here, we do not need to start from 5 × 2 = 10. Where should we start marking off? In fact, we can mark off multiples of 5 starting at 5 × 5 = 25, because 5 × 2 = 10 was already marked off by multiple of 2, similarly 5 × 3 = 15 was already marked off by multiple of 3. Therefore, if the current number is p, we can always mark off multiples of p starting at p2, then in increments of p: p2 + p, p2 + 2p, ... Now what should be the terminating loop condition? It is easy to say that the terminating loop condition is p < n, which is certainly correct but not efficient. Do you still remember Hint #3? Yes, the terminating loop condition can be p < ˆšn, as all non-primes ‰¥ ˆšn must have already been marked off. When the loop terminates, all the numbers in the table that are non-marked are prime.\nThe Sieve of Eratosthenes uses an extra O(n) memory and its runtime complexity is O(n log log n). For the more mathematically inclined readers, you can read more about its algorithm complexity on Wikipedia.\n\r\npublic int countPrimes(int n) {\r\n boolean[] isPrime = new boolean[n];\r\n for (int i = 2; i < n; i++) {\r\n isPrime[i] = true;\r\n }\r\n // Loop's ending condition is i * i < n instead of i < sqrt(n)\r\n // to avoid repeatedly calling an expensive function sqrt().\r\n for (int i = 2; i * i < n; i++) {\r\n if (!isPrime[i]) continue;\r\n for (int j = i * i; j < n; j += i) {\r\n isPrime[j] = false;\r\n }\r\n }\r\n int count = 0;\r\n for (int i = 2; i < n; i++) {\r\n if (isPrime[i]) count++;\r\n }\r\n return count;\r\n}", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 10", + "expected_output": "4", + "explanation": "There are 4 prime numbers less than 10, they are 2, 3, 5, 7." + }, + { + "example_num": 2, + "expected_input": "n = 0", + "expected_output": "0", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "n = 1", + "expected_output": "0", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b48", + "questionid": 125, + "title": "Course Schedule", + "slug": "course-schedule", + "description": "There are a total of numCourses courses you have to take, labeled from 0 to numCourses - 1. You are given an array prerequisites where prerequisites[i] = [ai, bi] indicates that you must take course bi first if you want to take course ai. Return true if you can finish all courses. Otherwise, return false. ", + "category": [ + "Depth-First Search", + "Breadth-First Search", + "Graph", + "Topological Sort" + ], + "complexity": "Medium", + "successrate": 45, + "totalsubmissions": 1871795, + "totalaccepted": 842989, + "likes": 9007, + "dislikes": 362, + "hints": "This problem is equivalent to finding if a cycle exists in a directed graph. If a cycle exists, no topological ordering exists and therefore it will be impossible to take all courses. Topological Sort via DFS - A great video tutorial (21 minutes) on Coursera explaining the basic concepts of Topological Sort. Topological sort could also be done via BFS.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "numCourses = 2, prerequisites = [[1,0]]", + "expected_output": "true", + "explanation": "There are a total of 2 courses to take. \nTo take course 1 you should have finished course 0. So it is possible." + }, + { + "example_num": 2, + "expected_input": "numCourses = 2, prerequisites = [[1,0],[0,1]]", + "expected_output": "false", + "explanation": "There are a total of 2 courses to take. \nTo take course 1 you should have finished course 0, and to take course 0 you should also have finished course 1. So it is impossible." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b49", + "questionid": 126, + "title": "Minimum Size Subarray Sum", + "slug": "minimum-size-subarray-sum", + "description": "Given an array of positive integers nums and a positive integer target, return the minimal length of a contiguous subarray [numsl, numsl+1, ..., numsr-1, numsr] of which the sum is greater than or equal to target. If there is no such subarray, return 0 instead. ", + "category": [ + "Array", + "Binary Search", + "Sliding Window", + "Prefix Sum" + ], + "complexity": "Medium", + "successrate": 43.2, + "totalsubmissions": 1177660, + "totalaccepted": 508413, + "likes": 6324, + "dislikes": 185, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "target = 7, nums = [2,3,1,2,4,3]", + "expected_output": "2", + "explanation": "The subarray [4,3] has the minimal length under the problem constraint." + }, + { + "example_num": 2, + "expected_input": "target = 4, nums = [1,4,4]", + "expected_output": "1", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "target = 11, nums = [1,1,1,1,1,1,1,1]", + "expected_output": "0", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b4b", + "questionid": 128, + "title": "Word Search II", + "slug": "word-search-ii", + "description": "Given an m x n board of characters and a list of strings words, return all words on the board. Each word must be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once in a word. ", + "category": [ + "Array", + "String", + "Backtracking", + "Trie", + "Matrix" + ], + "complexity": "Hard", + "successrate": 38.1, + "totalsubmissions": 1120097, + "totalaccepted": 426210, + "likes": 5820, + "dislikes": 213, + "hints": "You would need to optimize your backtracking to pass the larger test. Could you stop backtracking earlier? If the current candidate does not exist in all words' prefix, you could stop backtracking immediately. What kind of data structure could answer such query efficiently? Does a hash table work? Why or why not? How about a Trie? If you would like to learn how to implement a basic trie, please work on this problem: Implement Trie (Prefix Tree) first.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "board = [["o","a","a","n"],["e","t","a","e"],["i","h","k","r"],["i","f","l","v"]], words = ["oath","pea","eat","rain"]", + "expected_output": "["eat","oath"]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "board = [["a","b"],["c","d"]], words = ["abcb"]", + "expected_output": "[]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b10", + "questionid": 69, + "title": "Same Tree", + "slug": "same-tree", + "description": "Given the roots of two binary trees p and q, write a function to check if they are the same or not. Two binary trees are considered the same if they are structurally identical, and the nodes have the same value. ", + "category": [ + "Tree", + "Depth-First Search", + "Breadth-First Search", + "Binary Tree" + ], + "complexity": "Easy", + "successrate": 55.5, + "totalsubmissions": 1816972, + "totalaccepted": 1008051, + "likes": 5477, + "dislikes": 132, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "p = [1,2,3], q = [1,2,3]", + "expected_output": "true", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "p = [1,2], q = [1,null,2]", + "expected_output": "false", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "p = [1,2,1], q = [1,1,2]", + "expected_output": "false", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b15", + "questionid": 74, + "title": "Construct Binary Tree from Preorder and Inorder Traversal", + "slug": "construct-binary-tree-from-preorder-and-inorder-traversal", + "description": "Given two integer arrays preorder and inorder where preorder is the preorder traversal of a binary tree and inorder is the inorder traversal of the same tree, construct and return the binary tree. ", + "category": [ + "Array", + "Hash Table", + "Divide and Conquer", + "Tree", + "Binary Tree" + ], + "complexity": "Medium", + "successrate": 57.5, + "totalsubmissions": 1199122, + "totalaccepted": 688958, + "likes": 8192, + "dislikes": 218, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]", + "expected_output": "[3,9,20,null,null,15,7]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "preorder = [-1], inorder = [-1]", + "expected_output": "[-1]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b18", + "questionid": 77, + "title": "Convert Sorted Array to Binary Search Tree", + "slug": "convert-sorted-array-to-binary-search-tree", + "description": "Given an integer array nums where the elements are sorted in ascending order, convert it to a height-balanced binary search tree. A height-balanced binary tree is a binary tree in which the depth of the two subtrees of every node never differs by more than one. ", + "category": [ + "Array", + "Divide and Conquer", + "Tree", + "Binary Search Tree", + "Binary Tree" + ], + "complexity": "Easy", + "successrate": 65.9, + "totalsubmissions": 1096431, + "totalaccepted": 722308, + "likes": 6158, + "dislikes": 349, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [-10,-3,0,5,9]", + "expected_output": "[0,-3,9,-10,null,5]", + "explanation": "[0,-10,5,null,-3,null,9] is also accepted:\n\"\"" + }, + { + "example_num": 2, + "expected_input": "nums = [1,3]", + "expected_output": "[3,1]", + "explanation": "[1,null,3] and [3,1] are both height-balanced BSTs." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b1f", + "questionid": 84, + "title": "Best Time to Buy and Sell Stock", + "slug": "best-time-to-buy-and-sell-stock", + "description": "You are given an array prices where prices[i] is the price of a given stock on the ith day. You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock. Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0. ", + "category": [ + "Array", + "Dynamic Programming" + ], + "complexity": "Easy", + "successrate": 54, + "totalsubmissions": 3860000, + "totalaccepted": 2084089, + "likes": 15488, + "dislikes": 522, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "prices = [7,1,5,3,6,4]", + "expected_output": "5", + "explanation": "Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.\nNote that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell." + }, + { + "example_num": 2, + "expected_input": "prices = [7,6,4,3,1]", + "expected_output": "0", + "explanation": "In this case, no transactions are done and the max profit = 0." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b20", + "questionid": 85, + "title": "Best Time to Buy and Sell Stock II", + "slug": "best-time-to-buy-and-sell-stock-ii", + "description": "You are given an integer array prices where prices[i] is the price of a given stock on the ith day. On each day, you may decide to buy and/or sell the stock. You can only hold at most one share of the stock at any time. However, you can buy it then immediately sell it on the same day. Find and return the maximum profit you can achieve. ", + "category": [ + "Array", + "Dynamic Programming", + "Greedy" + ], + "complexity": "Medium", + "successrate": 61.9, + "totalsubmissions": 1815327, + "totalaccepted": 1123641, + "likes": 7301, + "dislikes": 2353, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "prices = [7,1,5,3,6,4]", + "expected_output": "7", + "explanation": "Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.\nThen buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.\nTotal profit is 4 + 3 = 7." + }, + { + "example_num": 2, + "expected_input": "prices = [1,2,3,4,5]", + "expected_output": "4", + "explanation": "Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.\nTotal profit is 4." + }, + { + "example_num": 3, + "expected_input": "prices = [7,6,4,3,1]", + "expected_output": "0", + "explanation": "There is no way to make a positive profit, so we never buy the stock to achieve the maximum profit of 0." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b22", + "questionid": 87, + "title": "Valid Palindrome", + "slug": "valid-palindrome", + "description": "A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers. Given a string s, return true if it is a palindrome, or false otherwise. ", + "category": [ + "Two Pointers", + "String" + ], + "complexity": "Easy", + "successrate": 41.5, + "totalsubmissions": 2944250, + "totalaccepted": 1220904, + "likes": 3460, + "dislikes": 5081, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "A man, a plan, a canal: Panama"", + "expected_output": "true", + "explanation": ""amanaplanacanalpanama" is a palindrome." + }, + { + "example_num": 2, + "expected_input": "s = "race a car"", + "expected_output": "false", + "explanation": ""raceacar" is not a palindrome." + }, + { + "example_num": 3, + "expected_input": "s = " "", + "expected_output": "true", + "explanation": "s is an empty string "" after removing non-alphanumeric characters.\nSince an empty string reads the same forward and backward, it is a palindrome." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b23", + "questionid": 88, + "title": "Longest Consecutive Sequence", + "slug": "longest-consecutive-sequence", + "description": "Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence. You must write an algorithm that runs in O(n) time. ", + "category": [ + "Array", + "Hash Table", + "Union Find" + ], + "complexity": "Medium", + "successrate": 48.7, + "totalsubmissions": 1319683, + "totalaccepted": 642062, + "likes": 9034, + "dislikes": 398, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [100,4,200,1,3,2]", + "expected_output": "4", + "explanation": "The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4." + }, + { + "example_num": 2, + "expected_input": "nums = [0,3,7,2,5,8,4,6,0,1]", + "expected_output": "9", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b2a", + "questionid": 95, + "title": "Single Number II", + "slug": "single-number-ii", + "description": "Given an integer array nums where every element appears three times except for one, which appears exactly once. Find the single element and return it. You must implement a solution with a linear runtime complexity and use only constant extra space. ", + "category": [ + "Array", + "Bit Manipulation" + ], + "complexity": "Medium", + "successrate": 56.5, + "totalsubmissions": 605201, + "totalaccepted": 342067, + "likes": 4009, + "dislikes": 475, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [2,2,3,2]", + "expected_output": "3", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "nums = [0,1,0,1,0,1,99]", + "expected_output": "99", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b2f", + "questionid": 100, + "title": "Binary Tree Preorder Traversal", + "slug": "binary-tree-preorder-traversal", + "description": "Given the root of a binary tree, return the preorder traversal of its nodes' values. ", + "category": [ + "Stack", + "Tree", + "Depth-First Search", + "Binary Tree" + ], + "complexity": "Easy", + "successrate": 62.3, + "totalsubmissions": 1471175, + "totalaccepted": 917273, + "likes": 3931, + "dislikes": 125, + "hints": "", + "deleted": false, + "examples": [] + }, + { + "_id": "66f925ddfdfb8e1665720b33", + "questionid": 104, + "title": "Evaluate Reverse Polish Notation", + "slug": "evaluate-reverse-polish-notation", + "description": "Evaluate the value of an arithmetic expression in Reverse Polish Notation. Valid operators are +, -, *, and /. Each operand may be an integer or another expression. Note that division between two integers should truncate toward zero. It is guaranteed that the given RPN expression is always valid. That means the expression would always evaluate to a result, and there will not be any division by zero operation. ", + "category": [ + "Array", + "Math", + "Stack" + ], + "complexity": "Medium", + "successrate": 42.3, + "totalsubmissions": 936103, + "totalaccepted": 396146, + "likes": 2884, + "dislikes": 615, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "tokens = ["2","1","+","3","*"]", + "expected_output": "9", + "explanation": "((2 + 1) * 3) = 9" + }, + { + "example_num": 2, + "expected_input": "tokens = ["4","13","5","/","+"]", + "expected_output": "6", + "explanation": "(4 + (13 / 5)) = 6" + }, + { + "example_num": 3, + "expected_input": "tokens = ["10","6","9","3","+","-11","*","/","*","17","+","5","+"]", + "expected_output": "22", + "explanation": "((10 * (6 / ((9 + 3) * -11))) + 17) + 5\n= ((10 * (6 / (12 * -11))) + 17) + 5\n= ((10 * (6 / -132)) + 17) + 5\n= ((10 * 0) + 17) + 5\n= (0 + 17) + 5\n= 17 + 5\n= 22" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b34", + "questionid": 105, + "title": "Reverse Words in a String", + "slug": "reverse-words-in-a-string", + "description": "Given an input string s, reverse the order of the words. A word is defined as a sequence of non-space characters. The words in s will be separated by at least one space. Return a string of the words in reverse order concatenated by a single space. Note that s may contain leading or trailing spaces or multiple spaces between two words. The returned string should only have a single space separating the words. Do not include any extra spaces. ", + "category": [ + "Two Pointers", + "String" + ], + "complexity": "Medium", + "successrate": 28.4, + "totalsubmissions": 2433332, + "totalaccepted": 690127, + "likes": 3004, + "dislikes": 3851, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "the sky is blue"", + "expected_output": ""blue is sky the"", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "s = " hello world "", + "expected_output": ""world hello"", + "explanation": "Your reversed string should not contain leading or trailing spaces." + }, + { + "example_num": 3, + "expected_input": "s = "a good example"", + "expected_output": ""example good a"", + "explanation": "You need to reduce multiple spaces between two words to a single space in the reversed string." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b35", + "questionid": 106, + "title": "Maximum Product Subarray", + "slug": "maximum-product-subarray", + "description": "Given an integer array nums, find a contiguous non-empty subarray within the array that has the largest product, and return the product. The test cases are generated so that the answer will fit in a 32-bit integer. A subarray is a contiguous subsequence of the array. ", + "category": [ + "Array", + "Dynamic Programming" + ], + "complexity": "Medium", + "successrate": 34.5, + "totalsubmissions": 2086147, + "totalaccepted": 720227, + "likes": 11150, + "dislikes": 345, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [2,3,-2,4]", + "expected_output": "6", + "explanation": "[2,3] has the largest product 6." + }, + { + "example_num": 2, + "expected_input": "nums = [-2,0,-1]", + "expected_output": "0", + "explanation": "The result cannot be 2, because [-2,-1] is not a subarray." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b39", + "questionid": 110, + "title": "Two Sum II - Input Array Is Sorted", + "slug": "two-sum-ii-input-array-is-sorted", + "description": "Given a 1-indexed array of integers numbers that is already sorted in non-decreasing order, find two numbers such that they add up to a specific target number. Let these two numbers be numbers[index1] and numbers[index2] where 1 <= index1 < index2 <= numbers.length. Return the indices of the two numbers, index1 and index2, added by one as an integer array [index1, index2] of length 2. The tests are generated such that there is exactly one solution. You may not use the same element twice. Your solution must use only constant extra space. ", + "category": [ + "Array", + "Two Pointers", + "Binary Search" + ], + "complexity": "Medium", + "successrate": 58.6, + "totalsubmissions": 1583339, + "totalaccepted": 928226, + "likes": 5160, + "dislikes": 923, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "numbers = [2,7,11,15], target = 9", + "expected_output": "[1,2]", + "explanation": "The sum of 2 and 7 is 9. Therefore, index1 = 1, index2 = 2. We return [1, 2]." + }, + { + "example_num": 2, + "expected_input": "numbers = [2,3,4], target = 6", + "expected_output": "[1,3]", + "explanation": "The sum of 2 and 4 is 6. Therefore index1 = 1, index2 = 3. We return [1, 3]." + }, + { + "example_num": 3, + "expected_input": "numbers = [-1,0], target = -1", + "expected_output": "[1,2]", + "explanation": "The sum of -1 and 0 is -1. Therefore index1 = 1, index2 = 2. We return [1, 2]." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b3c", + "questionid": 113, + "title": "Dungeon Game", + "slug": "dungeon-game", + "description": "The demons had captured the princess and imprisoned her in the bottom-right corner of a dungeon. The dungeon consists of m x n rooms laid out in a 2D grid. Our valiant knight was initially positioned in the top-left room and must fight his way through dungeon to rescue the princess. The knight has an initial health point represented by a positive integer. If at any point his health point drops to 0 or below, he dies immediately. Some of the rooms are guarded by demons (represented by negative integers), so the knight loses health upon entering these rooms; other rooms are either empty (represented as 0) or contain magic orbs that increase the knight's health (represented by positive integers). To reach the princess as quickly as possible, the knight decides to move only rightward or downward in each step. Return the knight's minimum initial health so that he can rescue the princess. Note that any room can contain threats or power-ups, even the first room the knight enters and the bottom-right room where the princess is imprisoned. ", + "category": [ + "Array", + "Dynamic Programming", + "Matrix" + ], + "complexity": "Hard", + "successrate": 36.4, + "totalsubmissions": 465945, + "totalaccepted": 169797, + "likes": 3977, + "dislikes": 80, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "dungeon = [[-2,-3,3],[-5,-10,1],[10,30,-5]]", + "expected_output": "7", + "explanation": "The initial health of the knight must be at least 7 if he follows the optimal path: RIGHT-> RIGHT -> DOWN -> DOWN." + }, + { + "example_num": 2, + "expected_input": "dungeon = [[0]]", + "expected_output": "1", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b43", + "questionid": 120, + "title": "Bitwise AND of Numbers Range", + "slug": "bitwise-and-of-numbers-range", + "description": "Given two integers left and right that represent the range [left, right], return the bitwise AND of all numbers in this range, inclusive. ", + "category": [ + "Bit Manipulation" + ], + "complexity": "Medium", + "successrate": 41.8, + "totalsubmissions": 510983, + "totalaccepted": 213336, + "likes": 2225, + "dislikes": 176, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "left = 5, right = 7", + "expected_output": "4", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "left = 0, right = 0", + "expected_output": "0", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "left = 1, right = 2147483647", + "expected_output": "0", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b44", + "questionid": 121, + "title": "Remove Linked List Elements", + "slug": "remove-linked-list-elements", + "description": "Given the head of a linked list and an integer val, remove all the nodes of the linked list that has Node.val == val, and return the new head. ", + "category": [ + "Linked List", + "Recursion" + ], + "complexity": "Easy", + "successrate": 43.4, + "totalsubmissions": 1582236, + "totalaccepted": 686326, + "likes": 4794, + "dislikes": 162, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "head = [1,2,6,3,4,5,6], val = 6", + "expected_output": "[1,2,3,4,5]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "head = [], val = 1", + "expected_output": "[]", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "head = [7,7,7,7], val = 7", + "expected_output": "[]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b46", + "questionid": 123, + "title": "Isomorphic Strings", + "slug": "isomorphic-strings", + "description": "Given two strings s and t, determine if they are isomorphic. Two strings s and t are isomorphic if the characters in s can be replaced to get t. All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character, but a character may map to itself. ", + "category": [ + "Hash Table", + "String" + ], + "complexity": "Easy", + "successrate": 42.1, + "totalsubmissions": 1160012, + "totalaccepted": 487870, + "likes": 3435, + "dislikes": 638, + "hints": "", + "deleted": false, + "examples": [] + }, + { + "_id": "66f925ddfdfb8e1665720b4a", + "questionid": 127, + "title": "Course Schedule II", + "slug": "course-schedule-ii", + "description": "There are a total of numCourses courses you have to take, labeled from 0 to numCourses - 1. You are given an array prerequisites where prerequisites[i] = [ai, bi] indicates that you must take course bi first if you want to take course ai. Return the ordering of courses you should take to finish all courses. If there are many valid answers, return any of them. If it is impossible to finish all courses, return an empty array. ", + "category": [ + "Depth-First Search", + "Breadth-First Search", + "Graph", + "Topological Sort" + ], + "complexity": "Medium", + "successrate": 46.4, + "totalsubmissions": 1304440, + "totalaccepted": 605688, + "likes": 6464, + "dislikes": 232, + "hints": "This problem is equivalent to finding the topological order in a directed graph. If a cycle exists, no topological ordering exists and therefore it will be impossible to take all courses. Topological Sort via DFS - A great video tutorial (21 minutes) on Coursera explaining the basic concepts of Topological Sort. Topological sort could also be done via BFS.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "numCourses = 2, prerequisites = [[1,0]]", + "expected_output": "[0,1]", + "explanation": "There are a total of 2 courses to take. To take course 1 you should have finished course 0. So the correct course order is [0,1]." + }, + { + "example_num": 2, + "expected_input": "numCourses = 4, prerequisites = [[1,0],[2,0],[3,1],[3,2]]", + "expected_output": "[0,2,1,3]", + "explanation": "There are a total of 4 courses to take. To take course 3 you should have finished both courses 1 and 2. Both courses 1 and 2 should be taken after you finished course 0.\nSo one correct course order is [0,1,2,3]. Another correct ordering is [0,2,1,3]." + }, + { + "example_num": 3, + "expected_input": "numCourses = 1, prerequisites = []", + "expected_output": "[0]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b0c", + "questionid": 65, + "title": "Binary Tree Inorder Traversal", + "slug": "binary-tree-inorder-traversal", + "description": "Given the root of a binary tree, return the inorder traversal of its nodes' values. ", + "category": [ + "Stack", + "Tree", + "Depth-First Search", + "Binary Tree" + ], + "complexity": "Easy", + "successrate": 70.6, + "totalsubmissions": 2018990, + "totalaccepted": 1425499, + "likes": 7405, + "dislikes": 335, + "hints": "", + "deleted": false, + "examples": [] + }, + { + "_id": "66f925ddfdfb8e1665720b0e", + "questionid": 67, + "title": "Unique Binary Search Trees", + "slug": "unique-binary-search-trees", + "description": "Given an integer n, return the number of structurally unique BST's (binary search trees) which has exactly n nodes of unique values from 1 to n. ", + "category": [ + "Math", + "Dynamic Programming", + "Tree", + "Binary Search Tree", + "Binary Tree" + ], + "complexity": "Medium", + "successrate": 58.2, + "totalsubmissions": 815533, + "totalaccepted": 474825, + "likes": 7042, + "dislikes": 284, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 3", + "expected_output": "5", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "n = 1", + "expected_output": "1", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b14", + "questionid": 73, + "title": "Maximum Depth of Binary Tree", + "slug": "maximum-depth-of-binary-tree", + "description": "Given the root of a binary tree, return its maximum depth. A binary tree's maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. ", + "category": [ + "Tree", + "Depth-First Search", + "Breadth-First Search", + "Binary Tree" + ], + "complexity": "Easy", + "successrate": 71.8, + "totalsubmissions": 2259723, + "totalaccepted": 1621474, + "likes": 6744, + "dislikes": 124, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [3,9,20,null,null,15,7]", + "expected_output": "3", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "root = [1,null,2]", + "expected_output": "2", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b16", + "questionid": 75, + "title": "Construct Binary Tree from Inorder and Postorder Traversal", + "slug": "construct-binary-tree-from-inorder-and-postorder-traversal", + "description": "Given two integer arrays inorder and postorder where inorder is the inorder traversal of a binary tree and postorder is the postorder traversal of the same tree, construct and return the binary tree. ", + "category": [ + "Array", + "Hash Table", + "Divide and Conquer", + "Tree", + "Binary Tree" + ], + "complexity": "Medium", + "successrate": 55.2, + "totalsubmissions": 707765, + "totalaccepted": 390759, + "likes": 4348, + "dislikes": 72, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "inorder = [9,3,15,20,7], postorder = [9,15,7,20,3]", + "expected_output": "[3,9,20,null,null,15,7]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "inorder = [-1], postorder = [-1]", + "expected_output": "[-1]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b1b", + "questionid": 80, + "title": "Path Sum II", + "slug": "path-sum-ii", + "description": "Given the root of a binary tree and an integer targetSum, return all root-to-leaf paths where the sum of the node values in the path equals targetSum. Each path should be returned as a list of the node values, not node references. A root-to-leaf path is a path starting from the root and ending at any leaf node. A leaf is a node with no children. ", + "category": [ + "Backtracking", + "Tree", + "Depth-First Search", + "Binary Tree" + ], + "complexity": "Medium", + "successrate": 53.9, + "totalsubmissions": 1052748, + "totalaccepted": 567301, + "likes": 4603, + "dislikes": 109, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22", + "expected_output": "[[5,4,11,2],[5,8,4,5]]", + "explanation": "There are two paths whose sum equals targetSum:\n5 + 4 + 11 + 2 = 22\n5 + 8 + 4 + 5 = 22" + }, + { + "example_num": 2, + "expected_input": "root = [1,2,3], targetSum = 5", + "expected_output": "[]", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "root = [1,2], targetSum = 0", + "expected_output": "[]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b26", + "questionid": 91, + "title": "Palindrome Partitioning", + "slug": "palindrome-partitioning", + "description": "Given a string s, partition s such that every substring of the partition is a palindrome. Return all possible palindrome partitioning of s. A palindrome string is a string that reads the same backward as forward. ", + "category": [ + "String", + "Dynamic Programming", + "Backtracking" + ], + "complexity": "Medium", + "successrate": 59.3, + "totalsubmissions": 746356, + "totalaccepted": 442390, + "likes": 6475, + "dislikes": 201, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = \"aab\"", + "expected_output": "[[\"a\",\"a\",\"b\"],[\"aa\",\"b\"]]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "s = \"a\"", + "expected_output": "[[\"a\"]]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b27", + "questionid": 92, + "title": "Palindrome Partitioning II", + "slug": "palindrome-partitioning-ii", + "description": "Given a string s, partition s such that every substring of the partition is a palindrome. Return the minimum cuts needed for a palindrome partitioning of s. ", + "category": [ + "String", + "Dynamic Programming" + ], + "complexity": "Hard", + "successrate": 33.1, + "totalsubmissions": 606455, + "totalaccepted": 200922, + "likes": 3268, + "dislikes": 77, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "aab"", + "expected_output": "1", + "explanation": "The palindrome partitioning ["aa","b"] could be produced using 1 cut." + }, + { + "example_num": 2, + "expected_input": "s = "a"", + "expected_output": "0", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "s = "ab"", + "expected_output": "1", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b2c", + "questionid": 97, + "title": "Word Break II", + "slug": "word-break-ii", + "description": "Given a string s and a dictionary of strings wordDict, add spaces in s to construct a sentence where each word is a valid dictionary word. Return all such possible sentences in any order. Note that the same word in the dictionary may be reused multiple times in the segmentation. ", + "category": [ + "Hash Table", + "String", + "Dynamic Programming", + "Backtracking", + "Trie", + "Memoization" + ], + "complexity": "Hard", + "successrate": 41.9, + "totalsubmissions": 1036483, + "totalaccepted": 434784, + "likes": 4595, + "dislikes": 475, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "catsanddog", wordDict = ["cat","cats","and","sand","dog"]", + "expected_output": "["cats and dog","cat sand dog"]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "s = "pineapplepenapple", wordDict = ["apple","pen","applepen","pine","pineapple"]", + "expected_output": "["pine apple pen apple","pineapple pen apple","pine applepen apple"]", + "explanation": "Note that you are allowed to reuse a dictionary word." + }, + { + "example_num": 3, + "expected_input": "s = "catsandog", wordDict = ["cats","dog","sand","and","cat"]", + "expected_output": "[]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b2e", + "questionid": 99, + "title": "Linked List Cycle II", + "slug": "linked-list-cycle-ii", + "description": "Given the head of a linked list, return the node where the cycle begins. If there is no cycle, return null. There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail's next pointer is connected to (0-indexed). It is -1 if there is no cycle. Note that pos is not passed as a parameter. Do not modify the linked list. ", + "category": [ + "Hash Table", + "Linked List", + "Two Pointers" + ], + "complexity": "Medium", + "successrate": 44.1, + "totalsubmissions": 1486657, + "totalaccepted": 656083, + "likes": 7044, + "dislikes": 462, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "head = [3,2,0,-4], pos = 1", + "expected_output": "tail connects to node index 1", + "explanation": "There is a cycle in the linked list, where tail connects to the second node." + }, + { + "example_num": 2, + "expected_input": "head = [1,2], pos = 0", + "expected_output": "tail connects to node index 0", + "explanation": "There is a cycle in the linked list, where tail connects to the first node." + }, + { + "example_num": 3, + "expected_input": "head = [1], pos = -1", + "expected_output": "no cycle", + "explanation": "There is no cycle in the linked list." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b37", + "questionid": 108, + "title": "Maximum Gap", + "slug": "maximum-gap", + "description": "Given an integer array nums, return the maximum difference between two successive elements in its sorted form. If the array contains less than two elements, return 0. You must write an algorithm that runs in linear time and uses linear extra space. ", + "category": [ + "Array", + "Sorting", + "Bucket Sort", + "Radix Sort" + ], + "complexity": "Hard", + "successrate": 41.3, + "totalsubmissions": 333410, + "totalaccepted": 137727, + "likes": 2054, + "dislikes": 281, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [3,6,9,1]", + "expected_output": "3", + "explanation": "The sorted form of the array is [1,3,6,9], either (3,6) or (6,9) has the maximum difference 3." + }, + { + "example_num": 2, + "expected_input": "nums = [10]", + "expected_output": "0", + "explanation": "The array contains less than 2 elements, therefore return 0." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b38", + "questionid": 109, + "title": "Fraction to Recurring Decimal", + "slug": "fraction-to-recurring-decimal", + "description": "Given two integers representing the numerator and denominator of a fraction, return the fraction in string format. If the fractional part is repeating, enclose the repeating part in parentheses. If multiple answers are possible, return any of them. It is guaranteed that the length of the answer string is less than 104 for all the given inputs. ", + "category": [ + "Hash Table", + "Math", + "String" + ], + "complexity": "Medium", + "successrate": 23.6, + "totalsubmissions": 770005, + "totalaccepted": 181343, + "likes": 1555, + "dislikes": 2915, + "hints": "No scary math, just apply elementary math knowledge. Still remember how to perform a long division? Try a long division on 4/9, the repeating part is obvious. Now try 4/333. Do you see a pattern? Notice that once the remainder starts repeating, so does the divided result. Be wary of edge cases! List out as many test cases as you can think of and test your code thoroughly.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "numerator = 1, denominator = 2", + "expected_output": ""0.5"", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "numerator = 2, denominator = 1", + "expected_output": ""2"", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "numerator = 4, denominator = 333", + "expected_output": ""0.(012)"", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b3b", + "questionid": 112, + "title": "Factorial Trailing Zeroes", + "slug": "factorial-trailing-zeroes", + "description": "Given an integer n, return the number of trailing zeroes in n!. Note that n! = n * (n - 1) * (n - 2) * ... * 3 * 2 * 1. ", + "category": [ + "Math" + ], + "complexity": "Medium", + "successrate": 40.7, + "totalsubmissions": 769195, + "totalaccepted": 313232, + "likes": 1949, + "dislikes": 1657, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 3", + "expected_output": "0", + "explanation": "3! = 6, no trailing zero." + }, + { + "example_num": 2, + "expected_input": "n = 5", + "expected_output": "1", + "explanation": "5! = 120, one trailing zero." + }, + { + "example_num": 3, + "expected_input": "n = 0", + "expected_output": "0", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b40", + "questionid": 117, + "title": "House Robber", + "slug": "house-robber", + "description": "You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security systems connected and it will automatically contact the police if two adjacent houses were broken into on the same night. Given an integer array nums representing the amount of money of each house, return the maximum amount of money you can rob tonight without alerting the police. ", + "category": [ + "Array", + "Dynamic Programming" + ], + "complexity": "Medium", + "successrate": 47, + "totalsubmissions": 2334058, + "totalaccepted": 1098090, + "likes": 11854, + "dislikes": 255, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,2,3,1]", + "expected_output": "4", + "explanation": "Rob house 1 (money = 1) and then rob house 3 (money = 3).\nTotal amount you can rob = 1 + 3 = 4." + }, + { + "example_num": 2, + "expected_input": "nums = [2,7,9,3,1]", + "expected_output": "12", + "explanation": "Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1).\nTotal amount you can rob = 2 + 9 + 1 = 12." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b47", + "questionid": 124, + "title": "Reverse Linked List", + "slug": "reverse-linked-list", + "description": "Given the head of a singly linked list, reverse the list, and return the reversed list. ", + "category": [ + "Linked List", + "Recursion" + ], + "complexity": "Easy", + "successrate": 70.1, + "totalsubmissions": 2927119, + "totalaccepted": 2052205, + "likes": 11446, + "dislikes": 199, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "head = [1,2,3,4,5]", + "expected_output": "[5,4,3,2,1]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "head = [1,2]", + "expected_output": "[2,1]", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "head = []", + "expected_output": "[]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b4d", + "questionid": 130, + "title": "Shortest Palindrome", + "slug": "shortest-palindrome", + "description": "You are given a string s. You can convert s to a palindrome by adding characters in front of it. Return the shortest palindrome you can find by performing this transformation. ", + "category": [ + "String", + "Rolling Hash", + "String Matching", + "Hash Function" + ], + "complexity": "Hard", + "successrate": 31.7, + "totalsubmissions": 425047, + "totalaccepted": 134927, + "likes": 2322, + "dislikes": 187, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = \"aacecaaa\"", + "expected_output": "\"aaacecaaa\"", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "s = \"abcd\"", + "expected_output": "\"dcbabcd\"", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b4f", + "questionid": 132, + "title": "Contains Duplicate", + "slug": "contains-duplicate", + "description": "Given an integer array nums, return true if any value appears at least twice in the array, and return false if every element is distinct. ", + "category": [ + "Array", + "Hash Table", + "Sorting" + ], + "complexity": "Easy", + "successrate": 60.7, + "totalsubmissions": 2443511, + "totalaccepted": 1483087, + "likes": 4378, + "dislikes": 943, + "hints": "", + "deleted": false, + "examples": [] + }, + { + "_id": "66f925ddfdfb8e1665720b52", + "questionid": 135, + "title": "Maximal Square", + "slug": "maximal-square", + "description": "Given an m x n binary matrix filled with 0's and 1's, find the largest square containing only 1's and return its area. ", + "category": [ + "Array", + "Dynamic Programming", + "Matrix" + ], + "complexity": "Medium", + "successrate": 43.4, + "totalsubmissions": 1116716, + "totalaccepted": 484269, + "likes": 7011, + "dislikes": 145, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]]", + "expected_output": "4", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "matrix = [["0","1"],["1","0"]]", + "expected_output": "1", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "matrix = [["0"]]", + "expected_output": "0", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b59", + "questionid": 142, + "title": "Number of Digit One", + "slug": "number-of-digit-one", + "description": "Given an integer n, count the total number of digit 1 appearing in all non-negative integers less than or equal to n. ", + "category": [ + "Math", + "Dynamic Programming", + "Recursion" + ], + "complexity": "Hard", + "successrate": 33.5, + "totalsubmissions": 190665, + "totalaccepted": 63889, + "likes": 704, + "dislikes": 1022, + "hints": "Beware of overflow.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 13", + "expected_output": "6", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "n = 0", + "expected_output": "0", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b5a", + "questionid": 143, + "title": "Palindrome Linked List", + "slug": "palindrome-linked-list", + "description": "Given the head of a singly linked list, return true if it is a palindrome. ", + "category": [ + "Linked List", + "Two Pointers", + "Stack", + "Recursion" + ], + "complexity": "Easy", + "successrate": 46.5, + "totalsubmissions": 2014641, + "totalaccepted": 935997, + "likes": 8563, + "dislikes": 523, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "head = [1,2,2,1]", + "expected_output": "true", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "head = [1,2]", + "expected_output": "false", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b5d", + "questionid": 146, + "title": "Sliding Window Maximum", + "slug": "sliding-window-maximum", + "description": "You are given an array of integers nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position. Return the max sliding window. ", + "category": [ + "Array", + "Queue", + "Sliding Window", + "Heap (Priority Queue)", + "Monotonic Queue" + ], + "complexity": "Hard", + "successrate": 46.2, + "totalsubmissions": 1201410, + "totalaccepted": 554953, + "likes": 9485, + "dislikes": 337, + "hints": "How about using a data structure such as deque (double-ended queue)? The queue size need not be the same as the window€™s size. Remove redundant elements and the queue should store only elements that need to be considered.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,3,-1,-3,5,3,6,7], k = 3", + "expected_output": "[3,3,5,5,6,7]", + "explanation": "Window position Max\n--------------- -----\n[1 3 -1] -3 5 3 6 7 3\n 1 [3 -1 -3] 5 3 6 7 3\n 1 3 [-1 -3 5] 3 6 7 5\n 1 3 -1 [-3 5 3] 6 7 5\n 1 3 -1 -3 [5 3 6] 7 6\n 1 3 -1 -3 5 [3 6 7] 7" + }, + { + "example_num": 2, + "expected_input": "nums = [1], k = 1", + "expected_output": "[1]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b5e", + "questionid": 147, + "title": "Different Ways to Add Parentheses", + "slug": "different-ways-to-add-parentheses", + "description": "Given a string expression of numbers and operators, return all possible results from computing all the different possible ways to group numbers and operators. You may return the answer in any order. ", + "category": [ + "Math", + "String", + "Dynamic Programming", + "Recursion", + "Memoization" + ], + "complexity": "Medium", + "successrate": 61.5, + "totalsubmissions": 259836, + "totalaccepted": 159798, + "likes": 3513, + "dislikes": 171, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "expression = "2-1-1"", + "expected_output": "[0,2]", + "explanation": "((2-1)-1) = 0 \n(2-(1-1)) = 2" + }, + { + "example_num": 2, + "expected_input": "expression = "2*3-4*5"", + "expected_output": "[-34,-14,-10,-10,10]", + "explanation": "(2*(3-(4*5))) = -34 \n((2*3)-(4*5)) = -14 \n((2*(3-4))*5) = -10 \n(2*((3-4)*5)) = -10 \n(((2*3)-4)*5) = 10" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b5f", + "questionid": 148, + "title": "Valid Anagram", + "slug": "valid-anagram", + "description": "Given two strings s and t, return true if t is an anagram of s, and false otherwise. An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. ", + "category": [ + "Hash Table", + "String", + "Sorting" + ], + "complexity": "Easy", + "successrate": 61.4, + "totalsubmissions": 1961949, + "totalaccepted": 1203937, + "likes": 4620, + "dislikes": 209, + "hints": "", + "deleted": false, + "examples": [] + }, + { + "_id": "66f925ddfdfb8e1665720b61", + "questionid": 150, + "title": "Add Digits", + "slug": "add-digits", + "description": "Given an integer num, repeatedly add all its digits until the result has only one digit, and return it. ", + "category": [ + "Math", + "Simulation", + "Number Theory" + ], + "complexity": "Easy", + "successrate": 62.4, + "totalsubmissions": 743480, + "totalaccepted": 463936, + "likes": 2409, + "dislikes": 1642, + "hints": "A naive implementation of the above process is trivial. Could you come up with other methods? What are all the possible results? How do they occur, periodically or randomly? You may find this Wikipedia article useful.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "num = 38", + "expected_output": "2", + "explanation": "The process is\n38 --> 3 + 8 --> 11\n11 --> 1 + 1 --> 2 \nSince 2 has only one digit, return it." + }, + { + "example_num": 2, + "expected_input": "num = 0", + "expected_output": "0", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b6a", + "questionid": 159, + "title": "Move Zeroes", + "slug": "move-zeroes", + "description": "Given an integer array nums, move all 0's to the end of it while maintaining the relative order of the non-zero elements. Note that you must do this in-place without making a copy of the array. ", + "category": [ + "Array", + "Two Pointers" + ], + "complexity": "Easy", + "successrate": 60.6, + "totalsubmissions": 2674454, + "totalaccepted": 1619817, + "likes": 8830, + "dislikes": 239, + "hints": "In-place means we should not be allocating any space for extra array. But we are allowed to modify the existing array. However, as a first step, try coming up with a solution that makes use of additional space. For this problem as well, first apply the idea discussed using an additional array and the in-place solution will pop up eventually. A two-pointer approach could be helpful here. The idea would be to have one pointer for iterating the array and another pointer that just works on the non-zero elements of the array.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [0,1,0,3,12]", + "expected_output": "[1,3,12,0,0]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "nums = [0]", + "expected_output": "[0]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b6b", + "questionid": 160, + "title": "Find the Duplicate Number", + "slug": "find-the-duplicate-number", + "description": "Given an array of integers nums containing n + 1 integers where each integer is in the range [1, n] inclusive. There is only one repeated number in nums, return this repeated number. You must solve the problem without modifying the array nums and uses only constant extra space. ", + "category": [ + "Array", + "Two Pointers", + "Binary Search", + "Bit Manipulation" + ], + "complexity": "Medium", + "successrate": 58.8, + "totalsubmissions": 1384998, + "totalaccepted": 814172, + "likes": 13323, + "dislikes": 1514, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,3,4,2,2]", + "expected_output": "2", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "nums = [3,1,3,4,2]", + "expected_output": "3", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "nums = [3,3,3,3,3]", + "expected_output": "3", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b6d", + "questionid": 162, + "title": "Longest Increasing Subsequence", + "slug": "longest-increasing-subsequence", + "description": "Given an integer array nums, return the length of the longest strictly increasing subsequence. A subsequence is a sequence that can be derived from an array by deleting some or no elements without changing the order of the remaining elements. For example, [3,6,2,7] is a subsequence of the array [0,3,1,6,2,2,7]. ", + "category": [ + "Array", + "Binary Search", + "Dynamic Programming" + ], + "complexity": "Medium", + "successrate": 49.1, + "totalsubmissions": 1685924, + "totalaccepted": 827984, + "likes": 11472, + "dislikes": 227, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [10,9,2,5,3,7,101,18]", + "expected_output": "4", + "explanation": "The longest increasing subsequence is [2,3,7,101], therefore the length is 4." + }, + { + "example_num": 2, + "expected_input": "nums = [0,1,0,3,2,3]", + "expected_output": "4", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "nums = [7,7,7,7,7,7,7]", + "expected_output": "1", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b70", + "questionid": 165, + "title": "Burst Balloons", + "slug": "burst-balloons", + "description": "You are given n balloons, indexed from 0 to n - 1. Each balloon is painted with a number on it represented by an array nums. You are asked to burst all the balloons. If you burst the ith balloon, you will get nums[i - 1] * nums[i] * nums[i + 1] coins. If i - 1 or i + 1 goes out of bounds of the array, then treat it as if there is a balloon with a 1 painted on it. Return the maximum coins you can collect by bursting the balloons wisely. ", + "category": [ + "Array", + "Dynamic Programming" + ], + "complexity": "Hard", + "successrate": 56.3, + "totalsubmissions": 325121, + "totalaccepted": 182895, + "likes": 5795, + "dislikes": 157, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [3,1,5,8]", + "expected_output": "167", + "explanation": "nums = [3,1,5,8] --> [3,5,8] --> [3,8] --> [8] --> []\ncoins = 3*1*5 + 3*5*8 + 1*3*8 + 1*8*1 = 167" + }, + { + "example_num": 2, + "expected_input": "nums = [1,5]", + "expected_output": "10", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b71", + "questionid": 166, + "title": "Super Ugly Number", + "slug": "super-ugly-number", + "description": "A super ugly number is a positive integer whose prime factors are in the array primes. Given an integer n and an array of integers primes, return the nth super ugly number. The nth super ugly number is guaranteed to fit in a 32-bit signed integer. ", + "category": [ + "Array", + "Hash Table", + "Math", + "Dynamic Programming", + "Heap (Priority Queue)" + ], + "complexity": "Medium", + "successrate": 45.8, + "totalsubmissions": 226970, + "totalaccepted": 103863, + "likes": 1460, + "dislikes": 278, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 12, primes = [2,7,13,19]", + "expected_output": "32", + "explanation": "[1,2,4,7,8,13,14,16,19,26,28,32] is the sequence of the first 12 super ugly numbers given primes = [2,7,13,19]." + }, + { + "example_num": 2, + "expected_input": "n = 1, primes = [2,3,5]", + "expected_output": "1", + "explanation": "1 has no prime factors, therefore all of its prime factors are in the array primes = [2,3,5]." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b76", + "questionid": 171, + "title": "Create Maximum Number", + "slug": "create-maximum-number", + "description": "You are given two integer arrays nums1 and nums2 of lengths m and n respectively. nums1 and nums2 represent the digits of two numbers. You are also given an integer k. Create the maximum number of length k <= m + n from digits of the two numbers. The relative order of the digits from the same array must be preserved. Return an array of the k digits representing the answer. ", + "category": [ + "Stack", + "Greedy", + "Monotonic Stack" + ], + "complexity": "Hard", + "successrate": 28.4, + "totalsubmissions": 173497, + "totalaccepted": 49224, + "likes": 1323, + "dislikes": 307, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums1 = [3,4,6,5], nums2 = [9,1,2,5,8,3], k = 5", + "expected_output": "[9,8,6,5,3]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "nums1 = [6,7], nums2 = [6,0,4], k = 5", + "expected_output": "[6,7,6,0,4]", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "nums1 = [3,9], nums2 = [8,9], k = 3", + "expected_output": "[9,8,9]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b78", + "questionid": 173, + "title": "Wiggle Sort II", + "slug": "wiggle-sort-ii", + "description": "Given an integer array nums, reorder it such that nums[0] < nums[1] > nums[2] < nums[3].... You may assume the input array always has a valid answer. ", + "category": [ + "Array", + "Divide and Conquer", + "Sorting", + "Quickselect" + ], + "complexity": "Medium", + "successrate": 32.2, + "totalsubmissions": 372665, + "totalaccepted": 119965, + "likes": 2055, + "dislikes": 793, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,5,1,1,6,4]", + "expected_output": "[1,6,1,5,1,4]", + "explanation": "[1,4,1,5,1,6] is also accepted." + }, + { + "example_num": 2, + "expected_input": "nums = [1,3,2,2,3,1]", + "expected_output": "[2,3,1,3,1,2]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b79", + "questionid": 174, + "title": "Power of Three", + "slug": "power-of-three", + "description": "Given an integer n, return true if it is a power of three. Otherwise, return false. An integer n is a power of three, if there exists an integer x such that n == 3x. ", + "category": [ + "Math", + "Recursion" + ], + "complexity": "Easy", + "successrate": 43.4, + "totalsubmissions": 1046656, + "totalaccepted": 454534, + "likes": 902, + "dislikes": 118, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 27", + "expected_output": "true", + "explanation": "27 = 33" + }, + { + "example_num": 2, + "expected_input": "n = 0", + "expected_output": "false", + "explanation": "There is no x where 3x = 0." + }, + { + "example_num": 3, + "expected_input": "n = -1", + "expected_output": "false", + "explanation": "There is no x where 3x = (-1)." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b7b", + "questionid": 176, + "title": "Odd Even Linked List", + "slug": "odd-even-linked-list", + "description": "Given the head of a singly linked list, group all the nodes with odd indices together followed by the nodes with even indices, and return the reordered list. The first node is considered odd, and the second node is even, and so on. Note that the relative order inside both the even and odd groups should remain as it was in the input. You must solve the problem in O(1) extra space complexity and O(n) time complexity. ", + "category": [ + "Linked List" + ], + "complexity": "Medium", + "successrate": 59.5, + "totalsubmissions": 871544, + "totalaccepted": 518520, + "likes": 5183, + "dislikes": 383, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "head = [1,2,3,4,5]", + "expected_output": "[1,3,5,2,4]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "head = [2,1,3,5,6,4,7]", + "expected_output": "[2,3,6,7,1,5,4]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b7d", + "questionid": 178, + "title": "Reconstruct Itinerary", + "slug": "reconstruct-itinerary", + "description": "You are given a list of airline tickets where tickets[i] = [fromi, toi] represent the departure and the arrival airports of one flight. Reconstruct the itinerary in order and return it. All of the tickets belong to a man who departs from \"JFK\", thus, the itinerary must begin with \"JFK\". If there are multiple valid itineraries, you should return the itinerary that has the smallest lexical order when read as a single string. You may assume all tickets form at least one valid itinerary. You must use all the tickets once and only once. ", + "category": [ + "Depth-First Search", + "Graph", + "Eulerian Circuit" + ], + "complexity": "Hard", + "successrate": 40.1, + "totalsubmissions": 689553, + "totalaccepted": 276521, + "likes": 3766, + "dislikes": 1545, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "tickets = [["MUC","LHR"],["JFK","MUC"],["SFO","SJC"],["LHR","SFO"]]", + "expected_output": "["JFK","MUC","LHR","SFO","SJC"]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "tickets = [["JFK","SFO"],["JFK","ATL"],["SFO","ATL"],["ATL","JFK"],["ATL","SFO"]]", + "expected_output": "["JFK","ATL","JFK","SFO","ATL","SFO"]", + "explanation": "Another possible reconstruction is ["JFK","SFO","ATL","JFK","ATL","SFO"] but it is larger in lexical order." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b81", + "questionid": 182, + "title": "House Robber III", + "slug": "house-robber-iii", + "description": "The thief has found himself a new place for his thievery again. There is only one entrance to this area, called root. Besides the root, each house has one and only one parent house. After a tour, the smart thief realized that all houses in this place form a binary tree. It will automatically contact the police if two directly-linked houses were broken into on the same night. Given the root of the binary tree, return the maximum amount of money the thief can rob without alerting the police. ", + "category": [ + "Dynamic Programming", + "Tree", + "Depth-First Search", + "Binary Tree" + ], + "complexity": "Medium", + "successrate": 53.5, + "totalsubmissions": 528529, + "totalaccepted": 282635, + "likes": 6128, + "dislikes": 93, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [3,2,3,null,3,null,1]", + "expected_output": "7", + "explanation": "Maximum amount of money the thief can rob = 3 + 3 + 1 = 7." + }, + { + "example_num": 2, + "expected_input": "root = [3,4,5,1,3,null,1]", + "expected_output": "9", + "explanation": "Maximum amount of money the thief can rob = 4 + 5 = 9." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b84", + "questionid": 185, + "title": "Integer Break", + "slug": "integer-break", + "description": "Given an integer n, break it into the sum of k positive integers, where k >= 2, and maximize the product of those integers. Return the maximum product you can get. ", + "category": [ + "Math", + "Dynamic Programming" + ], + "complexity": "Medium", + "successrate": 54, + "totalsubmissions": 337951, + "totalaccepted": 182547, + "likes": 2696, + "dislikes": 324, + "hints": "There is a simple O(n) solution to this problem. You may check the breaking results of n ranging from 7 to 10 to discover the regularities.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 2", + "expected_output": "1", + "explanation": "2 = 1 + 1, 1 × 1 = 1." + }, + { + "example_num": 2, + "expected_input": "n = 10", + "expected_output": "36", + "explanation": "10 = 3 + 3 + 4, 3 × 3 × 4 = 36." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b89", + "questionid": 190, + "title": "Intersection of Two Arrays II", + "slug": "intersection-of-two-arrays-ii", + "description": "Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must appear as many times as it shows in both arrays and you may return the result in any order. ", + "category": [ + "Array", + "Hash Table", + "Two Pointers", + "Binary Search", + "Sorting" + ], + "complexity": "Easy", + "successrate": 54.8, + "totalsubmissions": 1412120, + "totalaccepted": 774103, + "likes": 4292, + "dislikes": 684, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums1 = [1,2,2,1], nums2 = [2,2]", + "expected_output": "[2,2]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "nums1 = [4,9,5], nums2 = [9,4,9,8,4]", + "expected_output": "[4,9]", + "explanation": "[9,4] is also accepted." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b8a", + "questionid": 191, + "title": "Count Numbers with Unique Digits", + "slug": "count-numbers-with-unique-digits", + "description": "Given an integer n, return the count of all numbers with unique digits, x, where 0 <= x < 10n. ", + "category": [ + "Math", + "Dynamic Programming", + "Backtracking" + ], + "complexity": "Medium", + "successrate": 50.6, + "totalsubmissions": 200530, + "totalaccepted": 101429, + "likes": 870, + "dislikes": 1223, + "hints": "A direct way is to use the backtracking approach. Backtracking should contains three states which are (the current number, number of steps to get that number and a bitmask which represent which number is marked as visited so far in the current number). Start with state (0,0,0) and count all valid number till we reach number of steps equals to 10n. This problem can also be solved using a dynamic programming approach and some knowledge of combinatorics. Let f(k) = count of numbers with unique digits with length equals k. f(1) = 10, ..., f(k) = 9 * 9 * 8 * ... (9 - k + 2) [The first factor is 9 because a number cannot start with 0].", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 2", + "expected_output": "91", + "explanation": "The answer should be the total numbers in the range of 0 ≤ x < 100, excluding 11,22,33,44,55,66,77,88,99" + }, + { + "example_num": 2, + "expected_input": "n = 0", + "expected_output": "1", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b8b", + "questionid": 192, + "title": "Max Sum of Rectangle No Larger Than K", + "slug": "max-sum-of-rectangle-no-larger-than-k", + "description": "Given an m x n matrix matrix and an integer k, return the max sum of a rectangle in the matrix such that its sum is no larger than k. It is guaranteed that there will be a rectangle with a sum no larger than k. ", + "category": [ + "Array", + "Binary Search", + "Dynamic Programming", + "Matrix", + "Ordered Set" + ], + "complexity": "Hard", + "successrate": 40.1, + "totalsubmissions": 195205, + "totalaccepted": 78325, + "likes": 1887, + "dislikes": 107, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "matrix = [[1,0,1],[0,-2,3]], k = 2", + "expected_output": "2", + "explanation": "Because the sum of the blue rectangle [[0, 1], [-2, 3]] is 2, and 2 is the max number no larger than k (k = 2)." + }, + { + "example_num": 2, + "expected_input": "matrix = [[2,2,-1]], k = 3", + "expected_output": "3", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b4e", + "questionid": 131, + "title": "Kth Largest Element in an Array", + "slug": "kth-largest-element-in-an-array", + "description": "Given an integer array nums and an integer k, return the kth largest element in the array. Note that it is the kth largest element in the sorted order, not the kth distinct element. ", + "category": [ + "Array", + "Divide and Conquer", + "Sorting", + "Heap (Priority Queue)", + "Quickselect" + ], + "complexity": "Medium", + "successrate": 63.3, + "totalsubmissions": 2021242, + "totalaccepted": 1279643, + "likes": 8917, + "dislikes": 480, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [3,2,1,5,6,4], k = 2", + "expected_output": "5", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "nums = [3,2,3,1,2,4,5,5,6], k = 4", + "expected_output": "4", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b51", + "questionid": 134, + "title": "Contains Duplicate III", + "slug": "contains-duplicate-iii", + "description": "Given an integer array nums and two integers k and t, return true if there are two distinct indices i and j in the array such that abs(nums[i] - nums[j]) <= t and abs(i - j) <= k. ", + "category": [ + "Array", + "Sliding Window", + "Sorting", + "Bucket Sort", + "Ordered Set" + ], + "complexity": "Medium", + "successrate": 21.7, + "totalsubmissions": 920049, + "totalaccepted": 199738, + "likes": 2264, + "dislikes": 2212, + "hints": "Time complexity O(n logk) - This will give an indication that sorting is involved for k elements. Use already existing state to evaluate next state - Like, a set of k sorted numbers are only needed to be tracked. When we are processing the next number in array, then we can utilize the existing sorted state and it is not necessary to sort next overlapping set of k numbers again.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,2,3,1], indexDiff = 3, valueDiff = 0", + "expected_output": "true", + "explanation": "We can choose (i, j) = (0, 3).\nWe satisfy the three conditions:\ni != j --> 0 != 3\nabs(i - j) <= indexDiff --> abs(0 - 3) <= 3\nabs(nums[i] - nums[j]) <= valueDiff --> abs(1 - 1) <= 0" + }, + { + "example_num": 2, + "expected_input": "nums = [1,5,9,1,5,9], indexDiff = 2, valueDiff = 3", + "expected_output": "false", + "explanation": "After trying all the possible pairs (i, j), we cannot satisfy the three conditions, so we return false." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b57", + "questionid": 140, + "title": "Kth Smallest Element in a BST", + "slug": "kth-smallest-element-in-a-bst", + "description": "Given the root of a binary search tree, and an integer k, return the kth smallest value (1-indexed) of all the values of the nodes in the tree. ", + "category": [ + "Tree", + "Depth-First Search", + "Binary Search Tree", + "Binary Tree" + ], + "complexity": "Medium", + "successrate": 66.6, + "totalsubmissions": 1100066, + "totalaccepted": 732943, + "likes": 6137, + "dislikes": 123, + "hints": "Try to utilize the property of a BST. Try in-order traversal. (Credits to @chan13) What if you could modify the BST node's structure? The optimal runtime complexity is O(height of BST).", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [3,1,4,null,2], k = 1", + "expected_output": "1", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "root = [5,3,6,2,4,null,null,1], k = 3", + "expected_output": "3", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b58", + "questionid": 141, + "title": "Power of Two", + "slug": "power-of-two", + "description": "Given an integer n, return true if it is a power of two. Otherwise, return false. An integer n is a power of two, if there exists an integer x such that n == 2x. ", + "category": [ + "Math", + "Bit Manipulation", + "Recursion" + ], + "complexity": "Easy", + "successrate": 44.9, + "totalsubmissions": 1354147, + "totalaccepted": 608583, + "likes": 3100, + "dislikes": 288, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 1", + "expected_output": "true\nExplanation: 20 = 1", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "n = 16", + "expected_output": "true\nExplanation: 24 = 16", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "n = 3", + "expected_output": "false", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b5c", + "questionid": 145, + "title": "Product of Array Except Self", + "slug": "product-of-array-except-self", + "description": "Given an integer array nums, return an array answer such that answer[i] is equal to the product of all the elements of nums except nums[i]. The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer. You must write an algorithm that runs in O(n) time and without using the division operation. ", + "category": [ + "Array", + "Prefix Sum" + ], + "complexity": "Medium", + "successrate": 63.9, + "totalsubmissions": 1754180, + "totalaccepted": 1120129, + "likes": 11850, + "dislikes": 724, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,2,3,4]", + "expected_output": "[24,12,8,6]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "nums = [-1,1,0,-3,3]", + "expected_output": "[0,0,9,0,0]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b62", + "questionid": 151, + "title": "Single Number III", + "slug": "single-number-iii", + "description": "Given an integer array nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once. You can return the answer in any order. You must write an algorithm that runs in linear runtime complexity and uses only constant extra space. ", + "category": [ + "Array", + "Bit Manipulation" + ], + "complexity": "Medium", + "successrate": 67.1, + "totalsubmissions": 372615, + "totalaccepted": 250144, + "likes": 3806, + "dislikes": 182, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,2,1,3,2,5]", + "expected_output": "[3,5]\nExplanation: [5, 3] is also a valid answer.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "nums = [-1,0]", + "expected_output": "[-1,0]", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "nums = [0,1]", + "expected_output": "[1,0]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b64", + "questionid": 153, + "title": "Ugly Number II", + "slug": "ugly-number-ii", + "description": "An ugly number is a positive integer whose prime factors are limited to 2, 3, and 5. Given an integer n, return the nth ugly number. ", + "category": [ + "Hash Table", + "Math", + "Dynamic Programming", + "Heap (Priority Queue)" + ], + "complexity": "Medium", + "successrate": 45.2, + "totalsubmissions": 563935, + "totalaccepted": 254942, + "likes": 3941, + "dislikes": 210, + "hints": "The naive approach is to call isUgly for every number until you reach the nth one. Most numbers are not ugly. Try to focus your effort on generating only the ugly ones. An ugly number must be multiplied by either 2, 3, or 5 from a smaller ugly number. The key is how to maintain the order of the ugly numbers. Try a similar approach of merging from three sorted lists: L1, L2, and L3. Assume you have Uk, the kth ugly number. Then Uk+1 must be Min(L1 * 2, L2 * 3, L3 * 5).", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 10", + "expected_output": "12", + "explanation": "[1, 2, 3, 4, 5, 6, 8, 9, 10, 12] is the sequence of the first 10 ugly numbers." + }, + { + "example_num": 2, + "expected_input": "n = 1", + "expected_output": "1", + "explanation": "1 has no prime factors, therefore all of its prime factors are limited to 2, 3, and 5." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b67", + "questionid": 156, + "title": "First Bad Version", + "slug": "first-bad-version", + "description": "You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad. Suppose you have n versions [1, 2, ..., n] and you want to find out the first bad one, which causes all the following ones to be bad. You are given an API bool isBadVersion(version) which returns whether version is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API. ", + "category": [ + "Binary Search", + "Interactive" + ], + "complexity": "Easy", + "successrate": 41.5, + "totalsubmissions": 2305289, + "totalaccepted": 956971, + "likes": 4654, + "dislikes": 1743, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 5, bad = 4", + "expected_output": "4", + "explanation": "call isBadVersion(3) -> false\ncall isBadVersion(5) -> true\ncall isBadVersion(4) -> true\nThen 4 is the first bad version." + }, + { + "example_num": 2, + "expected_input": "n = 1, bad = 1", + "expected_output": "1", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b6e", + "questionid": 163, + "title": "Remove Invalid Parentheses", + "slug": "remove-invalid-parentheses", + "description": "Given a string s that contains parentheses and letters, remove the minimum number of invalid parentheses to make the input string valid. Return all the possible results. You may return the answer in any order. ", + "category": [ + "String", + "Backtracking", + "Breadth-First Search" + ], + "complexity": "Hard", + "successrate": 46.8, + "totalsubmissions": 735686, + "totalaccepted": 344520, + "likes": 4569, + "dislikes": 233, + "hints": "Since we don't know which of the brackets can possibly be removed, we try out all the options! We can use recursion to try out all possibilities for the given expression. For each of the brackets, we have 2 options:\r\n\r\n\n We keep the bracket and add it to the expression that we are building on the fly during recursion.\n OR, we can discard the bracket and move on. The one thing all these valid expressions have in common is that they will all be of the same length i.e. as compared to the original expression, all of these expressions will have the same number of characters removed. \r\n\r\nCan we somehow find the number of misplaced parentheses and use it in our solution? For every left parenthesis, we should have a corresponding right parenthesis. We can make use of two counters which keep track of misplaced left and right parenthesis and in one iteration we can find out these two values. \r\n\r\n\r\n0 1 2 3 4 5 6 7\r\n( ) ) ) ( ( ( ) \r\ni = 0, left = 1, right = 0\r\ni = 1, left = 0, right = 0\r\ni = 2, left = 0, right = 1\r\ni = 3, left = 0, right = 2\r\ni = 4, left = 1, right = 2\r\ni = 5, left = 2, right = 2\r\ni = 6, left = 3, right = 2\r\ni = 7, left = 2, right = 2\r\n\r\n\r\nWe have 2 misplaced left and 2 misplaced right parentheses. We found out that the exact number of left and right parenthesis that has to be removed to get a valid expression. So, e.g. in a 1000 parentheses string, if there are 2 misplaced left and 2 misplaced right parentheses, after we are done discarding 2 left and 2 right parentheses, we will have only one option per remaining character in the expression i.e. to consider them. We can't discard them.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "()())()"", + "expected_output": "["(())()","()()()"]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "s = "(a)())()"", + "expected_output": "["(a())()","(a)()()"]", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "s = ")("", + "expected_output": "[""]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b74", + "questionid": 169, + "title": "Maximum Product of Word Lengths", + "slug": "maximum-product-of-word-lengths", + "description": "Given a string array words, return the maximum value of length(word[i]) * length(word[j]) where the two words do not share common letters. If no such two words exist, return 0. ", + "category": [ + "Array", + "String", + "Bit Manipulation" + ], + "complexity": "Medium", + "successrate": 56.6, + "totalsubmissions": 251492, + "totalaccepted": 142365, + "likes": 1700, + "dislikes": 94, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "words = ["abcw","baz","foo","bar","xtfn","abcdef"]", + "expected_output": "16", + "explanation": "The two words can be "abcw", "xtfn"." + }, + { + "example_num": 2, + "expected_input": "words = ["a","ab","abc","d","cd","bcd","abcd"]", + "expected_output": "4", + "explanation": "The two words can be "ab", "cd"." + }, + { + "example_num": 3, + "expected_input": "words = ["a","aa","aaa","aaaa"]", + "expected_output": "0", + "explanation": "No such pair of words." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b80", + "questionid": 181, + "title": "Palindrome Pairs", + "slug": "palindrome-pairs", + "description": "Given a list of unique words, return all the pairs of the distinct indices (i, j) in the given list, so that the concatenation of the two words words[i] + words[j] is a palindrome. ", + "category": [ + "Array", + "Hash Table", + "String", + "Trie" + ], + "complexity": "Hard", + "successrate": 35.9, + "totalsubmissions": 409115, + "totalaccepted": 146725, + "likes": 2618, + "dislikes": 244, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "words = ["abcd","dcba","lls","s","sssll"]", + "expected_output": "[[0,1],[1,0],[3,2],[2,4]]", + "explanation": "The palindromes are ["abcddcba","dcbaabcd","slls","llssssll"]" + }, + { + "example_num": 2, + "expected_input": "words = ["bat","tab","cat"]", + "expected_output": "[[0,1],[1,0]]", + "explanation": "The palindromes are ["battab","tabbat"]" + }, + { + "example_num": 3, + "expected_input": "words = ["a",""]", + "expected_output": "[[0,1],[1,0]]", + "explanation": "The palindromes are ["a","a"]" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b82", + "questionid": 183, + "title": "Counting Bits", + "slug": "counting-bits", + "description": "Given an integer n, return an array ans of length n + 1 such that for each i (0 <= i <= n), ans[i] is the number of 1's in the binary representation of i. ", + "category": [ + "Dynamic Programming", + "Bit Manipulation" + ], + "complexity": "Easy", + "successrate": 74.2, + "totalsubmissions": 759000, + "totalaccepted": 563251, + "likes": 6774, + "dislikes": 317, + "hints": "You should make use of what you have produced already. Divide the numbers in ranges like [2-3], [4-7], [8-15] and so on. And try to generate new range from previous. Or does the odd/even status of the number help you in calculating the number of 1s?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 2", + "expected_output": "[0,1,1]", + "explanation": "0 --> 0\n1 --> 1\n2 --> 10" + }, + { + "example_num": 2, + "expected_input": "n = 5", + "expected_output": "[0,1,1,2,1,2]", + "explanation": "0 --> 0\n1 --> 1\n2 --> 10\n3 --> 11\n4 --> 100\n5 --> 101" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b83", + "questionid": 184, + "title": "Power of Four", + "slug": "power-of-four", + "description": "Given an integer n, return true if it is a power of four. Otherwise, return false. An integer n is a power of four, if there exists an integer x such that n == 4x. ", + "category": [ + "Math", + "Bit Manipulation", + "Recursion" + ], + "complexity": "Easy", + "successrate": 43.9, + "totalsubmissions": 663170, + "totalaccepted": 291168, + "likes": 1445, + "dislikes": 285, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 16", + "expected_output": "true", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "n = 5", + "expected_output": "false", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "n = 1", + "expected_output": "true", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b85", + "questionid": 186, + "title": "Reverse String", + "slug": "reverse-string", + "description": "Write a function that reverses a string. The input string is given as an array of characters s. You must do this by modifying the input array in-place with O(1) extra memory. ", + "category": [ + "Two Pointers", + "String", + "Recursion" + ], + "complexity": "Easy", + "successrate": 74.7, + "totalsubmissions": 2078623, + "totalaccepted": 1553675, + "likes": 4831, + "dislikes": 937, + "hints": "The entire logic for reversing a string is based on using the opposite directional two-pointer approach!", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = [\"h\",\"e\",\"l\",\"l\",\"o\"]", + "expected_output": "[\"o\",\"l\",\"l\",\"e\",\"h\"]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "s = [\"H\",\"a\",\"n\",\"n\",\"a\",\"h\"]", + "expected_output": "[\"h\",\"a\",\"n\",\"n\",\"a\",\"H\"]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b86", + "questionid": 187, + "title": "Reverse Vowels of a String", + "slug": "reverse-vowels-of-a-string", + "description": "Given a string s, reverse only all the vowels in the string and return it. The vowels are 'a', 'e', 'i', 'o', and 'u', and they can appear in both cases. ", + "category": [ + "Two Pointers", + "String" + ], + "complexity": "Easy", + "successrate": 46.9, + "totalsubmissions": 737331, + "totalaccepted": 345831, + "likes": 1560, + "dislikes": 1823, + "hints": "", + "deleted": false, + "examples": [] + }, + { + "_id": "66f925ddfdfb8e1665720b87", + "questionid": 188, + "title": "Top K Frequent Elements", + "slug": "top-k-frequent-elements", + "description": "Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order. ", + "category": [ + "Array", + "Hash Table", + "Divide and Conquer", + "Sorting", + "Heap (Priority Queue)", + "Bucket Sort", + "Counting", + "Quickselect" + ], + "complexity": "Medium", + "successrate": 65.1, + "totalsubmissions": 1418616, + "totalaccepted": 923599, + "likes": 8858, + "dislikes": 360, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,1,1,2,2,3], k = 2", + "expected_output": "[1,2]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "nums = [1], k = 1", + "expected_output": "[1]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b4c", + "questionid": 129, + "title": "House Robber II", + "slug": "house-robber-ii", + "description": "You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed. All houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, adjacent houses have a security system connected, and it will automatically contact the police if two adjacent houses were broken into on the same night. Given an integer array nums representing the amount of money of each house, return the maximum amount of money you can rob tonight without alerting the police. ", + "category": [ + "Array", + "Dynamic Programming" + ], + "complexity": "Medium", + "successrate": 39.8, + "totalsubmissions": 960606, + "totalaccepted": 382370, + "likes": 5261, + "dislikes": 91, + "hints": "Since House[1] and House[n] are adjacent, they cannot be robbed together. Therefore, the problem becomes to rob either House[1]-House[n-1] or House[2]-House[n], depending on which choice offers more money. Now the problem has degenerated to the House Robber, which is already been solved.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [2,3,2]", + "expected_output": "3", + "explanation": "You cannot rob house 1 (money = 2) and then rob house 3 (money = 2), because they are adjacent houses." + }, + { + "example_num": 2, + "expected_input": "nums = [1,2,3,1]", + "expected_output": "4", + "explanation": "Rob house 1 (money = 1) and then rob house 3 (money = 3).\nTotal amount you can rob = 1 + 3 = 4." + }, + { + "example_num": 3, + "expected_input": "nums = [1,2,3]", + "expected_output": "3", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b53", + "questionid": 136, + "title": "Count Complete Tree Nodes", + "slug": "count-complete-tree-nodes", + "description": "Given the root of a complete binary tree, return the number of the nodes in the tree. According to Wikipedia, every level, except possibly the last, is completely filled in a complete binary tree, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h. Design an algorithm that runs in less than O(n) time complexity. ", + "category": [ + "Binary Search", + "Tree", + "Depth-First Search", + "Binary Tree" + ], + "complexity": "Medium", + "successrate": 55.1, + "totalsubmissions": 719342, + "totalaccepted": 396136, + "likes": 4722, + "dislikes": 312, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [1,2,3,4,5,6]", + "expected_output": "6", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "root = []", + "expected_output": "0", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "root = [1]", + "expected_output": "1", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b56", + "questionid": 139, + "title": "Majority Element II", + "slug": "majority-element-ii", + "description": "Given an integer array of size n, find all elements that appear more than n/3 times. ", + "category": [ + "Array", + "Hash Table", + "Sorting", + "Counting" + ], + "complexity": "Medium", + "successrate": 42.2, + "totalsubmissions": 667653, + "totalaccepted": 282018, + "likes": 4680, + "dislikes": 277, + "hints": "How many majority elements could it possibly have?\r\n\r\nDo you have a better hint? Suggest it!", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [3,2,3]", + "expected_output": "[3]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "nums = [1]", + "expected_output": "[1]", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "nums = [1,2]", + "expected_output": "[1,2]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b65", + "questionid": 154, + "title": "Missing Number", + "slug": "missing-number", + "description": "Given an array nums containing n distinct numbers in the range [0, n], return the only number in the range that is missing from the array. ", + "category": [ + "Array", + "Hash Table", + "Math", + "Bit Manipulation", + "Sorting" + ], + "complexity": "Easy", + "successrate": 59.3, + "totalsubmissions": 1649957, + "totalaccepted": 977912, + "likes": 5317, + "dislikes": 2830, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [3,0,1]", + "expected_output": "2", + "explanation": "n = 3 since there are 3 numbers, so all numbers are in the range [0,3]. 2 is the missing number in the range since it does not appear in nums." + }, + { + "example_num": 2, + "expected_input": "nums = [0,1]", + "expected_output": "2", + "explanation": "n = 2 since there are 2 numbers, so all numbers are in the range [0,2]. 2 is the missing number in the range since it does not appear in nums." + }, + { + "example_num": 3, + "expected_input": "nums = [9,6,4,2,3,5,7,0,1]", + "expected_output": "8", + "explanation": "n = 9 since there are 9 numbers, so all numbers are in the range [0,9]. 8 is the missing number in the range since it does not appear in nums." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b66", + "questionid": 155, + "title": "Integer to English Words", + "slug": "integer-to-english-words", + "description": "Convert a non-negative integer num to its English words representation. ", + "category": [ + "Math", + "String", + "Recursion" + ], + "complexity": "Hard", + "successrate": 29.6, + "totalsubmissions": 1008214, + "totalaccepted": 298067, + "likes": 2025, + "dislikes": 4942, + "hints": "Did you see a pattern in dividing the number into chunk of words? For example, 123 and 123000. Group the number by thousands (3 digits). You can write a helper function that takes a number less than 1000 and convert just that chunk to words. There are many edge cases. What are some good test cases? Does your code work with input such as 0? Or 1000010? (middle chunk is zero and should not be printed out)", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "num = 123", + "expected_output": ""One Hundred Twenty Three"", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "num = 12345", + "expected_output": ""Twelve Thousand Three Hundred Forty Five"", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "num = 1234567", + "expected_output": ""One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b6f", + "questionid": 164, + "title": "Minimum Height Trees", + "slug": "minimum-height-trees", + "description": "A tree is an undirected graph in which any two vertices are connected by exactly one path. In other words, any connected graph without simple cycles is a tree. Given a tree of n nodes labelled from 0 to n - 1, and an array of n - 1 edges where edges[i] = [ai, bi] indicates that there is an undirected edge between the two nodes ai and bi in the tree, you can choose any node of the tree as the root. When you select a node x as the root, the result tree has height h. Among all possible rooted trees, those with minimum height (i.e. min(h))  are called minimum height trees (MHTs). Return a list of all MHTs' root labels. You can return the answer in any order. The height of a rooted tree is the number of edges on the longest downward path between the root and a leaf. ", + "category": [ + "Depth-First Search", + "Breadth-First Search", + "Graph", + "Topological Sort" + ], + "complexity": "Medium", + "successrate": 38.1, + "totalsubmissions": 507493, + "totalaccepted": 193328, + "likes": 5092, + "dislikes": 210, + "hints": "How many MHTs can a graph have at most?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 4, edges = [[1,0],[1,2],[1,3]]", + "expected_output": "[1]", + "explanation": "As shown, the height of the tree is 1 when the root is the node with label 1 which is the only MHT." + }, + { + "example_num": 2, + "expected_input": "n = 6, edges = [[3,0],[3,1],[3,2],[3,4],[5,4]]", + "expected_output": "[3,4]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b73", + "questionid": 168, + "title": "Remove Duplicate Letters", + "slug": "remove-duplicate-letters", + "description": "Given a string s, remove duplicate letters so that every letter appears once and only once. You must make sure your result is the smallest in lexicographical order among all possible results. ", + "category": [ + "String", + "Stack", + "Greedy", + "Monotonic Stack" + ], + "complexity": "Medium", + "successrate": 43.8, + "totalsubmissions": 432267, + "totalaccepted": 189513, + "likes": 5181, + "dislikes": 340, + "hints": "Greedily try to add one missing character. How to check if adding some character will not cause problems ? Use bit-masks to check whether you will be able to complete the sub-sequence if you add the character at some index i.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "bcabc"", + "expected_output": ""abc"", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "s = "cbacdcbc"", + "expected_output": ""acdb"", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b75", + "questionid": 170, + "title": "Bulb Switcher", + "slug": "bulb-switcher", + "description": "There are n bulbs that are initially off. You first turn on all the bulbs, then you turn off every second bulb. On the third round, you toggle every third bulb (turning on if it's off or turning off if it's on). For the ith round, you toggle every i bulb. For the nth round, you only toggle the last bulb. Return the number of bulbs that are on after n rounds. ", + "category": [ + "Math", + "Brainteaser" + ], + "complexity": "Medium", + "successrate": 47.2, + "totalsubmissions": 239996, + "totalaccepted": 113307, + "likes": 907, + "dislikes": 1636, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 3", + "expected_output": "1", + "explanation": "At first, the three bulbs are [off, off, off].\nAfter the first round, the three bulbs are [on, on, on].\nAfter the second round, the three bulbs are [on, off, on].\nAfter the third round, the three bulbs are [on, off, off]. \nSo you should return 1 because there is only one bulb is on." + }, + { + "example_num": 2, + "expected_input": "n = 0", + "expected_output": "0", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "n = 1", + "expected_output": "1", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b7f", + "questionid": 180, + "title": "Self Crossing", + "slug": "self-crossing", + "description": "You are given an array of integers distance. You start at point (0,0) on an X-Y plane and you move distance[0] meters to the north, then distance[1] meters to the west, distance[2] meters to the south, distance[3] meters to the east, and so on. In other words, after each move, your direction changes counter-clockwise. Return true if your path crosses itself, and false if it does not. ", + "category": [ + "Array", + "Math", + "Geometry" + ], + "complexity": "Hard", + "successrate": 29.1, + "totalsubmissions": 94557, + "totalaccepted": 27512, + "likes": 249, + "dislikes": 444, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "distance = [2,1,1,2]", + "expected_output": "true", + "explanation": "The path crosses itself at the point (0, 1)." + }, + { + "example_num": 2, + "expected_input": "distance = [1,2,3,4]", + "expected_output": "false", + "explanation": "The path does not cross itself at any point." + }, + { + "example_num": 3, + "expected_input": "distance = [1,1,1,2,1]", + "expected_output": "true", + "explanation": "The path crosses itself at the point (0, 0)." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b88", + "questionid": 189, + "title": "Intersection of Two Arrays", + "slug": "intersection-of-two-arrays", + "description": "Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must be unique and you may return the result in any order. ", + "category": [ + "Array", + "Hash Table", + "Two Pointers", + "Binary Search", + "Sorting" + ], + "complexity": "Easy", + "successrate": 68.9, + "totalsubmissions": 939599, + "totalaccepted": 647468, + "likes": 2731, + "dislikes": 1878, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums1 = [1,2,2,1], nums2 = [2,2]", + "expected_output": "[2]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "nums1 = [4,9,5], nums2 = [9,4,9,8,4]", + "expected_output": "[9,4]", + "explanation": "[4,9] is also accepted." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b50", + "questionid": 133, + "title": "Contains Duplicate II", + "slug": "contains-duplicate-ii", + "description": "Given an integer array nums and an integer k, return true if there are two distinct indices i and j in the array such that nums[i] == nums[j] and abs(i - j) <= k. ", + "category": [ + "Array", + "Hash Table", + "Sliding Window" + ], + "complexity": "Easy", + "successrate": 40.6, + "totalsubmissions": 1107769, + "totalaccepted": 450207, + "likes": 2368, + "dislikes": 1847, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,2,3,1], k = 3", + "expected_output": "true", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "nums = [1,0,1,1], k = 1", + "expected_output": "true", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "nums = [1,2,3,1,2,3], k = 2", + "expected_output": "false", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b54", + "questionid": 137, + "title": "Rectangle Area", + "slug": "rectangle-area", + "description": "Given the coordinates of two rectilinear rectangles in a 2D plane, return the total area covered by the two rectangles. The first rectangle is defined by its bottom-left corner (ax1, ay1) and its top-right corner (ax2, ay2). The second rectangle is defined by its bottom-left corner (bx1, by1) and its top-right corner (bx2, by2). ", + "category": [ + "Math", + "Geometry" + ], + "complexity": "Medium", + "successrate": 40.1, + "totalsubmissions": 337644, + "totalaccepted": 135232, + "likes": 745, + "dislikes": 1008, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "ax1 = -3, ay1 = 0, ax2 = 3, ay2 = 4, bx1 = 0, by1 = -1, bx2 = 9, by2 = 2", + "expected_output": "45", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "ax1 = -2, ay1 = -2, ax2 = 2, ay2 = 2, bx1 = -2, by1 = -2, bx2 = 2, by2 = 2", + "expected_output": "16", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b55", + "questionid": 138, + "title": "Invert Binary Tree", + "slug": "invert-binary-tree", + "description": "Given the root of a binary tree, invert the tree, and return its root. ", + "category": [ + "Tree", + "Depth-First Search", + "Breadth-First Search", + "Binary Tree" + ], + "complexity": "Easy", + "successrate": 71.4, + "totalsubmissions": 1394634, + "totalaccepted": 995662, + "likes": 8061, + "dislikes": 110, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [4,2,7,1,3,6,9]", + "expected_output": "[4,7,2,9,6,3,1]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "root = [2,1,3]", + "expected_output": "[2,3,1]", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "root = []", + "expected_output": "[]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b5b", + "questionid": 144, + "title": "Delete Node in a Linked List", + "slug": "delete-node-in-a-linked-list", + "description": "Write a function to delete a node in a singly-linked list. You will not be given access to the head of the list, instead you will be given access to the node to be deleted directly. It is guaranteed that the node to be deleted is not a tail node in the list. ", + "category": [ + "Linked List" + ], + "complexity": "Easy", + "successrate": 71.7, + "totalsubmissions": 1093877, + "totalaccepted": 784762, + "likes": 4258, + "dislikes": 11520, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "head = [4,5,1,9], node = 5", + "expected_output": "[4,1,9]\nExplanation: You are given the second node with value 5, the linked list should become 4 -> 1 -> 9 after calling your function.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "head = [4,5,1,9], node = 1", + "expected_output": "[4,5,9]\nExplanation: You are given the third node with value 1, the linked list should become 4 -> 5 -> 9 after calling your function.", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b60", + "questionid": 149, + "title": "Binary Tree Paths", + "slug": "binary-tree-paths", + "description": "Given the root of a binary tree, return all root-to-leaf paths in any order. A leaf is a node with no children. ", + "category": [ + "String", + "Backtracking", + "Tree", + "Depth-First Search", + "Binary Tree" + ], + "complexity": "Easy", + "successrate": 58.5, + "totalsubmissions": 857207, + "totalaccepted": 501173, + "likes": 3949, + "dislikes": 181, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [1,2,3,null,5]", + "expected_output": "["1->2->5","1->3"]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "root = [1]", + "expected_output": "["1"]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b63", + "questionid": 152, + "title": "Ugly Number", + "slug": "ugly-number", + "description": "An ugly number is a positive integer whose prime factors are limited to 2, 3, and 5. Given an integer n, return true if n is an ugly number. ", + "category": [ + "Math" + ], + "complexity": "Easy", + "successrate": 41.8, + "totalsubmissions": 699108, + "totalaccepted": 292500, + "likes": 1376, + "dislikes": 1018, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 6", + "expected_output": "true", + "explanation": "6 = 2 × 3" + }, + { + "example_num": 2, + "expected_input": "n = 1", + "expected_output": "true", + "explanation": "1 has no prime factors, therefore all of its prime factors are limited to 2, 3, and 5." + }, + { + "example_num": 3, + "expected_input": "n = 14", + "expected_output": "false", + "explanation": "14 is not ugly since it includes the prime factor 7." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b68", + "questionid": 157, + "title": "Perfect Squares", + "slug": "perfect-squares", + "description": "Given an integer n, return the least number of perfect square numbers that sum to n. A perfect square is an integer that is the square of an integer; in other words, it is the product of some integer with itself. For example, 1, 4, 9, and 16 are perfect squares while 3 and 11 are not. ", + "category": [ + "Math", + "Dynamic Programming", + "Breadth-First Search" + ], + "complexity": "Medium", + "successrate": 51.8, + "totalsubmissions": 1002301, + "totalaccepted": 519105, + "likes": 6581, + "dislikes": 291, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 12", + "expected_output": "3", + "explanation": "12 = 4 + 4 + 4." + }, + { + "example_num": 2, + "expected_input": "n = 13", + "expected_output": "2", + "explanation": "13 = 4 + 9." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b69", + "questionid": 158, + "title": "Expression Add Operators", + "slug": "expression-add-operators", + "description": "Given a string num that contains only digits and an integer target, return all possibilities to insert the binary operators '+', '-', and/or '*' between the digits of num so that the resultant expression evaluates to the target value. Note that operands in the returned expressions should not contain leading zeros. ", + "category": [ + "Math", + "String", + "Backtracking" + ], + "complexity": "Hard", + "successrate": 39.2, + "totalsubmissions": 460309, + "totalaccepted": 180213, + "likes": 2475, + "dislikes": 420, + "hints": "Note that a number can contain multiple digits. Since the question asks us to find all of the valid expressions, we need a way to iterate over all of them. (Hint: Recursion!) We can keep track of the expression string and evaluate it at the very end. But that would take a lot of time. Can we keep track of the expression's value as well so as to avoid the evaluation at the very end of recursion? Think carefully about the multiply operator. It has a higher precedence than the addition and subtraction operators. \r\n\r\n 1 + 2 = 3 \r\n1 + 2 - 4 --> 3 - 4 --> -1 \r\n1 + 2 - 4 * 12 --> -1 * 12 --> -12 (WRONG!) \r\n1 + 2 - 4 * 12 --> -1 - (-4) + (-4 * 12) --> 3 + (-48) --> -45 (CORRECT!) We simply need to keep track of the last operand in our expression and reverse it's effect on the expression's value while considering the multiply operator.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "num = "123", target = 6", + "expected_output": "["1*2*3","1+2+3"]", + "explanation": "Both "1*2*3" and "1+2+3" evaluate to 6." + }, + { + "example_num": 2, + "expected_input": "num = "232", target = 8", + "expected_output": "["2*3+2","2+3*2"]", + "explanation": "Both "2*3+2" and "2+3*2" evaluate to 8." + }, + { + "example_num": 3, + "expected_input": "num = "3456237490", target = 9191", + "expected_output": "[]", + "explanation": "There are no expressions that can be created from "3456237490" to evaluate to 9191." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b6c", + "questionid": 161, + "title": "Word Pattern", + "slug": "word-pattern", + "description": "Given a pattern and a string s, find if s follows the same pattern. Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in s. ", + "category": [ + "Hash Table", + "String" + ], + "complexity": "Easy", + "successrate": 40.2, + "totalsubmissions": 886230, + "totalaccepted": 356008, + "likes": 3477, + "dislikes": 402, + "hints": "", + "deleted": false, + "examples": [] + }, + { + "_id": "66f925ddfdfb8e1665720b72", + "questionid": 167, + "title": "Count of Smaller Numbers After Self", + "slug": "count-of-smaller-numbers-after-self", + "description": "You are given an integer array nums and you have to return a new counts array. The counts array has the property where counts[i] is the number of smaller elements to the right of nums[i]. ", + "category": [ + "Array", + "Binary Search", + "Divide and Conquer", + "Binary Indexed Tree", + "Segment Tree", + "Merge Sort", + "Ordered Set" + ], + "complexity": "Hard", + "successrate": 42, + "totalsubmissions": 531794, + "totalaccepted": 223619, + "likes": 5393, + "dislikes": 154, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [5,2,6,1]", + "expected_output": "[2,1,1,0]", + "explanation": "To the right of 5 there are 2 smaller elements (2 and 1).\nTo the right of 2 there is only 1 smaller element (1).\nTo the right of 6 there is 1 smaller element (1).\nTo the right of 1 there is 0 smaller element." + }, + { + "example_num": 2, + "expected_input": "nums = [-1]", + "expected_output": "[0]", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "nums = [-1,-1]", + "expected_output": "[0,0]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b77", + "questionid": 172, + "title": "Coin Change", + "slug": "coin-change", + "description": "You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money. Return the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1. You may assume that you have an infinite number of each kind of coin. ", + "category": [ + "Array", + "Dynamic Programming", + "Breadth-First Search" + ], + "complexity": "Medium", + "successrate": 40, + "totalsubmissions": 2373497, + "totalaccepted": 950323, + "likes": 10775, + "dislikes": 262, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "coins = [1,2,5], amount = 11", + "expected_output": "3", + "explanation": "11 = 5 + 5 + 1" + }, + { + "example_num": 2, + "expected_input": "coins = [2], amount = 3", + "expected_output": "-1", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "coins = [1], amount = 0", + "expected_output": "0", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b7a", + "questionid": 175, + "title": "Count of Range Sum", + "slug": "count-of-range-sum", + "description": "Given an integer array nums and two integers lower and upper, return the number of range sums that lie in [lower, upper] inclusive. Range sum S(i, j) is defined as the sum of the elements in nums between indices i and j inclusive, where i <= j. ", + "category": [ + "Array", + "Binary Search", + "Divide and Conquer", + "Binary Indexed Tree", + "Segment Tree", + "Merge Sort", + "Ordered Set" + ], + "complexity": "Hard", + "successrate": 36, + "totalsubmissions": 163712, + "totalaccepted": 59005, + "likes": 1502, + "dislikes": 155, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [-2,5,-1], lower = -2, upper = 2", + "expected_output": "3", + "explanation": "The three ranges are: [0,0], [2,2], and [0,2] and their respective sums are: -2, -1, 2." + }, + { + "example_num": 2, + "expected_input": "nums = [0], lower = 0, upper = 0", + "expected_output": "1", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b7c", + "questionid": 177, + "title": "Patching Array", + "slug": "patching-array", + "description": "Given a sorted integer array nums and an integer n, add/patch elements to the array such that any number in the range [1, n] inclusive can be formed by the sum of some elements in the array. Return the minimum number of patches required. ", + "category": [ + "Array", + "Greedy" + ], + "complexity": "Hard", + "successrate": 39.5, + "totalsubmissions": 141671, + "totalaccepted": 55966, + "likes": 1085, + "dislikes": 113, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,3], n = 6", + "expected_output": "1\nExplanation:\nCombinations of nums are [1], [3], [1,3], which form possible sums of: 1, 3, 4.\nNow if we add/patch 2 to nums, the combinations are: [1], [2], [3], [1,3], [2,3], [1,2,3].\nPossible sums are 1, 2, 3, 4, 5, 6, which now covers the range [1, 6].\nSo we only need 1 patch.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "nums = [1,5,10], n = 20", + "expected_output": "2\nExplanation: The two patches can be [2, 4].", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "nums = [1,2,2], n = 5", + "expected_output": "0", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b7e", + "questionid": 179, + "title": "Increasing Triplet Subsequence", + "slug": "increasing-triplet-subsequence", + "description": "Given an integer array nums, return true if there exists a triple of indices (i, j, k) such that i < j < k and nums[i] < nums[j] < nums[k]. If no such indices exists, return false. ", + "category": [ + "Array", + "Greedy" + ], + "complexity": "Medium", + "successrate": 41.5, + "totalsubmissions": 642716, + "totalaccepted": 266546, + "likes": 3768, + "dislikes": 208, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,2,3,4,5]", + "expected_output": "true", + "explanation": "Any triplet where i < j < k is valid." + }, + { + "example_num": 2, + "expected_input": "nums = [5,4,3,2,1]", + "expected_output": "false", + "explanation": "No triplet exists." + }, + { + "example_num": 3, + "expected_input": "nums = [2,1,5,0,4,6]", + "expected_output": "true", + "explanation": "The triplet (3, 4, 5) is valid because nums[3] == 0 < nums[4] == 4 < nums[5] == 6." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b8f", + "questionid": 196, + "title": "Wiggle Subsequence", + "slug": "wiggle-subsequence", + "description": "A wiggle sequence is a sequence where the differences between successive numbers strictly alternate between positive and negative. The first difference (if one exists) may be either positive or negative. A sequence with one element and a sequence with two non-equal elements are trivially wiggle sequences. A subsequence is obtained by deleting some elements (possibly zero) from the original sequence, leaving the remaining elements in their original order. Given an integer array nums, return the length of the longest wiggle subsequence of nums. ", + "category": [ + "Array", + "Dynamic Programming", + "Greedy" + ], + "complexity": "Medium", + "successrate": 44.9, + "totalsubmissions": 301689, + "totalaccepted": 135314, + "likes": 2617, + "dislikes": 93, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,7,4,9,2,5]", + "expected_output": "6", + "explanation": "The entire sequence is a wiggle sequence with differences (6, -3, 5, -7, 3)." + }, + { + "example_num": 2, + "expected_input": "nums = [1,17,5,10,13,15,10,5,16,8]", + "expected_output": "7", + "explanation": "There are several subsequences that achieve this length.\nOne is [1, 17, 10, 13, 10, 16, 8] with differences (16, -7, 3, -3, 6, -8)." + }, + { + "example_num": 3, + "expected_input": "nums = [1,2,3,4,5,6,7,8,9]", + "expected_output": "2", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b93", + "questionid": 200, + "title": "Mini Parser", + "slug": "mini-parser", + "description": "Given a string s represents the serialization of a nested list, implement a parser to deserialize it and return the deserialized NestedInteger. Each element is either an integer or a list whose elements may also be integers or other lists. ", + "category": [ + "String", + "Stack", + "Depth-First Search" + ], + "complexity": "Medium", + "successrate": 35.8, + "totalsubmissions": 133077, + "totalaccepted": 47667, + "likes": 360, + "dislikes": 1129, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "324"", + "expected_output": "324", + "explanation": "You should return a NestedInteger object which contains a single integer 324." + }, + { + "example_num": 2, + "expected_input": "s = "[123,[456,[789]]]"", + "expected_output": "[123,[456,[789]]]", + "explanation": "Return a NestedInteger object containing a nested list with 2 elements:\n1. An integer containing value 123.\n2. A nested list containing two elements:\n i. An integer containing value 456.\n ii. A nested list with one element:\n a. An integer containing value 789" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b98", + "questionid": 205, + "title": "Is Subsequence", + "slug": "is-subsequence", + "description": "Given two strings s and t, return true if s is a subsequence of t, or false otherwise. A subsequence of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., \"ace\" is a subsequence of \"abcde\" while \"aec\" is not). ", + "category": [ + "Two Pointers", + "String", + "Dynamic Programming" + ], + "complexity": "Easy", + "successrate": 51, + "totalsubmissions": 891195, + "totalaccepted": 454214, + "likes": 4635, + "dislikes": 285, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = \"abc\", t = \"ahbgdc\"", + "expected_output": "true", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "s = \"axc\", t = \"ahbgdc\"", + "expected_output": "false", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b9b", + "questionid": 208, + "title": "Binary Watch", + "slug": "binary-watch", + "description": "A binary watch has 4 LEDs on the top which represent the hours (0-11), and the 6 LEDs on the bottom represent the minutes (0-59). Each LED represents a zero or one, with the least significant bit on the right. Given an integer turnedOn which represents the number of LEDs that are currently on, return all possible times the watch could represent. You may return the answer in any order. The hour must not contain a leading zero. The minute must be consist of two digits and may contain a leading zero. ", + "category": [ + "Backtracking", + "Bit Manipulation" + ], + "complexity": "Easy", + "successrate": 50.4, + "totalsubmissions": 215786, + "totalaccepted": 108789, + "likes": 935, + "dislikes": 1753, + "hints": "Simplify by seeking for solutions that involve comparing bit counts. Consider calculating all possible times for comparison purposes.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "turnedOn = 1", + "expected_output": "[\"0:01\",\"0:02\",\"0:04\",\"0:08\",\"0:16\",\"0:32\",\"1:00\",\"2:00\",\"4:00\",\"8:00\"]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "turnedOn = 9", + "expected_output": "[]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720ba1", + "questionid": 214, + "title": "Longest Palindrome", + "slug": "longest-palindrome", + "description": "Given a string s which consists of lowercase or uppercase letters, return the length of the longest palindrome that can be built with those letters. Letters are case sensitive, for example, \"Aa\" is not considered a palindrome here. ", + "category": [ + "Hash Table", + "String", + "Greedy" + ], + "complexity": "Easy", + "successrate": 53.5, + "totalsubmissions": 496778, + "totalaccepted": 265829, + "likes": 2591, + "dislikes": 153, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "abccccdd"", + "expected_output": "7", + "explanation": "One longest palindrome that can be built is "dccaccd", whose length is 7." + }, + { + "example_num": 2, + "expected_input": "s = "a"", + "expected_output": "1", + "explanation": "The longest palindrome that can be built is "a", whose length is 1." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720ba6", + "questionid": 219, + "title": "Partition Equal Subset Sum", + "slug": "partition-equal-subset-sum", + "description": "Given a non-empty array nums containing only positive integers, find if the array can be partitioned into two subsets such that the sum of elements in both subsets is equal. ", + "category": [ + "Array", + "Dynamic Programming" + ], + "complexity": "Medium", + "successrate": 46.4, + "totalsubmissions": 925930, + "totalaccepted": 429311, + "likes": 7247, + "dislikes": 115, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,5,11,5]", + "expected_output": "true", + "explanation": "The array can be partitioned as [1, 5, 5] and [11]." + }, + { + "example_num": 2, + "expected_input": "nums = [1,2,3,5]", + "expected_output": "false", + "explanation": "The array cannot be partitioned into equal sum subsets." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720baf", + "questionid": 228, + "title": "Find Right Interval", + "slug": "find-right-interval", + "description": "You are given an array of intervals, where intervals[i] = [starti, endi] and each starti is unique. The right interval for an interval i is an interval j such that startj >= endi and startj is minimized. Note that i may equal j. Return an array of right interval indices for each interval i. If no right interval exists for interval i, then put -1 at index i. ", + "category": [ + "Array", + "Binary Search", + "Sorting" + ], + "complexity": "Medium", + "successrate": 49.4, + "totalsubmissions": 154224, + "totalaccepted": 76193, + "likes": 1169, + "dislikes": 248, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "intervals = [[1,2]]", + "expected_output": "[-1]", + "explanation": "There is only one interval in the collection, so it outputs -1." + }, + { + "example_num": 2, + "expected_input": "intervals = [[3,4],[2,3],[1,2]]", + "expected_output": "[-1,0,1]", + "explanation": "There is no right interval for [3,4].\nThe right interval for [2,3] is [3,4] since start0 = 3 is the smallest start that is >= end1 = 3.\nThe right interval for [1,2] is [2,3] since start1 = 2 is the smallest start that is >= end2 = 2." + }, + { + "example_num": 3, + "expected_input": "intervals = [[1,4],[2,3],[3,4]]", + "expected_output": "[-1,2,-1]", + "explanation": "There is no right interval for [1,4] and [3,4].\nThe right interval for [2,3] is [3,4] since start2 = 3 is the smallest start that is >= end1 = 3." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720bb5", + "questionid": 234, + "title": "Add Two Numbers II", + "slug": "add-two-numbers-ii", + "description": "You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list. You may assume the two numbers do not contain any leading zero, except the number 0 itself. ", + "category": [ + "Linked List", + "Math", + "Stack" + ], + "complexity": "Medium", + "successrate": 58.5, + "totalsubmissions": 523092, + "totalaccepted": 306223, + "likes": 3414, + "dislikes": 226, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "l1 = [7,2,4,3], l2 = [5,6,4]", + "expected_output": "[7,8,0,7]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "l1 = [2,4,3], l2 = [5,6,4]", + "expected_output": "[8,0,7]", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "l1 = [0], l2 = [0]", + "expected_output": "[0]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720bbb", + "questionid": 240, + "title": "Minimum Number of Arrows to Burst Balloons", + "slug": "minimum-number-of-arrows-to-burst-balloons", + "description": "There are some spherical balloons taped onto a flat wall that represents the XY-plane. The balloons are represented as a 2D integer array points where points[i] = [xstart, xend] denotes a balloon whose horizontal diameter stretches between xstart and xend. You do not know the exact y-coordinates of the balloons. Arrows can be shot up directly vertically (in the positive y-direction) from different points along the x-axis. A balloon with xstart and xend is burst by an arrow shot at x if xstart <= x <= xend. There is no limit to the number of arrows that can be shot. A shot arrow keeps traveling up infinitely, bursting any balloons in its path. Given the array points, return the minimum number of arrows that must be shot to burst all balloons. ", + "category": [ + "Array", + "Greedy", + "Sorting" + ], + "complexity": "Medium", + "successrate": 52.9, + "totalsubmissions": 351182, + "totalaccepted": 185715, + "likes": 3362, + "dislikes": 97, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "points = [[10,16],[2,8],[1,6],[7,12]]", + "expected_output": "2", + "explanation": "The balloons can be burst by 2 arrows:\n- Shoot an arrow at x = 6, bursting the balloons [2,8] and [1,6].\n- Shoot an arrow at x = 11, bursting the balloons [10,16] and [7,12]." + }, + { + "example_num": 2, + "expected_input": "points = [[1,2],[3,4],[5,6],[7,8]]", + "expected_output": "4", + "explanation": "One arrow needs to be shot for each balloon for a total of 4 arrows." + }, + { + "example_num": 3, + "expected_input": "points = [[1,2],[2,3],[3,4],[4,5]]", + "expected_output": "2", + "explanation": "The balloons can be burst by 2 arrows:\n- Shoot an arrow at x = 2, bursting the balloons [1,2] and [2,3].\n- Shoot an arrow at x = 4, bursting the balloons [3,4] and [4,5]." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b8c", + "questionid": 193, + "title": "Sum of Two Integers", + "slug": "sum-of-two-integers", + "description": "Given two integers a and b, return the sum of the two integers without using the operators + and -. ", + "category": [ + "Math", + "Bit Manipulation" + ], + "complexity": "Medium", + "successrate": 50.6, + "totalsubmissions": 575879, + "totalaccepted": 291580, + "likes": 2464, + "dislikes": 3695, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "a = 1, b = 2", + "expected_output": "3", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "a = 2, b = 3", + "expected_output": "5", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b8d", + "questionid": 194, + "title": "Super Pow", + "slug": "super-pow", + "description": "Your task is to calculate ab mod 1337 where a is a positive integer and b is an extremely large positive integer given in the form of an array. ", + "category": [ + "Math", + "Divide and Conquer" + ], + "complexity": "Medium", + "successrate": 37.6, + "totalsubmissions": 129129, + "totalaccepted": 48553, + "likes": 464, + "dislikes": 1081, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "a = 2, b = [3]", + "expected_output": "8", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "a = 2, b = [1,0]", + "expected_output": "1024", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "a = 1, b = [4,3,3,8,5,2]", + "expected_output": "1", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b92", + "questionid": 199, + "title": "Ransom Note", + "slug": "ransom-note", + "description": "Given two strings ransomNote and magazine, return true if ransomNote can be constructed from magazine and false otherwise. Each letter in magazine can only be used once in ransomNote. ", + "category": [ + "Hash Table", + "String", + "Counting" + ], + "complexity": "Easy", + "successrate": 55.8, + "totalsubmissions": 659531, + "totalaccepted": 367856, + "likes": 1646, + "dislikes": 297, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "ransomNote = \"a\", magazine = \"b\"", + "expected_output": "false", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "ransomNote = \"aa\", magazine = \"ab\"", + "expected_output": "false", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "ransomNote = \"aa\", magazine = \"aab\"", + "expected_output": "true", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b95", + "questionid": 202, + "title": "First Unique Character in a String", + "slug": "first-unique-character-in-a-string", + "description": "Given a string s, find the first non-repeating character in it and return its index. If it does not exist, return -1. ", + "category": [ + "Hash Table", + "String", + "Queue", + "Counting" + ], + "complexity": "Easy", + "successrate": 57, + "totalsubmissions": 1798969, + "totalaccepted": 1025564, + "likes": 4844, + "dislikes": 193, + "hints": "", + "deleted": false, + "examples": [] + }, + { + "_id": "66f925ddfdfb8e1665720b96", + "questionid": 203, + "title": "Find the Difference", + "slug": "find-the-difference", + "description": "You are given two strings s and t. String t is generated by random shuffling string s and then add one more letter at a random position. Return the letter that was added to t. ", + "category": [ + "Hash Table", + "String", + "Bit Manipulation", + "Sorting" + ], + "complexity": "Easy", + "successrate": 60.5, + "totalsubmissions": 635903, + "totalaccepted": 384938, + "likes": 2700, + "dislikes": 381, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "abcd", t = "abcde"", + "expected_output": ""e"", + "explanation": "'e' is the letter that was added." + }, + { + "example_num": 2, + "expected_input": "s = "", t = "y"", + "expected_output": ""y"", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b9a", + "questionid": 207, + "title": "Nth Digit", + "slug": "nth-digit", + "description": "Given an integer n, return the nth digit of the infinite integer sequence [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ...]. ", + "category": [ + "Math", + "Binary Search" + ], + "complexity": "Medium", + "successrate": 33.5, + "totalsubmissions": 223742, + "totalaccepted": 74920, + "likes": 656, + "dislikes": 1499, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 3", + "expected_output": "3", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "n = 11", + "expected_output": "0", + "explanation": "The 11th digit of the sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ... is a 0, which is part of the number 10." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720ba2", + "questionid": 215, + "title": "Split Array Largest Sum", + "slug": "split-array-largest-sum", + "description": "Given an array nums which consists of non-negative integers and an integer m, you can split the array into m non-empty continuous subarrays. Write an algorithm to minimize the largest sum among these m subarrays. ", + "category": [ + "Array", + "Binary Search", + "Dynamic Programming", + "Greedy" + ], + "complexity": "Hard", + "successrate": 52, + "totalsubmissions": 393533, + "totalaccepted": 204494, + "likes": 5728, + "dislikes": 149, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [7,2,5,10,8], k = 2", + "expected_output": "18", + "explanation": "There are four ways to split nums into two subarrays.\nThe best way is to split it into [7,2,5] and [10,8], where the largest sum among the two subarrays is only 18." + }, + { + "example_num": 2, + "expected_input": "nums = [1,2,3,4,5], k = 2", + "expected_output": "9", + "explanation": "There are four ways to split nums into two subarrays.\nThe best way is to split it into [1,2,3] and [4,5], where the largest sum among the two subarrays is only 9." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720ba3", + "questionid": 216, + "title": "Arithmetic Slices", + "slug": "arithmetic-slices", + "description": "An integer array is called arithmetic if it consists of at least three elements and if the difference between any two consecutive elements is the same. Given an integer array nums, return the number of arithmetic subarrays of nums. A subarray is a contiguous subsequence of the array. ", + "category": [ + "Array", + "Dynamic Programming" + ], + "complexity": "Medium", + "successrate": 64.4, + "totalsubmissions": 350296, + "totalaccepted": 225542, + "likes": 3847, + "dislikes": 249, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,2,3,4]", + "expected_output": "3", + "explanation": "We have 3 arithmetic slices in nums: [1, 2, 3], [2, 3, 4] and [1,2,3,4] itself." + }, + { + "example_num": 2, + "expected_input": "nums = [1]", + "expected_output": "0", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720ba5", + "questionid": 218, + "title": "Add Strings", + "slug": "add-strings", + "description": "Given two non-negative integers, num1 and num2 represented as string, return the sum of num1 and num2 as a string. You must solve the problem without using any built-in library for handling large integers (such as BigInteger). You must also not convert the inputs to integers directly. ", + "category": [ + "Math", + "String", + "Simulation" + ], + "complexity": "Easy", + "successrate": 52.1, + "totalsubmissions": 888575, + "totalaccepted": 462692, + "likes": 3167, + "dislikes": 538, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "num1 = "11", num2 = "123"", + "expected_output": ""134"", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "num1 = "456", num2 = "77"", + "expected_output": ""533"", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "num1 = "0", num2 = "0"", + "expected_output": ""0"", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720ba9", + "questionid": 222, + "title": "Maximum XOR of Two Numbers in an Array", + "slug": "maximum-xor-of-two-numbers-in-an-array", + "description": "Given an integer array nums, return the maximum result of nums[i] XOR nums[j], where 0 <= i <= j < n. ", + "category": [ + "Array", + "Hash Table", + "Bit Manipulation", + "Trie" + ], + "complexity": "Medium", + "successrate": 54.3, + "totalsubmissions": 223851, + "totalaccepted": 121492, + "likes": 3837, + "dislikes": 324, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [3,10,5,25,2,8]", + "expected_output": "28", + "explanation": "The maximum result is 5 XOR 25 = 28." + }, + { + "example_num": 2, + "expected_input": "nums = [14,70,53,83,49,91,36,80,92,51,66,70]", + "expected_output": "127", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720bb1", + "questionid": 230, + "title": "Find All Anagrams in a String", + "slug": "find-all-anagrams-in-a-string", + "description": "Given two strings s and p, return an array of all the start indices of p's anagrams in s. You may return the answer in any order. An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. ", + "category": [ + "Hash Table", + "String", + "Sliding Window" + ], + "complexity": "Medium", + "successrate": 48.2, + "totalsubmissions": 1076189, + "totalaccepted": 518606, + "likes": 7285, + "dislikes": 251, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "cbaebabacd", p = "abc"", + "expected_output": "[0,6]", + "explanation": "The substring with start index = 0 is "cba", which is an anagram of "abc".\nThe substring with start index = 6 is "bac", which is an anagram of "abc"." + }, + { + "example_num": 2, + "expected_input": "s = "abab", p = "ab"", + "expected_output": "[0,1,2]", + "explanation": "The substring with start index = 0 is "ab", which is an anagram of "ab".\nThe substring with start index = 1 is "ba", which is an anagram of "ab".\nThe substring with start index = 2 is "ab", which is an anagram of "ab"." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720bb6", + "questionid": 235, + "title": "Arithmetic Slices II - Subsequence", + "slug": "arithmetic-slices-ii-subsequence", + "description": "Given an integer array nums, return the number of all the arithmetic subsequences of nums. A sequence of numbers is called arithmetic if it consists of at least three elements and if the difference between any two consecutive elements is the same. A subsequence of an array is a sequence that can be formed by removing some elements (possibly none) of the array. The test cases are generated so that the answer fits in 32-bit integer. ", + "category": [ + "Array", + "Dynamic Programming" + ], + "complexity": "Hard", + "successrate": 39.4, + "totalsubmissions": 110325, + "totalaccepted": 43491, + "likes": 1340, + "dislikes": 85, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [2,4,6,8,10]", + "expected_output": "7", + "explanation": "All arithmetic subsequence slices are:\n[2,4,6]\n[4,6,8]\n[6,8,10]\n[2,4,6,8]\n[4,6,8,10]\n[2,4,6,8,10]\n[2,6,10]" + }, + { + "example_num": 2, + "expected_input": "nums = [7,7,7,7,7]", + "expected_output": "16", + "explanation": "Any subsequence of this array is arithmetic." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720bbd", + "questionid": 242, + "title": "Assign Cookies", + "slug": "assign-cookies", + "description": "Assume you are an awesome parent and want to give your children some cookies. But, you should give each child at most one cookie. Each child i has a greed factor g[i], which is the minimum size of a cookie that the child will be content with; and each cookie j has a size s[j]. If s[j] >= g[i], we can assign the cookie j to the child i, and the child i will be content. Your goal is to maximize the number of your content children and output the maximum number. ", + "category": [ + "Array", + "Greedy", + "Sorting" + ], + "complexity": "Easy", + "successrate": 50.7, + "totalsubmissions": 319993, + "totalaccepted": 162255, + "likes": 1404, + "dislikes": 157, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "g = [1,2,3], s = [1,1]", + "expected_output": "1", + "explanation": "You have 3 children and 2 cookies. The greed factors of 3 children are 1, 2, 3. \nAnd even though you have 2 cookies, since their size is both 1, you could only make the child whose greed factor is 1 content.\nYou need to output 1." + }, + { + "example_num": 2, + "expected_input": "g = [1,2], s = [1,2,3]", + "expected_output": "2", + "explanation": "You have 2 children and 3 cookies. The greed factors of 2 children are 1, 2. \nYou have 3 cookies and their sizes are big enough to gratify all of the children, \nYou need to output 2." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720bbe", + "questionid": 243, + "title": "132 Pattern", + "slug": "132-pattern", + "description": "Given an array of n integers nums, a 132 pattern is a subsequence of three integers nums[i], nums[j] and nums[k] such that i < j < k and nums[i] < nums[k] < nums[j]. Return true if there is a 132 pattern in nums, otherwise, return false. ", + "category": [ + "Array", + "Binary Search", + "Stack", + "Monotonic Stack", + "Ordered Set" + ], + "complexity": "Medium", + "successrate": 30.9, + "totalsubmissions": 344145, + "totalaccepted": 106371, + "likes": 3199, + "dislikes": 176, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,2,3,4]", + "expected_output": "false", + "explanation": "There is no 132 pattern in the sequence." + }, + { + "example_num": 2, + "expected_input": "nums = [3,1,4,2]", + "expected_output": "true", + "explanation": "There is a 132 pattern in the sequence: [1, 4, 2]." + }, + { + "example_num": 3, + "expected_input": "nums = [-1,3,2,0]", + "expected_output": "true", + "explanation": "There are three 132 patterns in the sequence: [-1, 3, 2], [-1, 3, 0] and [-1, 2, 0]." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720bbf", + "questionid": 244, + "title": "Repeated Substring Pattern", + "slug": "repeated-substring-pattern", + "description": "Given a string s, check if it can be constructed by taking a substring of it and appending multiple copies of the substring together. ", + "category": [ + "String", + "String Matching" + ], + "complexity": "Easy", + "successrate": 43.6, + "totalsubmissions": 545164, + "totalaccepted": 237600, + "likes": 3266, + "dislikes": 312, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "abab"", + "expected_output": "true", + "explanation": "It is the substring "ab" twice." + }, + { + "example_num": 2, + "expected_input": "s = "aba"", + "expected_output": "false", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "s = "abcabcabcabc"", + "expected_output": "true", + "explanation": "It is the substring "abc" four times or the substring "abcabc" twice." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720bc0", + "questionid": 245, + "title": "Hamming Distance", + "slug": "hamming-distance", + "description": "The Hamming distance between two integers is the number of positions at which the corresponding bits are different. Given two integers x and y, return the Hamming distance between them. ", + "category": [ + "Bit Manipulation" + ], + "complexity": "Easy", + "successrate": 74.5, + "totalsubmissions": 630915, + "totalaccepted": 469900, + "likes": 3021, + "dislikes": 197, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "x = 1, y = 4", + "expected_output": "2", + "explanation": "1 (0 0 0 1)\n4 (0 1 0 0)\n ↑ ↑\nThe above arrows point to positions where the corresponding bits are different." + }, + { + "example_num": 2, + "expected_input": "x = 3, y = 1", + "expected_output": "1", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720bc2", + "questionid": 247, + "title": "Island Perimeter", + "slug": "island-perimeter", + "description": "You are given row x col grid representing a map where grid[i][j] = 1 represents land and grid[i][j] = 0 represents water. Grid cells are connected horizontally/vertically (not diagonally). The grid is completely surrounded by water, and there is exactly one island (i.e., one or more connected land cells). The island doesn't have \"lakes\", meaning the water inside isn't connected to the water around the island. One cell is a square with side length 1. The grid is rectangular, width and height don't exceed 100. Determine the perimeter of the island. ", + "category": [ + "Array", + "Depth-First Search", + "Breadth-First Search", + "Matrix" + ], + "complexity": "Easy", + "successrate": 68.9, + "totalsubmissions": 522927, + "totalaccepted": 360401, + "likes": 4279, + "dislikes": 237, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "grid = [[0,1,0,0],[1,1,1,0],[0,1,0,0],[1,1,0,0]]", + "expected_output": "16", + "explanation": "The perimeter is the 16 yellow stripes in the image above." + }, + { + "example_num": 2, + "expected_input": "grid = [[1]]", + "expected_output": "4", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "grid = [[1,0]]", + "expected_output": "4", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720bc3", + "questionid": 248, + "title": "Can I Win", + "slug": "can-i-win", + "description": "In the \"100 game\" two players take turns adding, to a running total, any integer from 1 to 10. The player who first causes the running total to reach or exceed 100 wins. What if we change the game so that players cannot re-use integers? For example, two players might take turns drawing from a common pool of numbers from 1 to 15 without replacement until they reach a total >= 100. Given two integers maxChoosableInteger and desiredTotal, return true if the first player to move can force a win, otherwise, return false. Assume both players play optimally. ", + "category": [ + "Math", + "Dynamic Programming", + "Bit Manipulation", + "Memoization", + "Game Theory", + "Bitmask" + ], + "complexity": "Medium", + "successrate": 29.8, + "totalsubmissions": 250138, + "totalaccepted": 74662, + "likes": 1824, + "dislikes": 294, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "maxChoosableInteger = 10, desiredTotal = 11", + "expected_output": "false", + "explanation": "No matter which integer the first player choose, the first player will lose.\nThe first player can choose an integer from 1 up to 10.\nIf the first player choose 1, the second player can only choose integers from 2 up to 10.\nThe second player will win by choosing 10 and get a total = 11, which is >= desiredTotal.\nSame with other integers chosen by the first player, the second player will always win." + }, + { + "example_num": 2, + "expected_input": "maxChoosableInteger = 10, desiredTotal = 0", + "expected_output": "true", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "maxChoosableInteger = 10, desiredTotal = 1", + "expected_output": "true", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720bc5", + "questionid": 250, + "title": "Concatenated Words", + "slug": "concatenated-words", + "description": "Given an array of strings words (without duplicates), return all the concatenated words in the given list of words. A concatenated word is defined as a string that is comprised entirely of at least two shorter words in the given array. ", + "category": [ + "Array", + "String", + "Dynamic Programming", + "Depth-First Search", + "Trie" + ], + "complexity": "Hard", + "successrate": 42.8, + "totalsubmissions": 300523, + "totalaccepted": 128601, + "likes": 1848, + "dislikes": 216, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "words = ["cat","cats","catsdogcats","dog","dogcatsdog","hippopotamuses","rat","ratcatdogcat"]", + "expected_output": "["catsdogcats","dogcatsdog","ratcatdogcat"]", + "explanation": ""catsdogcats" can be concatenated by "cats", "dog" and "cats"; \n"dogcatsdog" can be concatenated by "dog", "cats" and "dog"; \n"ratcatdogcat" can be concatenated by "rat", "cat", "dog" and "cat"." + }, + { + "example_num": 2, + "expected_input": "words = ["cat","dog","catdog"]", + "expected_output": "["catdog"]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720bc7", + "questionid": 252, + "title": "Ones and Zeroes", + "slug": "ones-and-zeroes", + "description": "You are given an array of binary strings strs and two integers m and n. Return the size of the largest subset of strs such that there are at most m 0's and n 1's in the subset. A set x is a subset of a set y if all elements of x are also elements of y. ", + "category": [ + "Array", + "String", + "Dynamic Programming" + ], + "complexity": "Medium", + "successrate": 44.5, + "totalsubmissions": 237317, + "totalaccepted": 105672, + "likes": 2790, + "dislikes": 322, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "strs = ["10","0001","111001","1","0"], m = 5, n = 3", + "expected_output": "4", + "explanation": "The largest subset with at most 5 0's and 3 1's is {"10", "0001", "1", "0"}, so the answer is 4.\nOther valid but smaller subsets include {"0001", "1"} and {"10", "1", "0"}.\n{"111001"} is an invalid subset because it contains 4 1's, greater than the maximum of 3." + }, + { + "example_num": 2, + "expected_input": "strs = ["10","0","1"], m = 1, n = 1", + "expected_output": "2\nExplanation: The largest subset is {"0", "1"}, so the answer is 2.", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720bc8", + "questionid": 253, + "title": "Heaters", + "slug": "heaters", + "description": "Winter is coming! During the contest, your first job is to design a standard heater with a fixed warm radius to warm all the houses. Every house can be warmed, as long as the house is within the heater's warm radius range. Given the positions of houses and heaters on a horizontal line, return the minimum radius standard of heaters so that those heaters could cover all houses. Notice that all the heaters follow your radius standard, and the warm radius will the same. ", + "category": [ + "Array", + "Two Pointers", + "Binary Search", + "Sorting" + ], + "complexity": "Medium", + "successrate": 35.2, + "totalsubmissions": 247584, + "totalaccepted": 87206, + "likes": 1326, + "dislikes": 1026, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "houses = [1,2,3], heaters = [2]", + "expected_output": "1", + "explanation": "The only heater was placed in the position 2, and if we use the radius 1 standard, then all the houses can be warmed." + }, + { + "example_num": 2, + "expected_input": "houses = [1,2,3,4], heaters = [1,4]", + "expected_output": "1", + "explanation": "The two heaters were placed at positions 1 and 4. We need to use a radius 1 standard, then all the houses can be warmed." + }, + { + "example_num": 3, + "expected_input": "houses = [1,5], heaters = [2]", + "expected_output": "3", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720bc9", + "questionid": 254, + "title": "Number Complement", + "slug": "number-complement", + "description": "The complement of an integer is the integer you get when you flip all the 0's to 1's and all the 1's to 0's in its binary representation. Given an integer num, return its complement. ", + "category": [ + "Bit Manipulation" + ], + "complexity": "Easy", + "successrate": 66.7, + "totalsubmissions": 392862, + "totalaccepted": 261892, + "likes": 1954, + "dislikes": 105, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "num = 5", + "expected_output": "2", + "explanation": "The binary representation of 5 is 101 (no leading zero bits), and its complement is 010. So you need to output 2." + }, + { + "example_num": 2, + "expected_input": "num = 1", + "expected_output": "0", + "explanation": "The binary representation of 1 is 1 (no leading zero bits), and its complement is 0. So you need to output 0." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720bcb", + "questionid": 256, + "title": "Largest Palindrome Product", + "slug": "largest-palindrome-product", + "description": "Given an integer n, return the largest palindromic integer that can be represented as the product of two n-digits integers. Since the answer can be very large, return it modulo 1337. ", + "category": [ + "Math" + ], + "complexity": "Hard", + "successrate": 31.1, + "totalsubmissions": 65149, + "totalaccepted": 20274, + "likes": 123, + "dislikes": 1448, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 2", + "expected_output": "987\nExplanation: 99 x 91 = 9009, 9009 % 1337 = 987", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "n = 1", + "expected_output": "9", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b8e", + "questionid": 195, + "title": "Find K Pairs with Smallest Sums", + "slug": "find-k-pairs-with-smallest-sums", + "description": "You are given two integer arrays nums1 and nums2 sorted in ascending order and an integer k. Define a pair (u, v) which consists of one element from the first array and one element from the second array. Return the k pairs (u1, v1), (u2, v2), ..., (uk, vk) with the smallest sums. ", + "category": [ + "Array", + "Heap (Priority Queue)" + ], + "complexity": "Medium", + "successrate": 38.8, + "totalsubmissions": 430871, + "totalaccepted": 167230, + "likes": 2979, + "dislikes": 185, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums1 = [1,7,11], nums2 = [2,4,6], k = 3", + "expected_output": "[[1,2],[1,4],[1,6]]", + "explanation": "The first 3 pairs are returned from the sequence: [1,2],[1,4],[1,6],[7,2],[7,4],[11,2],[7,6],[11,4],[11,6]" + }, + { + "example_num": 2, + "expected_input": "nums1 = [1,1,2], nums2 = [1,2,3], k = 2", + "expected_output": "[[1,1],[1,1]]", + "explanation": "The first 2 pairs are returned from the sequence: [1,1],[1,1],[1,2],[2,1],[1,2],[2,2],[1,3],[1,3],[2,3]" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b97", + "questionid": 204, + "title": "Perfect Rectangle", + "slug": "perfect-rectangle", + "description": "Given an array rectangles where rectangles[i] = [xi, yi, ai, bi] represents an axis-aligned rectangle. The bottom-left point of the rectangle is (xi, yi) and the top-right point of it is (ai, bi). Return true if all the rectangles together form an exact cover of a rectangular region. ", + "category": [ + "Array", + "Line Sweep" + ], + "complexity": "Hard", + "successrate": 32.1, + "totalsubmissions": 106171, + "totalaccepted": 34050, + "likes": 592, + "dislikes": 97, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "rectangles = [[1,1,3,3],[3,1,4,2],[3,2,4,4],[1,3,2,4],[2,3,3,4]]", + "expected_output": "true", + "explanation": "All 5 rectangles together form an exact cover of a rectangular region." + }, + { + "example_num": 2, + "expected_input": "rectangles = [[1,1,2,3],[1,3,2,4],[3,1,4,2],[3,2,4,4]]", + "expected_output": "false", + "explanation": "Because there is a gap between the two rectangular regions." + }, + { + "example_num": 3, + "expected_input": "rectangles = [[1,1,3,3],[3,1,4,2],[1,3,2,4],[2,2,4,4]]", + "expected_output": "false", + "explanation": "Because two of the rectangles overlap with each other." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b9c", + "questionid": 209, + "title": "Remove K Digits", + "slug": "remove-k-digits", + "description": "Given string num representing a non-negative integer num, and an integer k, return the smallest possible integer after removing k digits from num. ", + "category": [ + "String", + "Stack", + "Greedy", + "Monotonic Stack" + ], + "complexity": "Medium", + "successrate": 30.5, + "totalsubmissions": 849382, + "totalaccepted": 258935, + "likes": 5963, + "dislikes": 249, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "num = "1432219", k = 3", + "expected_output": ""1219"", + "explanation": "Remove the three digits 4, 3, and 2 to form the new number 1219 which is the smallest." + }, + { + "example_num": 2, + "expected_input": "num = "10200", k = 1", + "expected_output": ""200"", + "explanation": "Remove the leading 1 and the number is 200. Note that the output must not contain leading zeroes." + }, + { + "example_num": 3, + "expected_input": "num = "10", k = 2", + "expected_output": ""0"", + "explanation": "Remove all the digits from the number and it is left with nothing which is 0." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720ba7", + "questionid": 220, + "title": "Pacific Atlantic Water Flow", + "slug": "pacific-atlantic-water-flow", + "description": "There is an m x n rectangular island that borders both the Pacific Ocean and Atlantic Ocean. The Pacific Ocean touches the island's left and top edges, and the Atlantic Ocean touches the island's right and bottom edges. The island is partitioned into a grid of square cells. You are given an m x n integer matrix heights where heights[r][c] represents the height above sea level of the cell at coordinate (r, c). The island receives a lot of rain, and the rain water can flow to neighboring cells directly north, south, east, and west if the neighboring cell's height is less than or equal to the current cell's height. Water can flow from any cell adjacent to an ocean into the ocean. Return a 2D list of grid coordinates result where result[i] = [ri, ci] denotes that rain water can flow from cell (ri, ci) to both the Pacific and Atlantic oceans. ", + "category": [ + "Array", + "Depth-First Search", + "Breadth-First Search", + "Matrix" + ], + "complexity": "Medium", + "successrate": 48.9, + "totalsubmissions": 392980, + "totalaccepted": 192213, + "likes": 3494, + "dislikes": 799, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "heights = [[1,2,2,3,5],[3,2,3,4,4],[2,4,5,3,1],[6,7,1,4,5],[5,1,1,2,4]]", + "expected_output": "[[0,4],[1,3],[1,4],[2,2],[3,0],[3,1],[4,0]]", + "explanation": "The following cells can flow to the Pacific and Atlantic oceans, as shown below:\n[0,4]: [0,4] -> Pacific Ocean \n  [0,4] -> Atlantic Ocean\n[1,3]: [1,3] -> [0,3] -> Pacific Ocean \n  [1,3] -> [1,4] -> Atlantic Ocean\n[1,4]: [1,4] -> [1,3] -> [0,3] -> Pacific Ocean \n  [1,4] -> Atlantic Ocean\n[2,2]: [2,2] -> [1,2] -> [0,2] -> Pacific Ocean \n  [2,2] -> [2,3] -> [2,4] -> Atlantic Ocean\n[3,0]: [3,0] -> Pacific Ocean \n  [3,0] -> [4,0] -> Atlantic Ocean\n[3,1]: [3,1] -> [3,0] -> Pacific Ocean \n  [3,1] -> [4,1] -> Atlantic Ocean\n[4,0]: [4,0] -> Pacific Ocean \n [4,0] -> Atlantic Ocean\nNote that there are other possible paths for these cells to flow to the Pacific and Atlantic oceans." + }, + { + "example_num": 2, + "expected_input": "heights = [[1]]", + "expected_output": "[[0,0]]", + "explanation": "The water can flow from the only cell to the Pacific and Atlantic oceans." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720ba8", + "questionid": 221, + "title": "Battleships in a Board", + "slug": "battleships-in-a-board", + "description": "Given an m x n matrix board where each cell is a battleship 'X' or empty '.', return the number of the battleships on board. Battleships can only be placed horizontally or vertically on board. In other words, they can only be made of the shape 1 x k (1 row, k columns) or k x 1 (k rows, 1 column), where k can be of any size. At least one horizontal or vertical cell separates between two battleships (i.e., there are no adjacent battleships). ", + "category": [ + "Array", + "Depth-First Search", + "Matrix" + ], + "complexity": "Medium", + "successrate": 73.4, + "totalsubmissions": 195795, + "totalaccepted": 143656, + "likes": 1452, + "dislikes": 733, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "board = [["X",".",".","X"],[".",".",".","X"],[".",".",".","X"]]", + "expected_output": "2", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "board = [["."]]", + "expected_output": "0", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720bab", + "questionid": 224, + "title": "Longest Repeating Character Replacement", + "slug": "longest-repeating-character-replacement", + "description": "You are given a string s and an integer k. You can choose any character of the string and change it to any other uppercase English character. You can perform this operation at most k times. Return the length of the longest substring containing the same letter you can get after performing the above operations. ", + "category": [ + "Hash Table", + "String", + "Sliding Window" + ], + "complexity": "Medium", + "successrate": 50.7, + "totalsubmissions": 406149, + "totalaccepted": 206085, + "likes": 4188, + "dislikes": 170, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "ABAB", k = 2", + "expected_output": "4", + "explanation": "Replace the two 'A's with two 'B's or vice versa." + }, + { + "example_num": 2, + "expected_input": "s = "AABABBA", k = 1", + "expected_output": "4", + "explanation": "Replace the one 'A' in the middle with 'B' and form "AABBBBA".\nThe substring "BBBB" has the longest repeating letters, which is 4.\nThere may exists other ways to achieve this answer too." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720bae", + "questionid": 227, + "title": "Non-overlapping Intervals", + "slug": "non-overlapping-intervals", + "description": "Given an array of intervals intervals where intervals[i] = [starti, endi], return the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping. ", + "category": [ + "Array", + "Dynamic Programming", + "Greedy", + "Sorting" + ], + "complexity": "Medium", + "successrate": 48.1, + "totalsubmissions": 494769, + "totalaccepted": 238037, + "likes": 3819, + "dislikes": 111, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "intervals = [[1,2],[2,3],[3,4],[1,3]]", + "expected_output": "1", + "explanation": "[1,3] can be removed and the rest of the intervals are non-overlapping." + }, + { + "example_num": 2, + "expected_input": "intervals = [[1,2],[1,2],[1,2]]", + "expected_output": "2", + "explanation": "You need to remove two [1,2] to make the rest of the intervals non-overlapping." + }, + { + "example_num": 3, + "expected_input": "intervals = [[1,2],[2,3]]", + "expected_output": "0", + "explanation": "You don't need to remove any of the intervals since they're already non-overlapping." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720bb2", + "questionid": 231, + "title": "K-th Smallest in Lexicographical Order", + "slug": "k-th-smallest-in-lexicographical-order", + "description": "Given two integers n and k, return the kth lexicographically smallest integer in the range [1, n]. ", + "category": [ + "Trie" + ], + "complexity": "Hard", + "successrate": 30.5, + "totalsubmissions": 57068, + "totalaccepted": 17419, + "likes": 552, + "dislikes": 73, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 13, k = 2", + "expected_output": "10", + "explanation": "The lexicographical order is [1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9], so the second smallest number is 10." + }, + { + "example_num": 2, + "expected_input": "n = 1, k = 1", + "expected_output": "1", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720bb4", + "questionid": 233, + "title": "Find All Duplicates in an Array", + "slug": "find-all-duplicates-in-an-array", + "description": "Given an integer array nums of length n where all the integers of nums are in the range [1, n] and each integer appears once or twice, return an array of all the integers that appears twice. You must write an algorithm that runs in O(n) time and uses only constant extra space. ", + "category": [ + "Array", + "Hash Table" + ], + "complexity": "Medium", + "successrate": 72.3, + "totalsubmissions": 540996, + "totalaccepted": 391236, + "likes": 5995, + "dislikes": 247, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [4,3,2,7,8,2,3,1]", + "expected_output": "[2,3]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "nums = [1,1,2]", + "expected_output": "[1]", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "nums = [1]", + "expected_output": "[]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720bb7", + "questionid": 236, + "title": "Number of Boomerangs", + "slug": "number-of-boomerangs", + "description": "You are given n points in the plane that are all distinct, where points[i] = [xi, yi]. A boomerang is a tuple of points (i, j, k) such that the distance between i and j equals the distance between i and k (the order of the tuple matters). Return the number of boomerangs. ", + "category": [ + "Array", + "Hash Table", + "Math" + ], + "complexity": "Medium", + "successrate": 54.1, + "totalsubmissions": 156588, + "totalaccepted": 84744, + "likes": 611, + "dislikes": 881, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "points = [[0,0],[1,0],[2,0]]", + "expected_output": "2", + "explanation": "The two boomerangs are [[1,0],[0,0],[2,0]] and [[1,0],[2,0],[0,0]]." + }, + { + "example_num": 2, + "expected_input": "points = [[1,1],[2,2],[3,3]]", + "expected_output": "2", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "points = [[1,1]]", + "expected_output": "0", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720bc6", + "questionid": 251, + "title": "Matchsticks to Square", + "slug": "matchsticks-to-square", + "description": "You are given an integer array matchsticks where matchsticks[i] is the length of the ith matchstick. You want to use all the matchsticks to make one square. You should not break any stick, but you can link them up, and each matchstick must be used exactly one time. Return true if you can make this square and false otherwise. ", + "category": [ + "Array", + "Dynamic Programming", + "Backtracking", + "Bit Manipulation", + "Bitmask" + ], + "complexity": "Medium", + "successrate": 40.3, + "totalsubmissions": 188482, + "totalaccepted": 76024, + "likes": 1571, + "dislikes": 121, + "hints": "Treat the matchsticks as an array. Can we split the array into 4 equal halves? Every matchstick can belong to either of the 4 sides. We don't know which one. Maybe try out all options! For every matchstick, we have to try out each of the 4 options i.e. which side it can belong to. We can make use of recursion for this. We don't really need to keep track of which matchsticks belong to a particular side during recursion. We just need to keep track of the length of each of the 4 sides. When all matchsticks have been used we simply need to see the length of all 4 sides. If they're equal, we have a square on our hands!", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "matchsticks = [1,1,2,2,2]", + "expected_output": "true", + "explanation": "You can form a square with length 2, one side of the square came two sticks with length 1." + }, + { + "example_num": 2, + "expected_input": "matchsticks = [3,3,3,3,4]", + "expected_output": "false", + "explanation": "You cannot find a way to form a square with all the matchsticks." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b90", + "questionid": 197, + "title": "Combination Sum IV", + "slug": "combination-sum-iv", + "description": "Given an array of distinct integers nums and a target integer target, return the number of possible combinations that add up to target. The test cases are generated so that the answer can fit in a 32-bit integer. ", + "category": [ + "Array", + "Dynamic Programming" + ], + "complexity": "Medium", + "successrate": 49.3, + "totalsubmissions": 482241, + "totalaccepted": 237874, + "likes": 3333, + "dislikes": 383, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,2,3], target = 4", + "expected_output": "7", + "explanation": "The possible combination ways are:\n(1, 1, 1, 1)\n(1, 1, 2)\n(1, 2, 1)\n(1, 3)\n(2, 1, 1)\n(2, 2)\n(3, 1)\nNote that different sequences are counted as different combinations." + }, + { + "example_num": 2, + "expected_input": "nums = [9], target = 3", + "expected_output": "0", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b91", + "questionid": 198, + "title": "Kth Smallest Element in a Sorted Matrix", + "slug": "kth-smallest-element-in-a-sorted-matrix", + "description": "Given an n x n matrix where each of the rows and columns is sorted in ascending order, return the kth smallest element in the matrix. Note that it is the kth smallest element in the sorted order, not the kth distinct element. You must find a solution with a memory complexity better than O(n2). ", + "category": [ + "Array", + "Binary Search", + "Sorting", + "Heap (Priority Queue)", + "Matrix" + ], + "complexity": "Medium", + "successrate": 59.6, + "totalsubmissions": 632411, + "totalaccepted": 376832, + "likes": 5707, + "dislikes": 236, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "matrix = [[1,5,9],[10,11,13],[12,13,15]], k = 8", + "expected_output": "13", + "explanation": "The elements in the matrix are [1,5,9,10,11,12,13,13,15], and the 8th smallest number is 13" + }, + { + "example_num": 2, + "expected_input": "matrix = [[-5]], k = 1", + "expected_output": "-5", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b94", + "questionid": 201, + "title": "Lexicographical Numbers", + "slug": "lexicographical-numbers", + "description": "Given an integer n, return all the numbers in the range [1, n] sorted in lexicographical order. You must write an algorithm that runs in O(n) time and uses O(1) extra space. ", + "category": [ + "Depth-First Search", + "Trie" + ], + "complexity": "Medium", + "successrate": 58.7, + "totalsubmissions": 140350, + "totalaccepted": 82427, + "likes": 1197, + "dislikes": 113, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 13", + "expected_output": "[1,10,11,12,13,2,3,4,5,6,7,8,9]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "n = 2", + "expected_output": "[1,2]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b99", + "questionid": 206, + "title": "Longest Substring with At Least K Repeating Characters", + "slug": "longest-substring-with-at-least-k-repeating-characters", + "description": "Given a string s and an integer k, return the length of the longest substring of s such that the frequency of each character in this substring is greater than or equal to k. ", + "category": [ + "Hash Table", + "String", + "Divide and Conquer", + "Sliding Window" + ], + "complexity": "Medium", + "successrate": 44.5, + "totalsubmissions": 345377, + "totalaccepted": 153849, + "likes": 3853, + "dislikes": 321, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "aaabb", k = 3", + "expected_output": "3", + "explanation": "The longest substring is "aaa", as 'a' is repeated 3 times." + }, + { + "example_num": 2, + "expected_input": "s = "ababbc", k = 2", + "expected_output": "5", + "explanation": "The longest substring is "ababb", as 'a' is repeated 2 times and 'b' is repeated 3 times." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b9d", + "questionid": 210, + "title": "Frog Jump", + "slug": "frog-jump", + "description": "A frog is crossing a river. The river is divided into some number of units, and at each unit, there may or may not exist a stone. The frog can jump on a stone, but it must not jump into the water. Given a list of stones' positions (in units) in sorted ascending order, determine if the frog can cross the river by landing on the last stone. Initially, the frog is on the first stone and assumes the first jump must be 1 unit. If the frog's last jump was k units, its next jump must be either k - 1, k, or k + 1 units. The frog can only jump in the forward direction. ", + "category": [ + "Array", + "Dynamic Programming" + ], + "complexity": "Hard", + "successrate": 42.9, + "totalsubmissions": 353218, + "totalaccepted": 151515, + "likes": 2448, + "dislikes": 160, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "stones = [0,1,3,5,6,8,12,17]", + "expected_output": "true", + "explanation": "The frog can jump to the last stone by jumping 1 unit to the 2nd stone, then 2 units to the 3rd stone, then 2 units to the 4th stone, then 3 units to the 6th stone, 4 units to the 7th stone, and 5 units to the 8th stone." + }, + { + "example_num": 2, + "expected_input": "stones = [0,1,2,3,4,8,9,11]", + "expected_output": "false", + "explanation": "There is no way to jump to the last stone as the gap between the 5th and 6th stone is too large." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b9e", + "questionid": 211, + "title": "Sum of Left Leaves", + "slug": "sum-of-left-leaves", + "description": "Given the root of a binary tree, return the sum of all left leaves. A leaf is a node with no children. A left leaf is a leaf that is the left child of another node. ", + "category": [ + "Tree", + "Depth-First Search", + "Breadth-First Search", + "Binary Tree" + ], + "complexity": "Easy", + "successrate": 55, + "totalsubmissions": 621755, + "totalaccepted": 341893, + "likes": 3236, + "dislikes": 244, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [3,9,20,null,null,15,7]", + "expected_output": "24", + "explanation": "There are two left leaves in the binary tree, with values 9 and 15 respectively." + }, + { + "example_num": 2, + "expected_input": "root = [1]", + "expected_output": "0", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720b9f", + "questionid": 212, + "title": "Queue Reconstruction by Height", + "slug": "queue-reconstruction-by-height", + "description": "You are given an array of people, people, which are the attributes of some people in a queue (not necessarily in order). Each people[i] = [hi, ki] represents the ith person of height hi with exactly ki other people in front who have a height greater than or equal to hi. Reconstruct and return the queue that is represented by the input array people. The returned queue should be formatted as an array queue, where queue[j] = [hj, kj] is the attributes of the jth person in the queue (queue[0] is the person at the front of the queue). ", + "category": [ + "Array", + "Greedy", + "Binary Indexed Tree", + "Segment Tree", + "Sorting" + ], + "complexity": "Medium", + "successrate": 70.1, + "totalsubmissions": 314990, + "totalaccepted": 220723, + "likes": 4787, + "dislikes": 511, + "hints": "What can you say about the position of the shortest person? \r\nIf the position of the shortest person is i, how many people would be in front of the shortest person? Once you fix the position of the shortest person, what can you say about the position of the second shortest person?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "people = [[7,0],[4,4],[7,1],[5,0],[6,1],[5,2]]", + "expected_output": "[[5,0],[7,0],[5,2],[6,1],[4,4],[7,1]]", + "explanation": "Person 0 has height 5 with no other people taller or the same height in front.\nPerson 1 has height 7 with no other people taller or the same height in front.\nPerson 2 has height 5 with two persons taller or the same height in front, which is person 0 and 1.\nPerson 3 has height 6 with one person taller or the same height in front, which is person 1.\nPerson 4 has height 4 with four people taller or the same height in front, which are people 0, 1, 2, and 3.\nPerson 5 has height 7 with one person taller or the same height in front, which is person 1.\nHence [[5,0],[7,0],[5,2],[6,1],[4,4],[7,1]] is the reconstructed queue." + }, + { + "example_num": 2, + "expected_input": "people = [[6,0],[5,0],[4,0],[3,2],[2,2],[1,4]]", + "expected_output": "[[4,0],[5,0],[2,2],[3,2],[1,4],[6,0]]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720ba0", + "questionid": 213, + "title": "Trapping Rain Water II", + "slug": "trapping-rain-water-ii", + "description": "Given an m x n integer matrix heightMap representing the height of each unit cell in a 2D elevation map, return the volume of water it can trap after raining. ", + "category": [ + "Array", + "Breadth-First Search", + "Heap (Priority Queue)", + "Matrix" + ], + "complexity": "Hard", + "successrate": 46.9, + "totalsubmissions": 145379, + "totalaccepted": 68250, + "likes": 2670, + "dislikes": 60, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "heightMap = [[1,4,3,1,3,2],[3,2,1,3,2,4],[2,3,3,2,3,1]]", + "expected_output": "4", + "explanation": "After the rain, water is trapped between the blocks.\nWe have two small ponds 1 and 3 units trapped.\nThe total volume of water trapped is 4." + }, + { + "example_num": 2, + "expected_input": "heightMap = [[3,3,3,3,3],[3,2,2,2,3],[3,2,1,2,3],[3,2,2,2,3],[3,3,3,3,3]]", + "expected_output": "10", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720ba4", + "questionid": 217, + "title": "Third Maximum Number", + "slug": "third-maximum-number", + "description": "Given an integer array nums, return the third distinct maximum number in this array. If the third maximum does not exist, return the maximum number. ", + "category": [ + "Array", + "Sorting" + ], + "complexity": "Easy", + "successrate": 31.8, + "totalsubmissions": 1005897, + "totalaccepted": 319648, + "likes": 1629, + "dislikes": 2274, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [3,2,1]", + "expected_output": "1", + "explanation": "The first distinct maximum is 3.\nThe second distinct maximum is 2.\nThe third distinct maximum is 1." + }, + { + "example_num": 2, + "expected_input": "nums = [1,2]", + "expected_output": "2", + "explanation": "The first distinct maximum is 2.\nThe second distinct maximum is 1.\nThe third distinct maximum does not exist, so the maximum (2) is returned instead." + }, + { + "example_num": 3, + "expected_input": "nums = [2,2,3,1]", + "expected_output": "1", + "explanation": "The first distinct maximum is 3.\nThe second distinct maximum is 2 (both 2's are counted together since they have the same value).\nThe third distinct maximum is 1." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720baa", + "questionid": 223, + "title": "Reconstruct Original Digits from English", + "slug": "reconstruct-original-digits-from-english", + "description": "Given a string s containing an out-of-order English representation of digits 0-9, return the digits in ascending order. ", + "category": [ + "Hash Table", + "Math", + "String" + ], + "complexity": "Medium", + "successrate": 51.2, + "totalsubmissions": 120508, + "totalaccepted": 61662, + "likes": 601, + "dislikes": 2013, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = \"owoztneoer\"", + "expected_output": "\"012\"", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "s = \"fviefuro\"", + "expected_output": "\"45\"", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720bac", + "questionid": 225, + "title": "Minimum Genetic Mutation", + "slug": "minimum-genetic-mutation", + "description": "A gene string can be represented by an 8-character long string, with choices from 'A', 'C', 'G', and 'T'. Suppose we need to investigate a mutation from a gene string start to a gene string end where one mutation is defined as one single character changed in the gene string. There is also a gene bank bank that records all the valid gene mutations. A gene must be in bank to make it a valid gene string. Given the two gene strings start and end and the gene bank bank, return the minimum number of mutations needed to mutate from start to end. If there is no such a mutation, return -1. Note that the starting point is assumed to be valid, so it might not be included in the bank. ", + "category": [ + "Hash Table", + "String", + "Breadth-First Search" + ], + "complexity": "Medium", + "successrate": 46.6, + "totalsubmissions": 113064, + "totalaccepted": 52704, + "likes": 868, + "dislikes": 102, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "startGene = "AACCGGTT", endGene = "AACCGGTA", bank = ["AACCGGTA"]", + "expected_output": "1", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "startGene = "AACCGGTT", endGene = "AAACGGTA", bank = ["AACCGGTA","AACCGCTA","AAACGGTA"]", + "expected_output": "2", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720bad", + "questionid": 226, + "title": "Number of Segments in a String", + "slug": "number-of-segments-in-a-string", + "description": "Given a string s, return the number of segments in the string. A segment is defined to be a contiguous sequence of non-space characters. ", + "category": [ + "String" + ], + "complexity": "Easy", + "successrate": 37.9, + "totalsubmissions": 301227, + "totalaccepted": 114139, + "likes": 433, + "dislikes": 1006, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "Hello, my name is John"", + "expected_output": "5", + "explanation": "The five segments are ["Hello,", "my", "name", "is", "John"]" + }, + { + "example_num": 2, + "expected_input": "s = "Hello"", + "expected_output": "1", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720bb0", + "questionid": 229, + "title": "Path Sum III", + "slug": "path-sum-iii", + "description": "Given the root of a binary tree and an integer targetSum, return the number of paths where the sum of the values along the path equals targetSum. The path does not need to start or end at the root or a leaf, but it must go downwards (i.e., traveling only from parent nodes to child nodes). ", + "category": [ + "Tree", + "Depth-First Search", + "Binary Tree" + ], + "complexity": "Medium", + "successrate": 50.2, + "totalsubmissions": 713399, + "totalaccepted": 357889, + "likes": 7352, + "dislikes": 359, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [10,5,-3,3,2,null,11,3,-2,null,1], targetSum = 8", + "expected_output": "3", + "explanation": "The paths that sum to 8 are shown." + }, + { + "example_num": 2, + "expected_input": "root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22", + "expected_output": "3", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720bb3", + "questionid": 232, + "title": "Arranging Coins", + "slug": "arranging-coins", + "description": "You have n coins and you want to build a staircase with these coins. The staircase consists of k rows where the ith row has exactly i coins. The last row of the staircase may be incomplete. Given the integer n, return the number of complete rows of the staircase you will build. ", + "category": [ + "Math", + "Binary Search" + ], + "complexity": "Easy", + "successrate": 45.3, + "totalsubmissions": 602006, + "totalaccepted": 272594, + "likes": 2139, + "dislikes": 1012, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 5", + "expected_output": "2", + "explanation": "Because the 3rd row is incomplete, we return 2." + }, + { + "example_num": 2, + "expected_input": "n = 8", + "expected_output": "3", + "explanation": "Because the 4th row is incomplete, we return 3." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720bb8", + "questionid": 237, + "title": "Find All Numbers Disappeared in an Array", + "slug": "find-all-numbers-disappeared-in-an-array", + "description": "Given an array nums of n integers where nums[i] is in the range [1, n], return an array of all the integers in the range [1, n] that do not appear in nums. ", + "category": [ + "Array", + "Hash Table" + ], + "complexity": "Easy", + "successrate": 59, + "totalsubmissions": 952265, + "totalaccepted": 561997, + "likes": 6409, + "dislikes": 376, + "hints": "This is a really easy problem if you decide to use additional memory. For those trying to write an initial solution using additional memory, think counters! However, the trick really is to not use any additional space than what is already available to use. Sometimes, multiple passes over the input array help find the solution. However, there's an interesting piece of information in this problem that makes it easy to re-use the input array itself for the solution. The problem specifies that the numbers in the array will be in the range [1, n] where n is the number of elements in the array. Can we use this information and modify the array in-place somehow to find what we need?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [4,3,2,7,8,2,3,1]", + "expected_output": "[5,6]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "nums = [1,1]", + "expected_output": "[2]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720bb9", + "questionid": 238, + "title": "Serialize and Deserialize BST", + "slug": "serialize-and-deserialize-bst", + "description": "Serialization is converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment. Design an algorithm to serialize and deserialize a binary search tree. There is no restriction on how your serialization/deserialization algorithm should work. You need to ensure that a binary search tree can be serialized to a string, and this string can be deserialized to the original tree structure. The encoded string should be as compact as possible. ", + "category": [ + "String", + "Tree", + "Depth-First Search", + "Breadth-First Search", + "Design", + "Binary Search Tree", + "Binary Tree" + ], + "complexity": "Medium", + "successrate": 56.1, + "totalsubmissions": 339893, + "totalaccepted": 190840, + "likes": 2633, + "dislikes": 129, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [2,1,3]", + "expected_output": "[2,1,3]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "root = []", + "expected_output": "[]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720bba", + "questionid": 239, + "title": "Sort Characters By Frequency", + "slug": "sort-characters-by-frequency", + "description": "Given a string s, sort it in decreasing order based on the frequency of the characters. The frequency of a character is the number of times it appears in the string. Return the sorted string. If there are multiple answers, return any of them. ", + "category": [ + "Hash Table", + "String", + "Sorting", + "Heap (Priority Queue)", + "Bucket Sort", + "Counting" + ], + "complexity": "Medium", + "successrate": 67.7, + "totalsubmissions": 524140, + "totalaccepted": 354883, + "likes": 4008, + "dislikes": 178, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "tree"", + "expected_output": ""eert"", + "explanation": "'e' appears twice while 'r' and 't' both appear once.\nSo 'e' must appear before both 'r' and 't'. Therefore "eetr" is also a valid answer." + }, + { + "example_num": 2, + "expected_input": "s = "cccaaa"", + "expected_output": ""aaaccc"", + "explanation": "Both 'c' and 'a' appear three times, so both "cccaaa" and "aaaccc" are valid answers.\nNote that "cacaca" is incorrect, as the same characters must be together." + }, + { + "example_num": 3, + "expected_input": "s = "Aabb"", + "expected_output": ""bbAa"", + "explanation": ""bbaA" is also a valid answer, but "Aabb" is incorrect.\nNote that 'A' and 'a' are treated as two different characters." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720bbc", + "questionid": 241, + "title": "Minimum Moves to Equal Array Elements", + "slug": "minimum-moves-to-equal-array-elements", + "description": "Given an integer array nums of size n, return the minimum number of moves required to make all array elements equal. In one move, you can increment n - 1 elements of the array by 1. ", + "category": [ + "Array", + "Math" + ], + "complexity": "Medium", + "successrate": 54, + "totalsubmissions": 224354, + "totalaccepted": 121115, + "likes": 1419, + "dislikes": 1548, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,2,3]", + "expected_output": "3", + "explanation": "Only three moves are needed (remember each move increments two elements):\n[1,2,3] => [2,3,3] => [3,4,3] => [4,4,4]" + }, + { + "example_num": 2, + "expected_input": "nums = [1,1,1]", + "expected_output": "0", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720bc1", + "questionid": 246, + "title": "Minimum Moves to Equal Array Elements II", + "slug": "minimum-moves-to-equal-array-elements-ii", + "description": "Given an integer array nums of size n, return the minimum number of moves required to make all array elements equal. In one move, you can increment or decrement an element of the array by 1. Test cases are designed so that the answer will fit in a 32-bit integer. ", + "category": [ + "Array", + "Math", + "Sorting" + ], + "complexity": "Medium", + "successrate": 56.9, + "totalsubmissions": 154692, + "totalaccepted": 88030, + "likes": 1373, + "dislikes": 73, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,2,3]", + "expected_output": "2", + "explanation": "Only two moves are needed (remember each move increments or decrements one element):\n[1,2,3] => [2,2,3] => [2,2,2]" + }, + { + "example_num": 2, + "expected_input": "nums = [1,10,2,9]", + "expected_output": "16", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720bc4", + "questionid": 249, + "title": "Count The Repetitions", + "slug": "count-the-repetitions", + "description": "We define str = [s, n] as the string str which consists of the string s concatenated n times. We define that string s1 can be obtained from string s2 if we can remove some characters from s2 such that it becomes s1. You are given two strings s1 and s2 and two integers n1 and n2. You have the two strings str1 = [s1, n1] and str2 = [s2, n2]. Return the maximum integer m such that str = [str2, m] can be obtained from str1. ", + "category": [ + "String", + "Dynamic Programming" + ], + "complexity": "Hard", + "successrate": 29, + "totalsubmissions": 48557, + "totalaccepted": 14067, + "likes": 292, + "dislikes": 260, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s1 = \"acb\", n1 = 4, s2 = \"ab\", n2 = 2", + "expected_output": "2", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "s1 = \"acb\", n1 = 1, s2 = \"acb\", n2 = 1", + "expected_output": "1", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720bca", + "questionid": 255, + "title": "Total Hamming Distance", + "slug": "total-hamming-distance", + "description": "The Hamming distance between two integers is the number of positions at which the corresponding bits are different. Given an integer array nums, return the sum of Hamming distances between all the pairs of the integers in nums. ", + "category": [ + "Array", + "Math", + "Bit Manipulation" + ], + "complexity": "Medium", + "successrate": 52, + "totalsubmissions": 167545, + "totalaccepted": 87042, + "likes": 1614, + "dislikes": 80, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [4,14,2]", + "expected_output": "6", + "explanation": "In binary representation, the 4 is 0100, 14 is 1110, and 2 is 0010 (just\nshowing the four bits relevant in this case).\nThe answer will be:\nHammingDistance(4, 14) + HammingDistance(4, 2) + HammingDistance(14, 2) = 2 + 2 + 2 = 6." + }, + { + "example_num": 2, + "expected_input": "nums = [4,14,4]", + "expected_output": "4", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720bd1", + "questionid": 262, + "title": "Reverse Pairs", + "slug": "reverse-pairs", + "description": "Given an integer array nums, return the number of reverse pairs in the array. A reverse pair is a pair (i, j) where 0 <= i < j < nums.length and nums[i] > 2 * nums[j]. ", + "category": [ + "Array", + "Binary Search", + "Divide and Conquer", + "Binary Indexed Tree", + "Segment Tree", + "Merge Sort", + "Ordered Set" + ], + "complexity": "Hard", + "successrate": 29.8, + "totalsubmissions": 270169, + "totalaccepted": 80624, + "likes": 2706, + "dislikes": 178, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,3,2,3,1]", + "expected_output": "2", + "explanation": "The reverse pairs are:\n(1, 4) --> nums[1] = 3, nums[4] = 1, 3 > 2 * 1\n(3, 4) --> nums[3] = 3, nums[4] = 1, 3 > 2 * 1" + }, + { + "example_num": 2, + "expected_input": "nums = [2,4,3,5,1]", + "expected_output": "3", + "explanation": "The reverse pairs are:\n(1, 4) --> nums[1] = 4, nums[4] = 1, 4 > 2 * 1\n(2, 4) --> nums[2] = 3, nums[4] = 1, 3 > 2 * 1\n(3, 4) --> nums[3] = 5, nums[4] = 1, 5 > 2 * 1" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720bd2", + "questionid": 263, + "title": "Target Sum", + "slug": "target-sum", + "description": "You are given an integer array nums and an integer target. You want to build an expression out of nums by adding one of the symbols '+' and '-' before each integer in nums and then concatenate all the integers. Return the number of different expressions that you can build, which evaluates to target. ", + "category": [ + "Array", + "Dynamic Programming", + "Backtracking" + ], + "complexity": "Medium", + "successrate": 45.4, + "totalsubmissions": 750493, + "totalaccepted": 340614, + "likes": 6621, + "dislikes": 253, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,1,1,1,1], target = 3", + "expected_output": "5", + "explanation": "There are 5 ways to assign symbols to make the sum of nums be target 3.\n-1 + 1 + 1 + 1 + 1 = 3\n+1 - 1 + 1 + 1 + 1 = 3\n+1 + 1 - 1 + 1 + 1 = 3\n+1 + 1 + 1 - 1 + 1 = 3\n+1 + 1 + 1 + 1 - 1 = 3" + }, + { + "example_num": 2, + "expected_input": "nums = [1], target = 1", + "expected_output": "1", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720bd7", + "questionid": 268, + "title": "Next Greater Element II", + "slug": "next-greater-element-ii", + "description": "Given a circular integer array nums (i.e., the next element of nums[nums.length - 1] is nums[0]), return the next greater number for every element in nums. The next greater number of a number x is the first greater number to its traversing-order next in the array, which means you could search circularly to find its next greater number. If it doesn't exist, return -1 for this number. ", + "category": [ + "Array", + "Stack", + "Monotonic Stack" + ], + "complexity": "Medium", + "successrate": 61.9, + "totalsubmissions": 341428, + "totalaccepted": 211511, + "likes": 4409, + "dislikes": 130, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,2,1]", + "expected_output": "[2,-1,2]\nExplanation: The first 1's next greater number is 2; \nThe number 2 can't find next greater number. \nThe second 1's next greater number needs to search circularly, which is also 2.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "nums = [1,2,3,4,3]", + "expected_output": "[2,3,4,-1,4]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720bd9", + "questionid": 270, + "title": "Perfect Number", + "slug": "perfect-number", + "description": "A perfect number is a positive integer that is equal to the sum of its positive divisors, excluding the number itself. A divisor of an integer x is an integer that can divide x evenly. Given an integer n, return true if n is a perfect number, otherwise return false. ", + "category": [ + "Math" + ], + "complexity": "Easy", + "successrate": 37.6, + "totalsubmissions": 269423, + "totalaccepted": 101225, + "likes": 543, + "dislikes": 836, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "num = 28", + "expected_output": "true", + "explanation": "28 = 1 + 2 + 4 + 7 + 14\n1, 2, 4, 7, and 14 are all divisors of 28." + }, + { + "example_num": 2, + "expected_input": "num = 7", + "expected_output": "false", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720bdc", + "questionid": 273, + "title": "Find Largest Value in Each Tree Row", + "slug": "find-largest-value-in-each-tree-row", + "description": "Given the root of a binary tree, return an array of the largest value in each row of the tree (0-indexed). ", + "category": [ + "Tree", + "Depth-First Search", + "Breadth-First Search", + "Binary Tree" + ], + "complexity": "Medium", + "successrate": 64.4, + "totalsubmissions": 291567, + "totalaccepted": 187850, + "likes": 1980, + "dislikes": 82, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [1,3,2,5,3,null,9]", + "expected_output": "[1,3,9]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "root = [1,2,3]", + "expected_output": "[1,3]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720bdd", + "questionid": 274, + "title": "Longest Palindromic Subsequence", + "slug": "longest-palindromic-subsequence", + "description": "Given a string s, find the longest palindromic subsequence's length in s. A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements. ", + "category": [ + "String", + "Dynamic Programming" + ], + "complexity": "Medium", + "successrate": 59.3, + "totalsubmissions": 418537, + "totalaccepted": 248026, + "likes": 5039, + "dislikes": 246, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "bbbab"", + "expected_output": "4", + "explanation": "One possible longest palindromic subsequence is "bbbb"." + }, + { + "example_num": 2, + "expected_input": "s = "cbbd"", + "expected_output": "2", + "explanation": "One possible longest palindromic subsequence is "bb"." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720bde", + "questionid": 275, + "title": "Super Washing Machines", + "slug": "super-washing-machines", + "description": "You have n super washing machines on a line. Initially, each washing machine has some dresses or is empty. For each move, you could choose any m (1 <= m <= n) washing machines, and pass one dress of each washing machine to one of its adjacent washing machines at the same time. Given an integer array machines representing the number of dresses in each washing machine from left to right on the line, return the minimum number of moves to make all the washing machines have the same number of dresses. If it is not possible to do it, return -1. ", + "category": [ + "Array", + "Greedy" + ], + "complexity": "Hard", + "successrate": 39.4, + "totalsubmissions": 55433, + "totalaccepted": 21827, + "likes": 530, + "dislikes": 178, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "machines = [1,0,5]", + "expected_output": "3", + "explanation": "1st move: 1 0 <-- 5 => 1 1 4\n2nd move: 1 <-- 1 <-- 4 => 2 1 3\n3rd move: 2 1 <-- 3 => 2 2 2" + }, + { + "example_num": 2, + "expected_input": "machines = [0,3,0]", + "expected_output": "2", + "explanation": "1st move: 0 <-- 3 0 => 1 2 0\n2nd move: 1 2 --> 0 => 1 1 1" + }, + { + "example_num": 3, + "expected_input": "machines = [0,2,0]", + "expected_output": "-1", + "explanation": "It's impossible to make all three washing machines have the same number of dresses." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720be6", + "questionid": 283, + "title": "Minimum Absolute Difference in BST", + "slug": "minimum-absolute-difference-in-bst", + "description": "Given the root of a Binary Search Tree (BST), return the minimum absolute difference between the values of any two different nodes in the tree. ", + "category": [ + "Tree", + "Depth-First Search", + "Breadth-First Search", + "Binary Search Tree", + "Binary Tree" + ], + "complexity": "Easy", + "successrate": 56.2, + "totalsubmissions": 273418, + "totalaccepted": 153691, + "likes": 1994, + "dislikes": 117, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [4,2,6,1,3]", + "expected_output": "1", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "root = [1,0,48,null,null,12,49]", + "expected_output": "1", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720bea", + "questionid": 287, + "title": "Diameter of Binary Tree", + "slug": "diameter-of-binary-tree", + "description": "Given the root of a binary tree, return the length of the diameter of the tree. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root. The length of a path between two nodes is represented by the number of edges between them. ", + "category": [ + "Tree", + "Depth-First Search", + "Binary Tree" + ], + "complexity": "Easy", + "successrate": 54.1, + "totalsubmissions": 1310070, + "totalaccepted": 708322, + "likes": 7587, + "dislikes": 481, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [1,2,3,4,5]", + "expected_output": "3", + "explanation": "3 is the length of the path [4,2,1,3] or [5,2,1,3]." + }, + { + "example_num": 2, + "expected_input": "root = [1,2]", + "expected_output": "1", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720bed", + "questionid": 290, + "title": "Brick Wall", + "slug": "brick-wall", + "description": "There is a rectangular brick wall in front of you with n rows of bricks. The ith row has some number of bricks each of the same height (i.e., one unit) but they can be of different widths. The total width of each row is the same. Draw a vertical line from the top to the bottom and cross the least bricks. If your line goes through the edge of a brick, then the brick is not considered as crossed. You cannot draw a line just along one of the two vertical edges of the wall, in which case the line will obviously cross no bricks. Given the 2D array wall that contains the information about the wall, return the minimum number of crossed bricks after drawing such a vertical line. ", + "category": [ + "Array", + "Hash Table" + ], + "complexity": "Medium", + "successrate": 52.6, + "totalsubmissions": 189678, + "totalaccepted": 99768, + "likes": 1789, + "dislikes": 101, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "wall = [[1,2,2,1],[3,1,2],[1,3,2],[2,4],[3,1,2],[1,3,1,1]]", + "expected_output": "2", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "wall = [[1],[1],[1]]", + "expected_output": "3", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720bee", + "questionid": 291, + "title": "Next Greater Element III", + "slug": "next-greater-element-iii", + "description": "Given a positive integer n, find the smallest integer which has exactly the same digits existing in the integer n and is greater in value than n. If no such positive integer exists, return -1. Note that the returned integer should fit in 32-bit integer, if there is a valid answer but it does not fit in 32-bit integer, return -1. ", + "category": [ + "Math", + "Two Pointers", + "String" + ], + "complexity": "Medium", + "successrate": 33.8, + "totalsubmissions": 285936, + "totalaccepted": 96588, + "likes": 2171, + "dislikes": 342, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 12", + "expected_output": "21", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "n = 21", + "expected_output": "-1", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720bf8", + "questionid": 301, + "title": "Out of Boundary Paths", + "slug": "out-of-boundary-paths", + "description": "There is an m x n grid with a ball. The ball is initially at the position [startRow, startColumn]. You are allowed to move the ball to one of the four adjacent cells in the grid (possibly out of the grid crossing the grid boundary). You can apply at most maxMove moves to the ball. Given the five integers m, n, maxMove, startRow, startColumn, return the number of paths to move the ball out of the grid boundary. Since the answer can be very large, return it modulo 109 + 7. ", + "category": [ + "Dynamic Programming" + ], + "complexity": "Medium", + "successrate": 40.1, + "totalsubmissions": 157850, + "totalaccepted": 63268, + "likes": 1475, + "dislikes": 182, + "hints": "Is traversing every path feasible? There are many possible paths for a small matrix. Try to optimize it. Can we use some space to store the number of paths and update them after every move? One obvious thing: the ball will go out of the boundary only by crossing it. Also, there is only one possible way the ball can go out of the boundary from the boundary cell except for corner cells. From the corner cell, the ball can go out in two different ways.\r\n\r\nCan you use this thing to solve the problem?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "m = 2, n = 2, maxMove = 2, startRow = 0, startColumn = 0", + "expected_output": "6", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "m = 1, n = 3, maxMove = 3, startRow = 0, startColumn = 1", + "expected_output": "12", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720bf9", + "questionid": 302, + "title": "Shortest Unsorted Continuous Subarray", + "slug": "shortest-unsorted-continuous-subarray", + "description": "Given an integer array nums, you need to find one continuous subarray that if you only sort this subarray in ascending order, then the whole array will be sorted in ascending order. Return the shortest such subarray and output its length. ", + "category": [ + "Array", + "Two Pointers", + "Stack", + "Greedy", + "Sorting", + "Monotonic Stack" + ], + "complexity": "Medium", + "successrate": 34.2, + "totalsubmissions": 631258, + "totalaccepted": 215582, + "likes": 4950, + "dislikes": 201, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [2,6,4,8,10,9,15]", + "expected_output": "5", + "explanation": "You need to sort [6, 4, 8, 10, 9] in ascending order to make the whole array sorted in ascending order." + }, + { + "example_num": 2, + "expected_input": "nums = [1,2,3,4]", + "expected_output": "0", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "nums = [1]", + "expected_output": "0", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c03", + "questionid": 312, + "title": "Construct String from Binary Tree", + "slug": "construct-string-from-binary-tree", + "description": "Given the root of a binary tree, construct a string consisting of parenthesis and integers from a binary tree with the preorder traversal way, and return it. Omit all the empty parenthesis pairs that do not affect the one-to-one mapping relationship between the string and the original binary tree. ", + "category": [ + "String", + "Tree", + "Depth-First Search", + "Binary Tree" + ], + "complexity": "Easy", + "successrate": 57.6, + "totalsubmissions": 220994, + "totalaccepted": 127369, + "likes": 1343, + "dislikes": 1714, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [1,2,3,4]", + "expected_output": ""1(2(4))(3)"", + "explanation": "Originally, it needs to be "1(2(4)())(3()())", but you need to omit all the empty parenthesis pairs. And it will be "1(2(4))(3)"." + }, + { + "example_num": 2, + "expected_input": "root = [1,2,3,null,4]", + "expected_output": ""1(2()(4))(3)"", + "explanation": "Almost the same as the first example, except the () after 2 is necessary to indicate the absence of a left child for 2 and the presence of a right child." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c0a", + "questionid": 319, + "title": "Sum of Square Numbers", + "slug": "sum-of-square-numbers", + "description": "Given a non-negative integer c, decide whether there're two integers a and b such that a2 + b2 = c. ", + "category": [ + "Math", + "Two Pointers", + "Binary Search" + ], + "complexity": "Medium", + "successrate": 34.6, + "totalsubmissions": 382523, + "totalaccepted": 132443, + "likes": 1360, + "dislikes": 462, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "c = 5", + "expected_output": "true", + "explanation": "1 * 1 + 2 * 2 = 5" + }, + { + "example_num": 2, + "expected_input": "c = 3", + "expected_output": "false", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720bcf", + "questionid": 260, + "title": "Max Consecutive Ones", + "slug": "max-consecutive-ones", + "description": "Given a binary array nums, return the maximum number of consecutive 1's in the array. ", + "category": [ + "Array" + ], + "complexity": "Easy", + "successrate": 55, + "totalsubmissions": 1160124, + "totalaccepted": 638413, + "likes": 2517, + "dislikes": 395, + "hints": "You need to think about two things as far as any window is concerned. One is the starting point for the window. How do you detect that a new window of 1s has started? The next part is detecting the ending point for this window.\r\n\r\nHow do you detect the ending point for an existing window? If you figure these two things out, you will be able to detect the windows of consecutive ones. All that remains afterward is to find the longest such window and return the size.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,1,0,1,1,1]", + "expected_output": "3", + "explanation": "The first two digits or the last three digits are consecutive 1s. The maximum number of consecutive 1s is 3." + }, + { + "example_num": 2, + "expected_input": "nums = [1,0,1,1,0,1]", + "expected_output": "2", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720bd3", + "questionid": 264, + "title": "Teemo Attacking", + "slug": "teemo-attacking", + "description": "Our hero Teemo is attacking an enemy Ashe with poison attacks! When Teemo attacks Ashe, Ashe gets poisoned for a exactly duration seconds. More formally, an attack at second t will mean Ashe is poisoned during the inclusive time interval [t, t + duration - 1]. If Teemo attacks again before the poison effect ends, the timer for it is reset, and the poison effect will end duration seconds after the new attack. You are given a non-decreasing integer array timeSeries, where timeSeries[i] denotes that Teemo attacks Ashe at second timeSeries[i], and an integer duration. Return the total number of seconds that Ashe is poisoned. ", + "category": [ + "Array", + "Simulation" + ], + "complexity": "Easy", + "successrate": 56.8, + "totalsubmissions": 171664, + "totalaccepted": 97561, + "likes": 396, + "dislikes": 37, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "timeSeries = [1,4], duration = 2", + "expected_output": "4", + "explanation": "Teemo's attacks on Ashe go as follows:\n- At second 1, Teemo attacks, and Ashe is poisoned for seconds 1 and 2.\n- At second 4, Teemo attacks, and Ashe is poisoned for seconds 4 and 5.\nAshe is poisoned for seconds 1, 2, 4, and 5, which is 4 seconds in total." + }, + { + "example_num": 2, + "expected_input": "timeSeries = [1,2], duration = 2", + "expected_output": "3", + "explanation": "Teemo's attacks on Ashe go as follows:\n- At second 1, Teemo attacks, and Ashe is poisoned for seconds 1 and 2.\n- At second 2 however, Teemo attacks again and resets the poison timer. Ashe is poisoned for seconds 2 and 3.\nAshe is poisoned for seconds 1, 2, and 3, which is 3 seconds in total." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720bd5", + "questionid": 266, + "title": "Diagonal Traverse", + "slug": "diagonal-traverse", + "description": "Given an m x n matrix mat, return an array of all the elements of the array in a diagonal order. ", + "category": [ + "Array", + "Matrix", + "Simulation" + ], + "complexity": "Medium", + "successrate": 56.5, + "totalsubmissions": 344843, + "totalaccepted": 194981, + "likes": 2118, + "dislikes": 524, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "mat = [[1,2,3],[4,5,6],[7,8,9]]", + "expected_output": "[1,2,4,7,5,3,6,8,9]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "mat = [[1,2],[3,4]]", + "expected_output": "[1,2,3,4]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720bdb", + "questionid": 272, + "title": "Find Bottom Left Tree Value", + "slug": "find-bottom-left-tree-value", + "description": "Given the root of a binary tree, return the leftmost value in the last row of the tree. ", + "category": [ + "Tree", + "Depth-First Search", + "Breadth-First Search", + "Binary Tree" + ], + "complexity": "Medium", + "successrate": 65.2, + "totalsubmissions": 259658, + "totalaccepted": 169188, + "likes": 2052, + "dislikes": 213, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [2,1,3]", + "expected_output": "1", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "root = [1,2,3,4,null,5,6,null,null,7]", + "expected_output": "7", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720be4", + "questionid": 281, + "title": "Contiguous Array", + "slug": "contiguous-array", + "description": "Given a binary array nums, return the maximum length of a contiguous subarray with an equal number of 0 and 1. ", + "category": [ + "Array", + "Hash Table", + "Prefix Sum" + ], + "complexity": "Medium", + "successrate": 46.3, + "totalsubmissions": 558046, + "totalaccepted": 258336, + "likes": 5250, + "dislikes": 227, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [0,1]", + "expected_output": "2", + "explanation": "[0, 1] is the longest contiguous subarray with an equal number of 0 and 1." + }, + { + "example_num": 2, + "expected_input": "nums = [0,1,0]", + "expected_output": "2", + "explanation": "[0, 1] (or [1, 0]) is a longest contiguous subarray with equal number of 0 and 1." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720be5", + "questionid": 282, + "title": "Swapping Nodes in a Linked List", + "slug": "swapping-nodes-in-a-linked-list", + "description": "You are given the head of a linked list, and an integer k. Return the head of the linked list after swapping the values of the kth node from the beginning and the kth node from the end (the list is 1-indexed). ", + "category": [ + "Linked List", + "Two Pointers" + ], + "complexity": "Medium", + "successrate": 68.4, + "totalsubmissions": 229189, + "totalaccepted": 156841, + "likes": 2691, + "dislikes": 100, + "hints": "We can transform the linked list to an array this should ease things up After transforming the linked list to an array it becomes as easy as swapping two integers in an array then rebuilding the linked list", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "head = [1,2,3,4,5], k = 2", + "expected_output": "[1,4,3,2,5]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "head = [7,9,6,6,7,8,3,0,9,5], k = 5", + "expected_output": "[7,9,6,6,8,7,3,0,9,5]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720bef", + "questionid": 292, + "title": "Reverse Words in a String III", + "slug": "reverse-words-in-a-string-iii", + "description": "Given a string s, reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order. ", + "category": [ + "Two Pointers", + "String" + ], + "complexity": "Easy", + "successrate": 78.5, + "totalsubmissions": 548465, + "totalaccepted": 430729, + "likes": 2698, + "dislikes": 160, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "Let's take LeetCode contest"", + "expected_output": ""s'teL ekat edoCteeL tsetnoc"", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "s = "Mr Ding"", + "expected_output": ""rM gniD"", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720bf7", + "questionid": 300, + "title": "Distribute Candies", + "slug": "distribute-candies", + "description": "Alice has n candies, where the ith candy is of type candyType[i]. Alice noticed that she started to gain weight, so she visited a doctor. The doctor advised Alice to only eat n / 2 of the candies she has (n is always even). Alice likes her candies very much, and she wants to eat the maximum number of different types of candies while still following the doctor's advice. Given the integer array candyType of length n, return the maximum number of different types of candies she can eat if she only eats n / 2 of them. ", + "category": [ + "Array", + "Hash Table" + ], + "complexity": "Easy", + "successrate": 65.6, + "totalsubmissions": 308181, + "totalaccepted": 202137, + "likes": 936, + "dislikes": 1147, + "hints": "To maximize the number of kinds of candies, we should try to distribute candies such that sister will gain all kinds. What is the upper limit of the number of kinds of candies sister will gain? Remember candies are to distributed equally. Which data structure is the most suitable for finding the number of kinds of candies? Will hashset solves the problem? Inserting all candies kind in the hashset and then checking its size with upper limit.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "candyType = [1,1,2,2,3,3]", + "expected_output": "3", + "explanation": "Alice can only eat 6 / 2 = 3 candies. Since there are only 3 types, she can eat one of each type." + }, + { + "example_num": 2, + "expected_input": "candyType = [1,1,2,3]", + "expected_output": "2", + "explanation": "Alice can only eat 4 / 2 = 2 candies. Whether she eats types [1,2], [1,3], or [2,3], she still can only eat 2 different types." + }, + { + "example_num": 3, + "expected_input": "candyType = [6,6,6,6]", + "expected_output": "1", + "explanation": "Alice can only eat 4 / 2 = 2 candies. Even though she can eat 2 candies, she only has 1 type." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720bfa", + "questionid": 303, + "title": "Delete Operation for Two Strings", + "slug": "delete-operation-for-two-strings", + "description": "Given two strings word1 and word2, return the minimum number of steps required to make word1 and word2 the same. In one step, you can delete exactly one character in either string. ", + "category": [ + "String", + "Dynamic Programming" + ], + "complexity": "Medium", + "successrate": 55.7, + "totalsubmissions": 203295, + "totalaccepted": 113212, + "likes": 2708, + "dislikes": 45, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "word1 = "sea", word2 = "eat"", + "expected_output": "2", + "explanation": "You need one step to make "sea" to "ea" and another step to make "eat" to "ea"." + }, + { + "example_num": 2, + "expected_input": "word1 = "leetcode", word2 = "etco"", + "expected_output": "4", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720bff", + "questionid": 308, + "title": "Range Addition II", + "slug": "range-addition-ii", + "description": "You are given an m x n matrix M initialized with all 0's and an array of operations ops, where ops[i] = [ai, bi] means M[x][y] should be incremented by one for all 0 <= x < ai and 0 <= y < bi. Count and return the number of maximum integers in the matrix after performing all the operations. ", + "category": [ + "Array", + "Math" + ], + "complexity": "Easy", + "successrate": 54.7, + "totalsubmissions": 141345, + "totalaccepted": 77261, + "likes": 649, + "dislikes": 803, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "m = 3, n = 3, ops = [[2,2],[3,3]]", + "expected_output": "4", + "explanation": "The maximum integer in M is 2, and there are four of it in M. So return 4." + }, + { + "example_num": 2, + "expected_input": "m = 3, n = 3, ops = [[2,2],[3,3],[3,3],[3,3],[2,2],[3,3],[3,3],[3,3],[2,2],[3,3],[3,3],[3,3]]", + "expected_output": "4", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "m = 3, n = 3, ops = []", + "expected_output": "9", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c01", + "questionid": 310, + "title": "Non-negative Integers without Consecutive Ones", + "slug": "non-negative-integers-without-consecutive-ones", + "description": "Given a positive integer n, return the number of the integers in the range [0, n] whose binary representations do not contain consecutive ones. ", + "category": [ + "Dynamic Programming" + ], + "complexity": "Hard", + "successrate": 38.8, + "totalsubmissions": 78458, + "totalaccepted": 30430, + "likes": 1055, + "dislikes": 114, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 5", + "expected_output": "5", + "explanation": "Here are the non-negative integers <= 5 with their corresponding binary representations:\n0 : 0\n1 : 1\n2 : 10\n3 : 11\n4 : 100\n5 : 101\nAmong them, only integer 3 disobeys the rule (two consecutive ones) and the other 5 satisfy the rule." + }, + { + "example_num": 2, + "expected_input": "n = 1", + "expected_output": "2", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "n = 2", + "expected_output": "3", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c02", + "questionid": 311, + "title": "Can Place Flowers", + "slug": "can-place-flowers", + "description": "You have a long flowerbed in which some of the plots are planted, and some are not. However, flowers cannot be planted in adjacent plots. Given an integer array flowerbed containing 0's and 1's, where 0 means empty and 1 means not empty, and an integer n, return if n new flowers can be planted in the flowerbed without violating the no-adjacent-flowers rule. ", + "category": [ + "Array", + "Greedy" + ], + "complexity": "Easy", + "successrate": 33.1, + "totalsubmissions": 874930, + "totalaccepted": 289310, + "likes": 2857, + "dislikes": 641, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "flowerbed = [1,0,0,0,1], n = 1", + "expected_output": "true", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "flowerbed = [1,0,0,0,1], n = 2", + "expected_output": "false", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c07", + "questionid": 316, + "title": "K Inverse Pairs Array", + "slug": "k-inverse-pairs-array", + "description": "For an integer array nums, an inverse pair is a pair of integers [i, j] where 0 <= i < j < nums.length and nums[i] > nums[j]. Given two integers n and k, return the number of different arrays consist of numbers from 1 to n such that there are exactly k inverse pairs. Since the answer can be huge, return it modulo 109 + 7. ", + "category": [ + "Dynamic Programming" + ], + "complexity": "Hard", + "successrate": 37.3, + "totalsubmissions": 66438, + "totalaccepted": 24766, + "likes": 752, + "dislikes": 108, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 3, k = 0", + "expected_output": "1", + "explanation": "Only the array [1,2,3] which consists of numbers from 1 to 3 has exactly 0 inverse pairs." + }, + { + "example_num": 2, + "expected_input": "n = 3, k = 1", + "expected_output": "2", + "explanation": "The array [1,3,2] and [2,1,3] have exactly 1 inverse pair." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720bce", + "questionid": 259, + "title": "Smallest Good Base", + "slug": "smallest-good-base", + "description": "Given an integer n represented as a string, return the smallest good base of n. We call k >= 2 a good base of n, if all digits of n base k are 1's. ", + "category": [ + "Math", + "Binary Search" + ], + "complexity": "Hard", + "successrate": 37.8, + "totalsubmissions": 44231, + "totalaccepted": 16728, + "likes": 265, + "dislikes": 429, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = "13"", + "expected_output": ""3"", + "explanation": "13 base 3 is 111." + }, + { + "example_num": 2, + "expected_input": "n = "4681"", + "expected_output": ""8"", + "explanation": "4681 base 8 is 11111." + }, + { + "example_num": 3, + "expected_input": "n = "1000000000000000000"", + "expected_output": ""999999999999999999"", + "explanation": "1000000000000000000 base 999999999999999999 is 11." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720bd4", + "questionid": 265, + "title": "Next Greater Element I", + "slug": "next-greater-element-i", + "description": "The next greater element of some element x in an array is the first greater element that is to the right of x in the same array. You are given two distinct 0-indexed integer arrays nums1 and nums2, where nums1 is a subset of nums2. For each 0 <= i < nums1.length, find the index j such that nums1[i] == nums2[j] and determine the next greater element of nums2[j] in nums2. If there is no next greater element, then the answer for this query is -1. Return an array ans of length nums1.length such that ans[i] is the next greater element as described above. ", + "category": [ + "Array", + "Hash Table", + "Stack", + "Monotonic Stack" + ], + "complexity": "Easy", + "successrate": 70, + "totalsubmissions": 496323, + "totalaccepted": 347209, + "likes": 2593, + "dislikes": 176, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums1 = [4,1,2], nums2 = [1,3,4,2]", + "expected_output": "[-1,3,-1]", + "explanation": "The next greater element for each value of nums1 is as follows:\n- 4 is underlined in nums2 = [1,3,4,2]. There is no next greater element, so the answer is -1.\n- 1 is underlined in nums2 = [1,3,4,2]. The next greater element is 3.\n- 2 is underlined in nums2 = [1,3,4,2]. There is no next greater element, so the answer is -1." + }, + { + "example_num": 2, + "expected_input": "nums1 = [2,4], nums2 = [1,2,3,4]", + "expected_output": "[3,-1]", + "explanation": "The next greater element for each value of nums1 is as follows:\n- 2 is underlined in nums2 = [1,2,3,4]. The next greater element is 3.\n- 4 is underlined in nums2 = [1,2,3,4]. There is no next greater element, so the answer is -1." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720bd8", + "questionid": 269, + "title": "Base 7", + "slug": "base-7", + "description": "Given an integer num, return a string of its base 7 representation. ", + "category": [ + "Math" + ], + "complexity": "Easy", + "successrate": 47.5, + "totalsubmissions": 178434, + "totalaccepted": 84670, + "likes": 464, + "dislikes": 192, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "num = 100", + "expected_output": "\"202\"", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "num = -7", + "expected_output": "\"-10\"", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720be3", + "questionid": 280, + "title": "Longest Word in Dictionary through Deleting", + "slug": "longest-word-in-dictionary-through-deleting", + "description": "Given a string s and a string array dictionary, return the longest string in the dictionary that can be formed by deleting some of the given string characters. If there is more than one possible result, return the longest word with the smallest lexicographical order. If there is no possible result, return the empty string. ", + "category": [ + "Array", + "Two Pointers", + "String", + "Sorting" + ], + "complexity": "Medium", + "successrate": 50.9, + "totalsubmissions": 245280, + "totalaccepted": 124739, + "likes": 1308, + "dislikes": 329, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "abpcplea", dictionary = ["ale","apple","monkey","plea"]", + "expected_output": ""apple"", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "s = "abpcplea", dictionary = ["a","b","c"]", + "expected_output": ""a"", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720be7", + "questionid": 284, + "title": "Single Element in a Sorted Array", + "slug": "single-element-in-a-sorted-array", + "description": "You are given a sorted array consisting of only integers where every element appears exactly twice, except for one element which appears exactly once. Return the single element that appears only once. Your solution must run in O(log n) time and O(1) space. ", + "category": [ + "Array", + "Binary Search" + ], + "complexity": "Medium", + "successrate": 58.7, + "totalsubmissions": 484707, + "totalaccepted": 284425, + "likes": 4963, + "dislikes": 111, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,1,2,3,3,4,4,8,8]", + "expected_output": "2", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "nums = [3,3,7,7,10,11,11]", + "expected_output": "10", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720beb", + "questionid": 288, + "title": "Remove Boxes", + "slug": "remove-boxes", + "description": "You are given several boxes with different colors represented by different positive numbers. You may experience several rounds to remove boxes until there is no box left. Each time you can choose some continuous boxes with the same color (i.e., composed of k boxes, k >= 1), remove them and get k * k points. Return the maximum points you can get. ", + "category": [ + "Array", + "Dynamic Programming", + "Memoization" + ], + "complexity": "Hard", + "successrate": 47.3, + "totalsubmissions": 71483, + "totalaccepted": 33844, + "likes": 1491, + "dislikes": 92, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "boxes = [1,3,2,2,2,3,4,3,1]", + "expected_output": "23", + "explanation": "[1, 3, 2, 2, 2, 3, 4, 3, 1] \n----> [1, 3, 3, 4, 3, 1] (3*3=9 points) \n----> [1, 3, 3, 3, 1] (1*1=1 points) \n----> [1, 1] (3*3=9 points) \n----> [] (2*2=4 points)" + }, + { + "example_num": 2, + "expected_input": "boxes = [1,1,1]", + "expected_output": "9", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "boxes = [1]", + "expected_output": "1", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720bec", + "questionid": 289, + "title": "Number of Provinces", + "slug": "number-of-provinces", + "description": "There are n cities. Some of them are connected, while some are not. If city a is connected directly with city b, and city b is connected directly with city c, then city a is connected indirectly with city c. A province is a group of directly or indirectly connected cities and no other cities outside of the group. You are given an n x n matrix isConnected where isConnected[i][j] = 1 if the ith city and the jth city are directly connected, and isConnected[i][j] = 0 otherwise. Return the total number of provinces. ", + "category": [ + "Depth-First Search", + "Breadth-First Search", + "Union Find", + "Graph" + ], + "complexity": "Medium", + "successrate": 62.6, + "totalsubmissions": 713510, + "totalaccepted": 446459, + "likes": 4990, + "dislikes": 235, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "isConnected = [[1,1,0],[1,1,0],[0,0,1]]", + "expected_output": "2", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "isConnected = [[1,0,0],[0,1,0],[0,0,1]]", + "expected_output": "3", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720bf2", + "questionid": 295, + "title": "Binary Tree Tilt", + "slug": "binary-tree-tilt", + "description": "Given the root of a binary tree, return the sum of every tree node's tilt. The tilt of a tree node is the absolute difference between the sum of all left subtree node values and all right subtree node values. If a node does not have a left child, then the sum of the left subtree node values is treated as 0. The rule is similar if the node does not have a right child. ", + "category": [ + "Tree", + "Depth-First Search", + "Binary Tree" + ], + "complexity": "Easy", + "successrate": 58.5, + "totalsubmissions": 282699, + "totalaccepted": 165284, + "likes": 1601, + "dislikes": 1903, + "hints": "Don't think too much, this is an easy problem. Take some small tree as an example. Can a parent node use the values of its child nodes? How will you implement it? May be recursion and tree traversal can help you in implementing. What about postorder traversal, using values of left and right childs?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [1,2,3]", + "expected_output": "1", + "explanation": "Tilt of node 2 : |0-0| = 0 (no children)\nTilt of node 3 : |0-0| = 0 (no children)\nTilt of node 1 : |2-3| = 1 (left subtree is just left child, so sum is 2; right subtree is just right child, so sum is 3)\nSum of every tilt : 0 + 0 + 1 = 1" + }, + { + "example_num": 2, + "expected_input": "root = [4,2,9,3,5,null,7]", + "expected_output": "15", + "explanation": "Tilt of node 3 : |0-0| = 0 (no children)\nTilt of node 5 : |0-0| = 0 (no children)\nTilt of node 7 : |0-0| = 0 (no children)\nTilt of node 2 : |3-5| = 2 (left subtree is just left child, so sum is 3; right subtree is just right child, so sum is 5)\nTilt of node 9 : |0-7| = 7 (no left child, so sum is 0; right subtree is just right child, so sum is 7)\nTilt of node 4 : |(3+5+2)-(9+7)| = |10-16| = 6 (left subtree values are 3, 5, and 2, which sums to 10; right subtree values are 9 and 7, which sums to 16)\nSum of every tilt : 0 + 0 + 0 + 2 + 7 + 6 = 15" + }, + { + "example_num": 3, + "expected_input": "root = [21,7,14,1,1,2,2,3,3]", + "expected_output": "9", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720bf3", + "questionid": 296, + "title": "Find the Closest Palindrome", + "slug": "find-the-closest-palindrome", + "description": "Given a string n representing an integer, return the closest integer (not including itself), which is a palindrome. If there is a tie, return the smaller one. The closest is defined as the absolute difference minimized between two integers. ", + "category": [ + "Math", + "String" + ], + "complexity": "Hard", + "successrate": 21.2, + "totalsubmissions": 145985, + "totalaccepted": 31011, + "likes": 474, + "dislikes": 1117, + "hints": "Will brute force work for this problem? Think of something else. Take some examples like 1234, 999,1000, etc and check their closest palindromes. How many different cases are possible? Do we have to consider only left half or right half of the string or both? Try to find the closest palindrome of these numbers- 12932, 99800, 12120. Did you observe something?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = "123"", + "expected_output": ""121"", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "n = "1"", + "expected_output": ""0"", + "explanation": "0 and 2 are the closest palindromes but we return the smallest which is 0." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720bf5", + "questionid": 298, + "title": "Permutation in String", + "slug": "permutation-in-string", + "description": "Given two strings s1 and s2, return true if s2 contains a permutation of s1, or false otherwise. In other words, return true if one of s1's permutations is the substring of s2. ", + "category": [ + "Hash Table", + "Two Pointers", + "String", + "Sliding Window" + ], + "complexity": "Medium", + "successrate": 44.8, + "totalsubmissions": 824372, + "totalaccepted": 369629, + "likes": 5663, + "dislikes": 164, + "hints": "Obviously, brute force will result in TLE. Think of something else. How will you check whether one string is a permutation of another string? One way is to sort the string and then compare. But, Is there a better way? If one string is a permutation of another string then they must one common metric. What is that? Both strings must have same character frequencies, if one is permutation of another. Which data structure should be used to store frequencies? What about hash table? An array of size 26?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s1 = "ab", s2 = "eidbaooo"", + "expected_output": "true", + "explanation": "s2 contains one permutation of s1 ("ba")." + }, + { + "example_num": 2, + "expected_input": "s1 = "ab", s2 = "eidboaoo"", + "expected_output": "false", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720bfc", + "questionid": 305, + "title": "Fraction Addition and Subtraction", + "slug": "fraction-addition-and-subtraction", + "description": "Given a string expression representing an expression of fraction addition and subtraction, return the calculation result in string format. The final result should be an irreducible fraction. If your final result is an integer, change it to the format of a fraction that has a denominator 1. So in this case, 2 should be converted to 2/1. ", + "category": [ + "Math", + "String", + "Simulation" + ], + "complexity": "Medium", + "successrate": 51.7, + "totalsubmissions": 55560, + "totalaccepted": 28714, + "likes": 303, + "dislikes": 435, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "expression = "-1/2+1/2"", + "expected_output": ""0/1"", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "expression = "-1/2+1/2+1/3"", + "expected_output": ""1/3"", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "expression = "1/3-1/2"", + "expected_output": ""-1/6"", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720bfd", + "questionid": 306, + "title": "Valid Square", + "slug": "valid-square", + "description": "Given the coordinates of four points in 2D space p1, p2, p3 and p4, return true if the four points construct a square. The coordinate of a point pi is represented as [xi, yi]. The input is not given in any order. A valid square has four equal sides with positive length and four equal angles (90-degree angles). ", + "category": [ + "Math", + "Geometry" + ], + "complexity": "Medium", + "successrate": 43.8, + "totalsubmissions": 186845, + "totalaccepted": 81890, + "likes": 674, + "dislikes": 739, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "p1 = [0,0], p2 = [1,1], p3 = [1,0], p4 = [0,1]", + "expected_output": "true", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "p1 = [0,0], p2 = [1,1], p3 = [1,0], p4 = [0,12]", + "expected_output": "false", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "p1 = [1,0], p2 = [-1,0], p3 = [0,1], p4 = [0,-1]", + "expected_output": "true", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c00", + "questionid": 309, + "title": "Minimum Index Sum of Two Lists", + "slug": "minimum-index-sum-of-two-lists", + "description": "Suppose Andy and Doris want to choose a restaurant for dinner, and they both have a list of favorite restaurants represented by strings. You need to help them find out their common interest with the least list index sum. If there is a choice tie between answers, output all of them with no order requirement. You could assume there always exists an answer. ", + "category": [ + "Array", + "Hash Table", + "String" + ], + "complexity": "Easy", + "successrate": 52.8, + "totalsubmissions": 279803, + "totalaccepted": 147774, + "likes": 1170, + "dislikes": 318, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "list1 = ["Shogun","Tapioca Express","Burger King","KFC"], list2 = ["Piatti","The Grill at Torrey Pines","Hungry Hunter Steakhouse","Shogun"]", + "expected_output": "["Shogun"]", + "explanation": "The only common string is "Shogun"." + }, + { + "example_num": 2, + "expected_input": "list1 = ["Shogun","Tapioca Express","Burger King","KFC"], list2 = ["KFC","Shogun","Burger King"]", + "expected_output": "["Shogun"]", + "explanation": "The common string with the least index sum is "Shogun" with index sum = (0 + 1) = 1." + }, + { + "example_num": 3, + "expected_input": "list1 = ["happy","sad","good"], list2 = ["sad","happy","good"]", + "expected_output": "["sad","happy"]", + "explanation": "There are three common strings:\n"happy" with index sum = (0 + 1) = 1.\n"sad" with index sum = (1 + 0) = 1.\n"good" with index sum = (2 + 2) = 4.\nThe strings with the least index sum are "sad" and "happy"." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c05", + "questionid": 314, + "title": "Task Scheduler", + "slug": "task-scheduler", + "description": "Given a characters array tasks, representing the tasks a CPU needs to do, where each letter represents a different task. Tasks could be done in any order. Each task is done in one unit of time. For each unit of time, the CPU could complete either one task or just be idle. However, there is a non-negative integer n that represents the cooldown period between two same tasks (the same letter in the array), that is that there must be at least n units of time between any two same tasks. Return the least number of units of times that the CPU will take to finish all the given tasks. ", + "category": [ + "Array", + "Hash Table", + "Greedy", + "Sorting", + "Heap (Priority Queue)", + "Counting" + ], + "complexity": "Medium", + "successrate": 54.4, + "totalsubmissions": 610179, + "totalaccepted": 332057, + "likes": 6262, + "dislikes": 1206, + "hints": "", + "deleted": false, + "examples": [] + }, + { + "_id": "66f925ddfdfb8e1665720c09", + "questionid": 318, + "title": "Smallest Range Covering Elements from K Lists", + "slug": "smallest-range-covering-elements-from-k-lists", + "description": "You have k lists of sorted integers in non-decreasing order. Find the smallest range that includes at least one number from each of the k lists. We define the range [a, b] is smaller than range [c, d] if b - a < d - c or a < c if b - a == d - c. ", + "category": [ + "Array", + "Hash Table", + "Greedy", + "Sliding Window", + "Sorting", + "Heap (Priority Queue)" + ], + "complexity": "Hard", + "successrate": 58.4, + "totalsubmissions": 109130, + "totalaccepted": 63761, + "likes": 2094, + "dislikes": 36, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [[4,10,15,24,26],[0,9,12,20],[5,18,22,30]]", + "expected_output": "[20,24]\nExplanation: \nList 1: [4, 10, 15, 24,26], 24 is in range [20,24].\nList 2: [0, 9, 12, 20], 20 is in range [20,24].\nList 3: [5, 18, 22, 30], 22 is in range [20,24].", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "nums = [[1,2,3],[1,2,3],[1,2,3]]", + "expected_output": "[1,1]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720bcc", + "questionid": 257, + "title": "Sliding Window Median", + "slug": "sliding-window-median", + "description": "The median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value. So the median is the mean of the two middle values. You are given an integer array nums and an integer k. There is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position. Return the median array for each window in the original array. Answers within 10-5 of the actual value will be accepted. ", + "category": [ + "Array", + "Hash Table", + "Sliding Window", + "Heap (Priority Queue)" + ], + "complexity": "Hard", + "successrate": 40.8, + "totalsubmissions": 252073, + "totalaccepted": 102947, + "likes": 2111, + "dislikes": 130, + "hints": "The simplest of solutions comes from the basic idea of finding the median given a set of numbers. We know that by definition, a median is the center element (or an average of the two center elements). Given an unsorted list of numbers, how do we find the median element? If you know the answer to this question, can we extend this idea to every sliding window that we come across in the array? Is there a better way to do what we are doing in the above hint? Don't you think there is duplication of calculation being done there? Is there some sort of optimization that we can do to achieve the same result? This approach is merely a modification of the basic approach except that it simply reduces duplication of calculations once done. The third line of thought is also based on this same idea but achieving the result in a different way. We obviously need the window to be sorted for us to be able to find the median. Is there a data-structure out there that we can use (in one or more quantities) to obtain the median element extremely fast, say O(1) time while having the ability to perform the other operations fairly efficiently as well?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,3,-1,-3,5,3,6,7], k = 3", + "expected_output": "[1.00000,-1.00000,-1.00000,3.00000,5.00000,6.00000]", + "explanation": "Window position Median\n--------------- -----\n[1 3 -1] -3 5 3 6 7 1\n 1 [3 -1 -3] 5 3 6 7 -1\n 1 3 [-1 -3 5] 3 6 7 -1\n 1 3 -1 [-3 5 3] 6 7 3\n 1 3 -1 -3 [5 3 6] 7 5\n 1 3 -1 -3 5 [3 6 7] 6" + }, + { + "example_num": 2, + "expected_input": "nums = [1,2,3,4,2,3,1,4,2], k = 3", + "expected_output": "[2.00000,3.00000,3.00000,3.00000,2.00000,3.00000,2.00000]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720bcd", + "questionid": 258, + "title": "License Key Formatting", + "slug": "license-key-formatting", + "description": "You are given a license key represented as a string s that consists of only alphanumeric characters and dashes. The string is separated into n + 1 groups by n dashes. You are also given an integer k. We want to reformat the string s such that each group contains exactly k characters, except for the first group, which could be shorter than k but still must contain at least one character. Furthermore, there must be a dash inserted between two groups, and you should convert all lowercase letters to uppercase. Return the reformatted license key. ", + "category": [ + "String" + ], + "complexity": "Easy", + "successrate": 43.1, + "totalsubmissions": 486859, + "totalaccepted": 209919, + "likes": 751, + "dislikes": 1077, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "5F3Z-2e-9-w", k = 4", + "expected_output": ""5F3Z-2E9W"", + "explanation": "The string s has been split into two parts, each part has 4 characters.\nNote that the two extra dashes are not needed and can be removed." + }, + { + "example_num": 2, + "expected_input": "s = "2-5g-3-J", k = 2", + "expected_output": ""2-5G-3J"", + "explanation": "The string s has been split into three parts, each part has 2 characters except the first part as it could be shorter as mentioned above." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720bd6", + "questionid": 267, + "title": "IPO", + "slug": "ipo", + "description": "Suppose LeetCode will start its IPO soon. In order to sell a good price of its shares to Venture Capital, LeetCode would like to work on some projects to increase its capital before the IPO. Since it has limited resources, it can only finish at most k distinct projects before the IPO. Help LeetCode design the best way to maximize its total capital after finishing at most k distinct projects. You are given n projects where the ith project has a pure profit profits[i] and a minimum capital of capital[i] is needed to start it. Initially, you have w capital. When you finish a project, you will obtain its pure profit and the profit will be added to your total capital. Pick a list of at most k distinct projects from given projects to maximize your final capital, and return the final maximized capital. The answer is guaranteed to fit in a 32-bit signed integer. ", + "category": [ + "Array", + "Greedy", + "Sorting", + "Heap (Priority Queue)" + ], + "complexity": "Hard", + "successrate": 44, + "totalsubmissions": 73070, + "totalaccepted": 32171, + "likes": 775, + "dislikes": 70, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "k = 2, w = 0, profits = [1,2,3], capital = [0,1,1]", + "expected_output": "4", + "explanation": "Since your initial capital is 0, you can only start the project indexed 0.\nAfter finishing it you will obtain profit 1 and your capital becomes 1.\nWith capital 1, you can either start the project indexed 1 or the project indexed 2.\nSince you can choose at most 2 projects, you need to finish the project indexed 2 to get the maximum capital.\nTherefore, output the final maximized capital, which is 0 + 1 + 3 = 4." + }, + { + "example_num": 2, + "expected_input": "k = 3, w = 0, profits = [1,2,3], capital = [0,1,2]", + "expected_output": "6", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720bda", + "questionid": 271, + "title": "Most Frequent Subtree Sum", + "slug": "most-frequent-subtree-sum", + "description": "Given the root of a binary tree, return the most frequent subtree sum. If there is a tie, return all the values with the highest frequency in any order. The subtree sum of a node is defined as the sum of all the node values formed by the subtree rooted at that node (including the node itself). ", + "category": [ + "Hash Table", + "Tree", + "Depth-First Search", + "Binary Tree" + ], + "complexity": "Medium", + "successrate": 62.7, + "totalsubmissions": 169666, + "totalaccepted": 106337, + "likes": 1455, + "dislikes": 222, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [5,2,-3]", + "expected_output": "[2,-3,4]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "root = [5,2,-5]", + "expected_output": "[2]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720be0", + "questionid": 277, + "title": "Longest Uncommon Subsequence I", + "slug": "longest-uncommon-subsequence-i", + "description": "Given two strings a and b, return the length of the longest uncommon subsequence between a and b. If the longest uncommon subsequence does not exist, return -1. An uncommon subsequence between two strings is a string that is a subsequence of one but not the other. A subsequence of a string s is a string that can be obtained after deleting any number of characters from s. ", + "category": [ + "String" + ], + "complexity": "Easy", + "successrate": 60.1, + "totalsubmissions": 138850, + "totalaccepted": 83443, + "likes": 570, + "dislikes": 5566, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "a = "aba", b = "cdc"", + "expected_output": "3", + "explanation": "One longest uncommon subsequence is "aba" because "aba" is a subsequence of "aba" but not "cdc".\nNote that "cdc" is also a longest uncommon subsequence." + }, + { + "example_num": 2, + "expected_input": "a = "aaa", b = "bbb"", + "expected_output": "3", + "explanation": " The longest uncommon subsequences are "aaa" and "bbb"." + }, + { + "example_num": 3, + "expected_input": "a = "aaa", b = "aaa"", + "expected_output": "-1", + "explanation": " Every subsequence of string a is also a subsequence of string b. Similarly, every subsequence of string b is also a subsequence of string a. So the answer would be -1." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720be1", + "questionid": 278, + "title": "Longest Uncommon Subsequence II", + "slug": "longest-uncommon-subsequence-ii", + "description": "Given an array of strings strs, return the length of the longest uncommon subsequence between them. If the longest uncommon subsequence does not exist, return -1. An uncommon subsequence between an array of strings is a string that is a subsequence of one string but not the others. A subsequence of a string s is a string that can be obtained after deleting any number of characters from s. ", + "category": [ + "Array", + "Hash Table", + "Two Pointers", + "String", + "Sorting" + ], + "complexity": "Medium", + "successrate": 40.1, + "totalsubmissions": 106746, + "totalaccepted": 42789, + "likes": 367, + "dislikes": 1065, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "strs = [\"aba\",\"cdc\",\"eae\"]", + "expected_output": "3", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "strs = [\"aaa\",\"aaa\",\"aa\"]", + "expected_output": "-1", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720be2", + "questionid": 279, + "title": "Continuous Subarray Sum", + "slug": "continuous-subarray-sum", + "description": "Given an integer array nums and an integer k, return true if nums has a continuous subarray of size at least two whose elements sum up to a multiple of k, or false otherwise. An integer x is a multiple of k if there exists an integer n such that x = n * k. 0 is always a multiple of k. ", + "category": [ + "Array", + "Hash Table", + "Math", + "Prefix Sum" + ], + "complexity": "Medium", + "successrate": 27.2, + "totalsubmissions": 1047671, + "totalaccepted": 285001, + "likes": 1762, + "dislikes": 245, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [23,2,4,6,7], k = 6", + "expected_output": "true", + "explanation": "[2, 4] is a continuous subarray of size 2 whose elements sum up to 6." + }, + { + "example_num": 2, + "expected_input": "nums = [23,2,6,4,7], k = 6", + "expected_output": "true", + "explanation": "[23, 2, 6, 4, 7] is an continuous subarray of size 5 whose elements sum up to 42.\n42 is a multiple of 6 because 42 = 7 * 6 and 7 is an integer." + }, + { + "example_num": 3, + "expected_input": "nums = [23,2,6,4,7], k = 13", + "expected_output": "false", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720be8", + "questionid": 285, + "title": "Reverse String II", + "slug": "reverse-string-ii", + "description": "Given a string s and an integer k, reverse the first k characters for every 2k characters counting from the start of the string. If there are fewer than k characters left, reverse all of them. If there are less than 2k but greater than or equal to k characters, then reverse the first k characters and leave the other as original. ", + "category": [ + "Two Pointers", + "String" + ], + "complexity": "Easy", + "successrate": 50.1, + "totalsubmissions": 297991, + "totalaccepted": 149401, + "likes": 952, + "dislikes": 2363, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = \"abcdefg\", k = 2", + "expected_output": "\"bacdfeg\"", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "s = \"abcd\", k = 2", + "expected_output": "\"bacd\"", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720be9", + "questionid": 286, + "title": "01 Matrix", + "slug": "01-matrix", + "description": "Given an m x n binary matrix mat, return the distance of the nearest 0 for each cell. The distance between two adjacent cells is 1. ", + "category": [ + "Array", + "Dynamic Programming", + "Breadth-First Search", + "Matrix" + ], + "complexity": "Medium", + "successrate": 43.8, + "totalsubmissions": 534554, + "totalaccepted": 233903, + "likes": 4442, + "dislikes": 221, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "mat = [[0,0,0],[0,1,0],[0,0,0]]", + "expected_output": "[[0,0,0],[0,1,0],[0,0,0]]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "mat = [[0,0,0],[0,1,0],[1,1,1]]", + "expected_output": "[[0,0,0],[0,1,0],[1,2,1]]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720bf0", + "questionid": 293, + "title": "Subarray Sum Equals K", + "slug": "subarray-sum-equals-k", + "description": "Given an array of integers nums and an integer k, return the total number of subarrays whose sum equals to k. ", + "category": [ + "Array", + "Hash Table", + "Prefix Sum" + ], + "complexity": "Medium", + "successrate": 44.2, + "totalsubmissions": 1715764, + "totalaccepted": 758711, + "likes": 12822, + "dislikes": 409, + "hints": "Will Brute force work here? Try to optimize it. Can we optimize it by using some extra space? What about storing sum frequencies in a hash table? Will it be useful? sum(i,j)=sum(0,j)-sum(0,i), where sum(i,j) represents the sum of all the elements from index i to j-1.\r\n\r\nCan we use this property to optimize it.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,1,1], k = 2", + "expected_output": "2", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "nums = [1,2,3], k = 3", + "expected_output": "2", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720bf4", + "questionid": 297, + "title": "Reshape the Matrix", + "slug": "reshape-the-matrix", + "description": "In MATLAB, there is a handy function called reshape which can reshape an m x n matrix into a new one with a different size r x c keeping its original data. You are given an m x n matrix mat and two integers r and c representing the number of rows and the number of columns of the wanted reshaped matrix. The reshaped matrix should be filled with all the elements of the original matrix in the same row-traversing order as they were. If the reshape operation with given parameters is possible and legal, output the new reshaped matrix; Otherwise, output the original matrix. ", + "category": [ + "Array", + "Matrix", + "Simulation" + ], + "complexity": "Easy", + "successrate": 62.4, + "totalsubmissions": 365645, + "totalaccepted": 228101, + "likes": 2155, + "dislikes": 243, + "hints": "Do you know how 2d matrix is stored in 1d memory? Try to map 2-dimensions into one. M[i][j]=M[n*i+j] , where n is the number of cols. \r\nThis is the one way of converting 2-d indices into one 1-d index. \r\nNow, how will you convert 1-d index into 2-d indices? Try to use division and modulus to convert 1-d index into 2-d indices. M[i] => M[i/n][i%n] Will it result in right mapping? Take some example and check this formula.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "mat = [[1,2],[3,4]], r = 1, c = 4", + "expected_output": "[[1,2,3,4]]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "mat = [[1,2],[3,4]], r = 2, c = 4", + "expected_output": "[[1,2],[3,4]]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720bf6", + "questionid": 299, + "title": "Subtree of Another Tree", + "slug": "subtree-of-another-tree", + "description": "Given the roots of two binary trees root and subRoot, return true if there is a subtree of root with the same structure and node values of subRoot and false otherwise. A subtree of a binary tree tree is a tree that consists of a node in tree and all of this node's descendants. The tree tree could also be considered as a subtree of itself. ", + "category": [ + "Tree", + "Depth-First Search", + "String Matching", + "Binary Tree", + "Hash Function" + ], + "complexity": "Easy", + "successrate": 45.3, + "totalsubmissions": 996628, + "totalaccepted": 451495, + "likes": 5105, + "dislikes": 265, + "hints": "Which approach is better here- recursive or iterative? If recursive approach is better, can you write recursive function with its parameters? Two trees s and t are said to be identical if their root values are same and their left and right subtrees are identical. Can you write this in form of recursive formulae? Recursive formulae can be: \r\nisIdentical(s,t)= s.val==t.val AND isIdentical(s.left,t.left) AND isIdentical(s.right,t.right)", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [3,4,5,1,2], subRoot = [4,1,2]", + "expected_output": "true", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "root = [3,4,5,1,2,null,null,null,null,0], subRoot = [4,1,2]", + "expected_output": "false", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720bfb", + "questionid": 304, + "title": "Erect the Fence", + "slug": "erect-the-fence", + "description": "You are given an array trees where trees[i] = [xi, yi] represents the location of a tree in the garden. You are asked to fence the entire garden using the minimum length of rope as it is expensive. The garden is well fenced only if all the trees are enclosed. Return the coordinates of trees that are exactly located on the fence perimeter. ", + "category": [ + "Array", + "Math", + "Geometry" + ], + "complexity": "Hard", + "successrate": 43.2, + "totalsubmissions": 55809, + "totalaccepted": 24131, + "likes": 550, + "dislikes": 344, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "trees = [[1,1],[2,2],[2,0],[2,4],[3,3],[4,2]]", + "expected_output": "[[1,1],[2,0],[4,2],[3,3],[2,4]]", + "explanation": "All the trees will be on the perimeter of the fence except the tree at [2, 2], which will be inside the fence." + }, + { + "example_num": 2, + "expected_input": "trees = [[1,2],[2,2],[4,2]]", + "expected_output": "[[4,2],[2,2],[1,2]]", + "explanation": "The fence forms a line that passes through all the trees." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720bfe", + "questionid": 307, + "title": "Longest Harmonious Subsequence", + "slug": "longest-harmonious-subsequence", + "description": "We define a harmonious array as an array where the difference between its maximum value and its minimum value is exactly 1. Given an integer array nums, return the length of its longest harmonious subsequence among all its possible subsequences. A subsequence of array is a sequence that can be derived from the array by deleting some or no elements without changing the order of the remaining elements. ", + "category": [ + "Array", + "Hash Table", + "Sorting" + ], + "complexity": "Easy", + "successrate": 52.6, + "totalsubmissions": 217843, + "totalaccepted": 114669, + "likes": 1522, + "dislikes": 151, + "hints": "", + "deleted": false, + "examples": [] + }, + { + "_id": "66f925ddfdfb8e1665720c04", + "questionid": 313, + "title": "Valid Triangle Number", + "slug": "valid-triangle-number", + "description": "Given an integer array nums, return the number of triplets chosen from the array that can make triangles if we take them as side lengths of a triangle. ", + "category": [ + "Array", + "Two Pointers", + "Binary Search", + "Greedy", + "Sorting" + ], + "complexity": "Medium", + "successrate": 49.7, + "totalsubmissions": 270227, + "totalaccepted": 134273, + "likes": 2468, + "dislikes": 150, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [2,2,3,4]", + "expected_output": "3", + "explanation": "Valid combinations are: \n2,3,4 (using the first 2)\n2,3,4 (using the second 2)\n2,2,3" + }, + { + "example_num": 2, + "expected_input": "nums = [4,2,3,4]", + "expected_output": "4", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c06", + "questionid": 315, + "title": "Maximum Product of Three Numbers", + "slug": "maximum-product-of-three-numbers", + "description": "Given an integer array nums, find three numbers whose product is maximum and return the maximum product. ", + "category": [ + "Array", + "Math", + "Sorting" + ], + "complexity": "Easy", + "successrate": 46.8, + "totalsubmissions": 437389, + "totalaccepted": 204489, + "likes": 2617, + "dislikes": 520, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,2,3]", + "expected_output": "6", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "nums = [1,2,3,4]", + "expected_output": "24", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "nums = [-1,-2,-3]", + "expected_output": "-6", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c08", + "questionid": 317, + "title": "Course Schedule III", + "slug": "course-schedule-iii", + "description": "There are n different online courses numbered from 1 to n. You are given an array courses where courses[i] = [durationi, lastDayi] indicate that the ith course should be taken continuously for durationi days and must be finished before or on lastDayi. You will start on the 1st day and you cannot take two or more courses simultaneously. Return the maximum number of courses that you can take. ", + "category": [ + "Array", + "Greedy", + "Heap (Priority Queue)" + ], + "complexity": "Hard", + "successrate": 35.7, + "totalsubmissions": 157006, + "totalaccepted": 56052, + "likes": 1903, + "dislikes": 54, + "hints": "During iteration, say I want to add the current course, currentTotalTime being total time of all courses taken till now, but adding the current course might exceed my deadline or it doesn€™t.\r\n\r\n1. If it doesn€™t, then I have added one new course. Increment the currentTotalTime with duration of current course. 2. If it exceeds deadline, I can swap current course with current courses that has biggest duration.\r\n* No harm done and I might have just reduced the currentTotalTime, right? \r\n* What preprocessing do I need to do on my course processing order so that this swap is always legal?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "courses = [[100,200],[200,1300],[1000,1250],[2000,3200]]", + "expected_output": "3\nExplanation: \nThere are totally 4 courses, but you can take 3 courses at most:\nFirst, take the 1st course, it costs 100 days so you will finish it on the 100th day, and ready to take the next course on the 101st day.\nSecond, take the 3rd course, it costs 1000 days so you will finish it on the 1100th day, and ready to take the next course on the 1101st day. \nThird, take the 2nd course, it costs 200 days so you will finish it on the 1300th day. \nThe 4th course cannot be taken now, since you will finish it on the 3300th day, which exceeds the closed date.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "courses = [[1,2]]", + "expected_output": "1", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "courses = [[3,2],[4,3]]", + "expected_output": "0", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c0b", + "questionid": 320, + "title": "Shopping Offers", + "slug": "shopping-offers", + "description": "In LeetCode Store, there are n items to sell. Each item has a price. However, there are some special offers, and a special offer consists of one or more different kinds of items with a sale price. You are given an integer array price where price[i] is the price of the ith item, and an integer array needs where needs[i] is the number of pieces of the ith item you want to buy. You are also given an array special where special[i] is of size n + 1 where special[i][j] is the number of pieces of the jth item in the ith offer and special[i][n] (i.e., the last integer in the array) is the price of the ith offer. Return the lowest price you have to pay for exactly certain items as given, where you could make optimal use of the special offers. You are not allowed to buy more items than you want, even if that would lower the overall price. You could use any of the special offers as many times as you want. ", + "category": [ + "Array", + "Dynamic Programming", + "Backtracking", + "Bit Manipulation", + "Memoization", + "Bitmask" + ], + "complexity": "Medium", + "successrate": 54.6, + "totalsubmissions": 83312, + "totalaccepted": 45471, + "likes": 983, + "dislikes": 633, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "price = [2,5], special = [[3,0,5],[1,2,10]], needs = [3,2]", + "expected_output": "14", + "explanation": "There are two kinds of items, A and B. Their prices are $2 and $5 respectively. \nIn special offer 1, you can pay $5 for 3A and 0B\nIn special offer 2, you can pay $10 for 1A and 2B. \nYou need to buy 3A and 2B, so you may pay $10 for 1A and 2B (special offer #2), and $4 for 2A." + }, + { + "example_num": 2, + "expected_input": "price = [2,3,4], special = [[1,1,0,4],[2,2,1,9]], needs = [1,2,1]", + "expected_output": "11", + "explanation": "The price of A is $2, and $3 for B, $4 for C. \nYou may pay $4 for 1A and 1B, and $9 for 2A ,2B and 1C. \nYou need to buy 1A ,2B and 1C, so you may pay $4 for 1A and 1B (special offer #1), and $3 for 1B, $4 for 1C. \nYou cannot add more items, though only $9 for 2A ,2B and 1C." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c10", + "questionid": 325, + "title": "Palindromic Substrings", + "slug": "palindromic-substrings", + "description": "Given a string s, return the number of palindromic substrings in it. A string is a palindrome when it reads the same backward as forward. A substring is a contiguous sequence of characters within the string. ", + "category": [ + "String", + "Dynamic Programming" + ], + "complexity": "Medium", + "successrate": 64.6, + "totalsubmissions": 614298, + "totalaccepted": 396625, + "likes": 6149, + "dislikes": 153, + "hints": "How can we reuse a previously computed palindrome to compute a larger palindrome? If €œaba€ is a palindrome, is €œxabax€ and palindrome? Similarly is €œxabay€ a palindrome? Complexity based hint:\r\nIf we use brute-force and check whether for every start and end position a substring is a palindrome we have O(n^2) start - end pairs and O(n) palindromic checks. Can we reduce the time for palindromic checks to O(1) by reusing some previous computation?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "abc"", + "expected_output": "3", + "explanation": "Three palindromic strings: "a", "b", "c"." + }, + { + "example_num": 2, + "expected_input": "s = "aaa"", + "expected_output": "6", + "explanation": "Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa"." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c0c", + "questionid": 321, + "title": "Solve the Equation", + "slug": "solve-the-equation", + "description": "Solve a given equation and return the value of 'x' in the form of a string \"x=#value\". The equation contains only '+', '-' operation, the variable 'x' and its coefficient. You should return \"No solution\" if there is no solution for the equation, or \"Infinite solutions\" if there are infinite solutions for the equation. If there is exactly one solution for the equation, we ensure that the value of 'x' is an integer. ", + "category": [ + "Math", + "String", + "Simulation" + ], + "complexity": "Medium", + "successrate": 43.3, + "totalsubmissions": 74026, + "totalaccepted": 32029, + "likes": 367, + "dislikes": 691, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "equation = "x+5-3+x=6+x-2"", + "expected_output": ""x=2"", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "equation = "x=x"", + "expected_output": ""Infinite solutions"", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "equation = "2x=x"", + "expected_output": ""x=0"", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c11", + "questionid": 326, + "title": "Replace Words", + "slug": "replace-words", + "description": "In English, we have a concept called root, which can be followed by some other word to form another longer word - let's call this word successor. For example, when the root \"an\" is followed by the successor word \"other\", we can form a new word \"another\". Given a dictionary consisting of many roots and a sentence consisting of words separated by spaces, replace all the successors in the sentence with the root forming it. If a successor can be replaced by more than one root, replace it with the root that has the shortest length. Return the sentence after the replacement. ", + "category": [ + "Array", + "Hash Table", + "String", + "Trie" + ], + "complexity": "Medium", + "successrate": 61.9, + "totalsubmissions": 152554, + "totalaccepted": 94448, + "likes": 1483, + "dislikes": 152, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "dictionary = ["cat","bat","rat"], sentence = "the cattle was rattled by the battery"", + "expected_output": ""the cat was rat by the bat"", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "dictionary = ["a","b","c"], sentence = "aadsfasf absbs bbab cadsfafs"", + "expected_output": ""a a b c"", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c14", + "questionid": 329, + "title": "Image Smoother", + "slug": "image-smoother", + "description": "An image smoother is a filter of the size 3 x 3 that can be applied to each cell of an image by rounding down the average of the cell and the eight surrounding cells (i.e., the average of the nine cells in the blue smoother). If one or more of the surrounding cells of a cell is not present, we do not consider it in the average (i.e., the average of the four cells in the red smoother). Given an m x n integer matrix img representing the grayscale of an image, return the image after applying the smoother on each cell of it. ", + "category": [ + "Array", + "Matrix" + ], + "complexity": "Easy", + "successrate": 54.2, + "totalsubmissions": 117656, + "totalaccepted": 63743, + "likes": 376, + "dislikes": 1580, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "img = [[1,1,1],[1,0,1],[1,1,1]]", + "expected_output": "[[0,0,0],[0,0,0],[0,0,0]]", + "explanation": "For the points (0,0), (0,2), (2,0), (2,2): floor(3/4) = floor(0.75) = 0\nFor the points (0,1), (1,0), (1,2), (2,1): floor(5/6) = floor(0.83333333) = 0\nFor the point (1,1): floor(8/9) = floor(0.88888889) = 0" + }, + { + "example_num": 2, + "expected_input": "img = [[100,200,100],[200,50,200],[100,200,100]]", + "expected_output": "[[137,141,137],[141,138,141],[137,141,137]]", + "explanation": "For the points (0,0), (0,2), (2,0), (2,2): floor((100+200+200+50)/4) = floor(137.5) = 137\nFor the points (0,1), (1,0), (1,2), (2,1): floor((200+200+50+200+100+100)/6) = floor(141.666667) = 141\nFor the point (1,1): floor((50+200+200+200+200+100+100+100+100)/9) = floor(138.888889) = 138" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c1d", + "questionid": 338, + "title": "Valid Palindrome II", + "slug": "valid-palindrome-ii", + "description": "Given a string s, return true if the s can be palindrome after deleting at most one character from it. ", + "category": [ + "Two Pointers", + "String", + "Greedy" + ], + "complexity": "Easy", + "successrate": 39.4, + "totalsubmissions": 1227426, + "totalaccepted": 483424, + "likes": 5468, + "dislikes": 298, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "aba"", + "expected_output": "true", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "s = "abca"", + "expected_output": "true", + "explanation": "You could delete the character 'c'." + }, + { + "example_num": 3, + "expected_input": "s = "abc"", + "expected_output": "false", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c25", + "questionid": 346, + "title": "Count Binary Substrings", + "slug": "count-binary-substrings", + "description": "Give a binary string s, return the number of non-empty substrings that have the same number of 0's and 1's, and all the 0's and all the 1's in these substrings are grouped consecutively. Substrings that occur multiple times are counted the number of times they occur. ", + "category": [ + "Two Pointers", + "String" + ], + "complexity": "Easy", + "successrate": 64.8, + "totalsubmissions": 225586, + "totalaccepted": 146161, + "likes": 2806, + "dislikes": 593, + "hints": "How many valid binary substrings exist in \"000111\", and how many in \"11100\"? What about \"00011100\"?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "00110011"", + "expected_output": "6", + "explanation": "There are 6 substrings that have equal number of consecutive 1's and 0's: "0011", "01", "1100", "10", "0011", and "01".\nNotice that some of these substrings repeat and are counted the number of times they occur.\nAlso, "00110011" is not a valid substring because all the 0's (and 1's) are not grouped together." + }, + { + "example_num": 2, + "expected_input": "s = "10101"", + "expected_output": "4", + "explanation": "There are 4 substrings: "10", "01", "10", "01" that have equal number of consecutive 1's and 0's." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c2c", + "questionid": 353, + "title": "Find K-th Smallest Pair Distance", + "slug": "find-k-th-smallest-pair-distance", + "description": "The distance of a pair of integers a and b is defined as the absolute difference between a and b. Given an integer array nums and an integer k, return the kth smallest distance among all the pairs nums[i] and nums[j] where 0 <= i < j < nums.length. ", + "category": [ + "Array", + "Two Pointers", + "Binary Search", + "Sorting" + ], + "complexity": "Hard", + "successrate": 35, + "totalsubmissions": 165915, + "totalaccepted": 58039, + "likes": 1921, + "dislikes": 62, + "hints": "Binary search for the answer. How can you check how many pairs have distance <= X?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,3,1], k = 1", + "expected_output": "0", + "explanation": "Here are all the pairs:\n(1,3) -> 2\n(1,1) -> 0\n(3,1) -> 2\nThen the 1st smallest distance pair is (1,1), and its distance is 0." + }, + { + "example_num": 2, + "expected_input": "nums = [1,1,1], k = 2", + "expected_output": "0", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "nums = [1,6,1], k = 3", + "expected_output": "5", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c3b", + "questionid": 368, + "title": "Shortest Completing Word", + "slug": "shortest-completing-word", + "description": "Given a string licensePlate and an array of strings words, find the shortest completing word in words. A completing word is a word that contains all the letters in licensePlate. Ignore numbers and spaces in licensePlate, and treat letters as case insensitive. If a letter appears more than once in licensePlate, then it must appear in the word the same number of times or more. For example, if licensePlate = \"aBc 12c\", then it contains letters 'a', 'b' (ignoring case), and 'c' twice. Possible completing words are \"abccdef\", \"caaacab\", and \"cbca\". Return the shortest completing word in words. It is guaranteed an answer exists. If there are multiple shortest completing words, return the first one that occurs in words. ", + "category": [ + "Array", + "Hash Table", + "String" + ], + "complexity": "Easy", + "successrate": 58.9, + "totalsubmissions": 84073, + "totalaccepted": 49487, + "likes": 312, + "dislikes": 851, + "hints": "Count only the letters (possibly converted to lowercase) of each word. If a word is shorter and the count of each letter is at least the count of that letter in the licensePlate, it is the best answer we've seen yet.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "licensePlate = "1s3 PSt", words = ["step","steps","stripe","stepple"]", + "expected_output": ""steps"", + "explanation": "licensePlate contains letters 's', 'p', 's' (ignoring case), and 't'.\n"step" contains 't' and 'p', but only contains 1 's'.\n"steps" contains 't', 'p', and both 's' characters.\n"stripe" is missing an 's'.\n"stepple" is missing an 's'.\nSince "steps" is the only word containing all the letters, that is the answer." + }, + { + "example_num": 2, + "expected_input": "licensePlate = "1s3 456", words = ["looks","pest","stew","show"]", + "expected_output": ""pest"", + "explanation": "licensePlate only contains the letter 's'. All the words contain 's', but among these "pest", "stew", and "show" are shortest. The answer is "pest" because it is the word that appears earliest of the 3." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c41", + "questionid": 374, + "title": "Flatten a Multilevel Doubly Linked List", + "slug": "flatten-a-multilevel-doubly-linked-list", + "description": "You are given a doubly linked list, which contains nodes that have a next pointer, a previous pointer, and an additional child pointer. This child pointer may or may not point to a separate doubly linked list, also containing these special nodes. These child lists may have one or more children of their own, and so on, to produce a multilevel data structure as shown in the example below. Given the head of the first level of the list, flatten the list so that all the nodes appear in a single-level, doubly linked list. Let curr be a node with a child list. The nodes in the child list should appear after curr and before curr.next in the flattened list. Return the head of the flattened list. The nodes in the list must have all of their child pointers set to null. ", + "category": [ + "Linked List", + "Depth-First Search", + "Doubly-Linked List" + ], + "complexity": "Medium", + "successrate": 58.9, + "totalsubmissions": 389156, + "totalaccepted": 229148, + "likes": 3579, + "dislikes": 249, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "head = [1,2,3,4,5,6,null,null,null,7,8,9,10,null,null,11,12]", + "expected_output": "[1,2,3,7,8,11,12,9,10,4,5,6]", + "explanation": "The multilevel linked list in the input is shown.\nAfter flattening the multilevel linked list it becomes:\n" + }, + { + "example_num": 2, + "expected_input": "head = [1,2,null,3]", + "expected_output": "[1,3,2]", + "explanation": "The multilevel linked list in the input is shown.\nAfter flattening the multilevel linked list it becomes:\n" + }, + { + "example_num": 3, + "expected_input": "head = []", + "expected_output": "[]", + "explanation": "There could be empty list in the input." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c42", + "questionid": 375, + "title": "Prime Number of Set Bits in Binary Representation", + "slug": "prime-number-of-set-bits-in-binary-representation", + "description": "Given two integers left and right, return the count of numbers in the inclusive range [left, right] having a prime number of set bits in their binary representation. Recall that the number of set bits an integer has is the number of 1's present when written in binary. ", + "category": [ + "Math", + "Bit Manipulation" + ], + "complexity": "Easy", + "successrate": 66.7, + "totalsubmissions": 102152, + "totalaccepted": 68143, + "likes": 452, + "dislikes": 460, + "hints": "Write a helper function to count the number of set bits in a number, then check whether the number of set bits is 2, 3, 5, 7, 11, 13, 17 or 19.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "left = 6, right = 10", + "expected_output": "4", + "explanation": "6 -> 110 (2 set bits, 2 is prime)\n7 -> 111 (3 set bits, 3 is prime)\n8 -> 1000 (1 set bit, 1 is not prime)\n9 -> 1001 (2 set bits, 2 is prime)\n10 -> 1010 (2 set bits, 2 is prime)\n4 numbers have a prime number of set bits." + }, + { + "example_num": 2, + "expected_input": "left = 10, right = 15", + "expected_output": "5", + "explanation": "10 -> 1010 (2 set bits, 2 is prime)\n11 -> 1011 (3 set bits, 3 is prime)\n12 -> 1100 (2 set bits, 2 is prime)\n13 -> 1101 (3 set bits, 3 is prime)\n14 -> 1110 (3 set bits, 3 is prime)\n15 -> 1111 (4 set bits, 4 is not prime)\n5 numbers have a prime number of set bits." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c43", + "questionid": 376, + "title": "Partition Labels", + "slug": "partition-labels", + "description": "You are given a string s. We want to partition the string into as many parts as possible so that each letter appears in at most one part. Note that the partition is done so that after concatenating all the parts in order, the resultant string should be s. Return a list of integers representing the size of these parts. ", + "category": [ + "Hash Table", + "Two Pointers", + "String", + "Greedy" + ], + "complexity": "Medium", + "successrate": 79.5, + "totalsubmissions": 475982, + "totalaccepted": 378565, + "likes": 7541, + "dislikes": 287, + "hints": "Try to greedily choose the smallest partition that includes the first letter. If you have something like \"abaccbdeffed\", then you might need to add b. You can use an map like \"last['b'] = 5\" to help you expand the width of your partition.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "ababcbacadefegdehijhklij"", + "expected_output": "[9,7,8]", + "explanation": "The partition is "ababcbaca", "defegde", "hijhklij".\nThis is a partition so that each letter appears in at most one part.\nA partition like "ababcbacadefegde", "hijhklij" is incorrect, because it splits s into less parts." + }, + { + "example_num": 2, + "expected_input": "s = "eccbbbbdec"", + "expected_output": "[10]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c46", + "questionid": 379, + "title": "Maximum Depth of N-ary Tree", + "slug": "maximum-depth-of-n-ary-tree", + "description": "Given a n-ary tree, find its maximum depth. The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See examples). ", + "category": [ + "Tree", + "Depth-First Search", + "Breadth-First Search" + ], + "complexity": "Easy", + "successrate": 71, + "totalsubmissions": 291893, + "totalaccepted": 207200, + "likes": 1947, + "dislikes": 69, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [1,null,3,2,4,null,5,6]", + "expected_output": "3", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]", + "expected_output": "5", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c49", + "questionid": 382, + "title": "Toeplitz Matrix", + "slug": "toeplitz-matrix", + "description": "Given an m x n matrix, return true if the matrix is Toeplitz. Otherwise, return false. A matrix is Toeplitz if every diagonal from top-left to bottom-right has the same elements. ", + "category": [ + "Array", + "Matrix" + ], + "complexity": "Easy", + "successrate": 68, + "totalsubmissions": 269427, + "totalaccepted": 183077, + "likes": 1915, + "dislikes": 119, + "hints": "Check whether each value is equal to the value of it's top-left neighbor.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "matrix = [[1,2,3,4],[5,1,2,3],[9,5,1,2]]", + "expected_output": "true", + "explanation": "In the above grid, the diagonals are:\n"[9]", "[5, 5]", "[1, 1, 1]", "[2, 2, 2]", "[3, 3]", "[4]".\nIn each diagonal all elements are the same, so the answer is True." + }, + { + "example_num": 2, + "expected_input": "matrix = [[1,2],[2,2]]", + "expected_output": "false", + "explanation": "The diagonal "[1, 2]" has different elements." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c4a", + "questionid": 383, + "title": "Reorganize String", + "slug": "reorganize-string", + "description": "Given a string s, rearrange the characters of s so that any two adjacent characters are not the same. Return any possible rearrangement of s or return \"\" if not possible. ", + "category": [ + "Hash Table", + "String", + "Greedy", + "Sorting", + "Heap (Priority Queue)", + "Counting" + ], + "complexity": "Medium", + "successrate": 52, + "totalsubmissions": 395857, + "totalaccepted": 205838, + "likes": 4519, + "dislikes": 173, + "hints": "Alternate placing the most common letters.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = \"aab\"", + "expected_output": "\"aba\"", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "s = \"aaab\"", + "expected_output": "\"\"", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c15", + "questionid": 330, + "title": "Maximum Width of Binary Tree", + "slug": "maximum-width-of-binary-tree", + "description": "Given the root of a binary tree, return the maximum width of the given tree. The maximum width of a tree is the maximum width among all levels. The width of one level is defined as the length between the end-nodes (the leftmost and rightmost non-null nodes), where the null nodes between the end-nodes that would be present in a complete binary tree extending down to that level are also counted into the length calculation. It is guaranteed that the answer will in the range of a 32-bit signed integer. ", + "category": [ + "Tree", + "Depth-First Search", + "Breadth-First Search", + "Binary Tree" + ], + "complexity": "Medium", + "successrate": 40.2, + "totalsubmissions": 448427, + "totalaccepted": 180303, + "likes": 4442, + "dislikes": 714, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [1,3,2,5,3,null,9]", + "expected_output": "4", + "explanation": "The maximum width exists in the third level with length 4 (5,3,null,9)." + }, + { + "example_num": 2, + "expected_input": "root = [1,3,2,5,null,null,9,6,null,7]", + "expected_output": "7", + "explanation": "The maximum width exists in the fourth level with length 7 (6,null,null,null,null,null,7)." + }, + { + "example_num": 3, + "expected_input": "root = [1,3,2,5]", + "expected_output": "2", + "explanation": "The maximum width exists in the second level with length 2 (3,2)." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c17", + "questionid": 332, + "title": "Kth Smallest Number in Multiplication Table", + "slug": "kth-smallest-number-in-multiplication-table", + "description": "Nearly everyone has used the Multiplication Table. The multiplication table of size m x n is an integer matrix mat where mat[i][j] == i * j (1-indexed). Given three integers m, n, and k, return the kth smallest element in the m x n multiplication table. ", + "category": [ + "Binary Search" + ], + "complexity": "Hard", + "successrate": 51, + "totalsubmissions": 93964, + "totalaccepted": 47939, + "likes": 1592, + "dislikes": 45, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "m = 3, n = 3, k = 5", + "expected_output": "3", + "explanation": "The 5th smallest number is 3." + }, + { + "example_num": 2, + "expected_input": "m = 2, n = 3, k = 6", + "expected_output": "6", + "explanation": "The 6th smallest number is 6." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c1f", + "questionid": 340, + "title": "Redundant Connection II", + "slug": "redundant-connection-ii", + "description": "In this problem, a rooted tree is a directed graph such that, there is exactly one node (the root) for which all other nodes are descendants of this node, plus every node has exactly one parent, except for the root node which has no parents. The given input is a directed graph that started as a rooted tree with n nodes (with distinct values from 1 to n), with one additional directed edge added. The added edge has two different vertices chosen from 1 to n, and was not an edge that already existed. The resulting graph is given as a 2D-array of edges. Each element of edges is a pair [ui, vi] that represents a directed edge connecting nodes ui and vi, where ui is a parent of child vi. Return an edge that can be removed so that the resulting graph is a rooted tree of n nodes. If there are multiple answers, return the answer that occurs last in the given 2D-array. ", + "category": [ + "Depth-First Search", + "Breadth-First Search", + "Union Find", + "Graph" + ], + "complexity": "Hard", + "successrate": 33.7, + "totalsubmissions": 152361, + "totalaccepted": 51386, + "likes": 1538, + "dislikes": 265, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "edges = [[1,2],[1,3],[2,3]]", + "expected_output": "[2,3]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "edges = [[1,2],[2,3],[3,4],[4,1],[1,5]]", + "expected_output": "[4,1]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c21", + "questionid": 342, + "title": "Knight Probability in Chessboard", + "slug": "knight-probability-in-chessboard", + "description": "On an n x n chessboard, a knight starts at the cell (row, column) and attempts to make exactly k moves. The rows and columns are 0-indexed, so the top-left cell is (0, 0), and the bottom-right cell is (n - 1, n - 1). A chess knight has eight possible moves it can make, as illustrated below. Each move is two cells in a cardinal direction, then one cell in an orthogonal direction. Each time the knight is to move, it chooses one of eight possible moves uniformly at random (even if the piece would go off the chessboard) and moves there. The knight continues moving until it has made exactly k moves or has moved off the chessboard. Return the probability that the knight remains on the board after it has stopped moving. ", + "category": [ + "Dynamic Programming" + ], + "complexity": "Medium", + "successrate": 51.5, + "totalsubmissions": 153524, + "totalaccepted": 79062, + "likes": 1905, + "dislikes": 287, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 3, k = 2, row = 0, column = 0", + "expected_output": "0.06250", + "explanation": "There are two moves (to (1,2), (2,1)) that will keep the knight on the board.\nFrom each of those positions, there are also two moves that will keep the knight on the board.\nThe total probability the knight stays on the board is 0.0625." + }, + { + "example_num": 2, + "expected_input": "n = 1, k = 0, row = 0, column = 0", + "expected_output": "1.00000", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c22", + "questionid": 343, + "title": "Maximum Sum of 3 Non-Overlapping Subarrays", + "slug": "maximum-sum-of-3-non-overlapping-subarrays", + "description": "Given an integer array nums and an integer k, find three non-overlapping subarrays of length k with maximum sum and return them. Return the result as a list of indices representing the starting position of each interval (0-indexed). If there are multiple answers, return the lexicographically smallest one. ", + "category": [ + "Array", + "Dynamic Programming" + ], + "complexity": "Hard", + "successrate": 48.5, + "totalsubmissions": 128154, + "totalaccepted": 62143, + "likes": 1590, + "dislikes": 97, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,2,1,2,6,7,5,1], k = 2", + "expected_output": "[0,3,5]", + "explanation": "Subarrays [1, 2], [2, 6], [7, 5] correspond to the starting indices [0, 3, 5].\nWe could have also taken [2, 1], but an answer of [1, 3, 5] would be lexicographically larger." + }, + { + "example_num": 2, + "expected_input": "nums = [1,2,1,2,1,2,1,2,1], k = 2", + "expected_output": "[0,2,4]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c27", + "questionid": 348, + "title": "Partition to K Equal Sum Subsets", + "slug": "partition-to-k-equal-sum-subsets", + "description": "Given an integer array nums and an integer k, return true if it is possible to divide this array into k non-empty subsets whose sums are all equal. ", + "category": [ + "Array", + "Dynamic Programming", + "Backtracking", + "Bit Manipulation", + "Memoization", + "Bitmask" + ], + "complexity": "Medium", + "successrate": 44.2, + "totalsubmissions": 437177, + "totalaccepted": 193131, + "likes": 4667, + "dislikes": 300, + "hints": "We can figure out what target each subset must sum to. Then, let's recursively search, where at each call to our function, we choose which of k subsets the next value will join.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [4,3,2,3,5,2,1], k = 4", + "expected_output": "true", + "explanation": "It is possible to divide it into 4 subsets (5), (1, 4), (2,3), (2,3) with equal sums." + }, + { + "example_num": 2, + "expected_input": "nums = [1,2,3,4], k = 3", + "expected_output": "false", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c28", + "questionid": 349, + "title": "Falling Squares", + "slug": "falling-squares", + "description": "There are several squares being dropped onto the X-axis of a 2D plane. You are given a 2D integer array positions where positions[i] = [lefti, sideLengthi] represents the ith square with a side length of sideLengthi that is dropped with its left edge aligned with X-coordinate lefti. Each square is dropped one at a time from a height above any landed squares. It then falls downward (negative Y direction) until it either lands on the top side of another square or on the X-axis. A square brushing the left/right side of another square does not count as landing on it. Once it lands, it freezes in place and cannot be moved. After each square is dropped, you must record the height of the current tallest stack of squares. Return an integer array ans where ans[i] represents the height described above after dropping the ith square. ", + "category": [ + "Array", + "Segment Tree", + "Ordered Set" + ], + "complexity": "Hard", + "successrate": 43.8, + "totalsubmissions": 44288, + "totalaccepted": 19395, + "likes": 446, + "dislikes": 69, + "hints": "If positions = [[10, 20], [20, 30]], this is the same as [[1, 2], [2, 3]]. Currently, the values of positions are very large. Can you generalize this approach so as to make the values in positions manageable?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "positions = [[1,2],[2,3],[6,1]]", + "expected_output": "[2,5,5]", + "explanation": "After the first drop, the tallest stack is square 1 with a height of 2.\nAfter the second drop, the tallest stack is squares 1 and 2 with a height of 5.\nAfter the third drop, the tallest stack is still squares 1 and 2 with a height of 5.\nThus, we return an answer of [2, 5, 5]." + }, + { + "example_num": 2, + "expected_input": "positions = [[100,100],[200,100]]", + "expected_output": "[100,100]", + "explanation": "After the first drop, the tallest stack is square 1 with a height of 100.\nAfter the second drop, the tallest stack is either square 1 or square 2, both with heights of 100.\nThus, we return an answer of [100, 100].\nNote that square 2 only brushes the right side of square 1, which does not count as landing on it." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c29", + "questionid": 350, + "title": "Minimum ASCII Delete Sum for Two Strings", + "slug": "minimum-ascii-delete-sum-for-two-strings", + "description": "Given two strings s1 and s2, return the lowest ASCII sum of deleted characters to make two strings equal. ", + "category": [ + "String", + "Dynamic Programming" + ], + "complexity": "Medium", + "successrate": 61.5, + "totalsubmissions": 99713, + "totalaccepted": 61334, + "likes": 1878, + "dislikes": 62, + "hints": "Let dp(i, j) be the answer for inputs s1[i:] and s2[j:].", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s1 = "sea", s2 = "eat"", + "expected_output": "231", + "explanation": "Deleting "s" from "sea" adds the ASCII value of "s" (115) to the sum.\nDeleting "t" from "eat" adds 116 to the sum.\nAt the end, both strings are equal, and 115 + 116 = 231 is the minimum sum possible to achieve this." + }, + { + "example_num": 2, + "expected_input": "s1 = "delete", s2 = "leet"", + "expected_output": "403", + "explanation": "Deleting "dee" from "delete" to turn the string into "let",\nadds 100[d] + 101[e] + 101[e] to the sum.\nDeleting "e" from "leet" adds 101[e] to the sum.\nAt the end, both strings are equal to "let", and the answer is 100+101+101+101 = 403.\nIf instead we turned both strings into "lee" or "eet", we would get answers of 433 or 417, which are higher." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c2b", + "questionid": 352, + "title": "Maximum Length of Repeated Subarray", + "slug": "maximum-length-of-repeated-subarray", + "description": "Given two integer arrays nums1 and nums2, return the maximum length of a subarray that appears in both arrays. ", + "category": [ + "Array", + "Binary Search", + "Dynamic Programming", + "Sliding Window", + "Rolling Hash", + "Hash Function" + ], + "complexity": "Medium", + "successrate": 51.4, + "totalsubmissions": 326681, + "totalaccepted": 167799, + "likes": 3731, + "dislikes": 88, + "hints": "Use dynamic programming. dp[i][j] will be the answer for inputs A[i:], B[j:].", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums1 = [1,2,3,2,1], nums2 = [3,2,1,4,7]", + "expected_output": "3", + "explanation": "The repeated subarray with maximum length is [3,2,1]." + }, + { + "example_num": 2, + "expected_input": "nums1 = [0,0,0,0,0], nums2 = [0,0,0,0,0]", + "expected_output": "5", + "explanation": "The repeated subarray with maximum length is [0,0,0,0,0]." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c2e", + "questionid": 355, + "title": "Find Pivot Index", + "slug": "find-pivot-index", + "description": "Given an array of integers nums, calculate the pivot index of this array. The pivot index is the index where the sum of all the numbers strictly to the left of the index is equal to the sum of all the numbers strictly to the index's right. If the index is on the left edge of the array, then the left sum is 0 because there are no elements to the left. This also applies to the right edge of the array. Return the leftmost pivot index. If no such index exists, return -1. ", + "category": [ + "Array", + "Prefix Sum" + ], + "complexity": "Easy", + "successrate": 51.5, + "totalsubmissions": 584791, + "totalaccepted": 300925, + "likes": 3064, + "dislikes": 364, + "hints": "We can precompute prefix sums P[i] = nums[0] + nums[1] + ... + nums[i-1].\r\nThen for each index, the left sum is P[i], and the right sum is P[P.length - 1] - P[i] - nums[i].", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,7,3,6,5,6]", + "expected_output": "3", + "explanation": "The pivot index is 3.\nLeft sum = nums[0] + nums[1] + nums[2] = 1 + 7 + 3 = 11\nRight sum = nums[4] + nums[5] = 5 + 6 = 11" + }, + { + "example_num": 2, + "expected_input": "nums = [1,2,3]", + "expected_output": "-1", + "explanation": "There is no index that satisfies the conditions in the problem statement." + }, + { + "example_num": 3, + "expected_input": "nums = [2,1,-1]", + "expected_output": "0", + "explanation": "The pivot index is 0.\nLeft sum = 0 (no elements to the left of index 0)\nRight sum = nums[1] + nums[2] = 1 + -1 = 0" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c36", + "questionid": 363, + "title": "To Lower Case", + "slug": "to-lower-case", + "description": "Given a string s, return the string after replacing every uppercase letter with the same lowercase letter. ", + "category": [ + "String" + ], + "complexity": "Easy", + "successrate": 81.3, + "totalsubmissions": 413860, + "totalaccepted": 336519, + "likes": 1053, + "dislikes": 2298, + "hints": "Most languages support lowercase conversion for a string data type. However, that is certainly not the purpose of the problem. Think about how the implementation of the lowercase function call can be done easily. Think ASCII! Think about the different capital letters and their ASCII codes and how that relates to their lowercase counterparts. Does there seem to be any pattern there? Any mathematical relationship that we can use?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "Hello"", + "expected_output": ""hello"", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "s = "here"", + "expected_output": ""here"", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "s = "LOVELY"", + "expected_output": ""lovely"", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c37", + "questionid": 364, + "title": "Network Delay Time", + "slug": "network-delay-time", + "description": "You are given a network of n nodes, labeled from 1 to n. You are also given times, a list of travel times as directed edges times[i] = (ui, vi, wi), where ui is the source node, vi is the target node, and wi is the time it takes for a signal to travel from source to target. We will send a signal from a given node k. Return the time it takes for all the n nodes to receive the signal. If it is impossible for all the n nodes to receive the signal, return -1. ", + "category": [ + "Depth-First Search", + "Breadth-First Search", + "Graph", + "Heap (Priority Queue)", + "Shortest Path" + ], + "complexity": "Medium", + "successrate": 48.4, + "totalsubmissions": 479952, + "totalaccepted": 232392, + "likes": 3920, + "dislikes": 275, + "hints": "We visit each node at some time, and if that time is better than the fastest time we've reached this node, we travel along outgoing edges in sorted order. Alternatively, we could use Dijkstra's algorithm.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "times = [[2,1,1],[2,3,1],[3,4,1]], n = 4, k = 2", + "expected_output": "2", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "times = [[1,2,1]], n = 2, k = 1", + "expected_output": "1", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "times = [[1,2,1]], n = 2, k = 2", + "expected_output": "-1", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c3a", + "questionid": 367, + "title": "Largest Number At Least Twice of Others", + "slug": "largest-number-at-least-twice-of-others", + "description": "You are given an integer array nums where the largest integer is unique. Determine whether the largest element in the array is at least twice as much as every other number in the array. If it is, return the index of the largest element, or return -1 otherwise. ", + "category": [ + "Array", + "Sorting" + ], + "complexity": "Easy", + "successrate": 45.2, + "totalsubmissions": 342731, + "totalaccepted": 154812, + "likes": 665, + "dislikes": 752, + "hints": "Scan through the array to find the unique largest element `m`, keeping track of it's index `maxIndex`.\r\n\r\nScan through the array again. If we find some `x != m` with `m < 2*x`, we should return `-1`.\r\n\r\nOtherwise, we should return `maxIndex`.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [3,6,1,0]", + "expected_output": "1", + "explanation": "6 is the largest integer.\nFor every other number in the array x, 6 is at least twice as big as x.\nThe index of value 6 is 1, so we return 1." + }, + { + "example_num": 2, + "expected_input": "nums = [1,2,3,4]", + "expected_output": "-1", + "explanation": "4 is less than twice the value of 3, so we return -1." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c3c", + "questionid": 369, + "title": "Contain Virus", + "slug": "contain-virus", + "description": "A virus is spreading rapidly, and your task is to quarantine the infected area by installing walls. The world is modeled as an m x n binary grid isInfected, where isInfected[i][j] == 0 represents uninfected cells, and isInfected[i][j] == 1 represents cells contaminated with the virus. A wall (and only one wall) can be installed between any two 4-directionally adjacent cells, on the shared boundary. Every night, the virus spreads to all neighboring cells in all four directions unless blocked by a wall. Resources are limited. Each day, you can install walls around only one region (i.e., the affected area (continuous block of infected cells) that threatens the most uninfected cells the following night). There will never be a tie. Return the number of walls used to quarantine all the infected regions. If the world will become fully infected, return the number of walls used. ", + "category": [ + "Array", + "Depth-First Search", + "Breadth-First Search", + "Matrix", + "Simulation" + ], + "complexity": "Hard", + "successrate": 50, + "totalsubmissions": 16339, + "totalaccepted": 8173, + "likes": 229, + "dislikes": 367, + "hints": "The implementation is long - we want to perfrom the following steps:\r\n\r\n* Find all viral regions (connected components), additionally for each region keeping track of the frontier (neighboring uncontaminated cells), and the perimeter of the region.\r\n\r\n* Disinfect the most viral region, adding it's perimeter to the answer.\r\n\r\n* Spread the virus in the remaining regions outward by 1 square.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "isInfected = [[0,1,0,0,0,0,0,1],[0,1,0,0,0,0,0,1],[0,0,0,0,0,0,0,1],[0,0,0,0,0,0,0,0]]", + "expected_output": "10", + "explanation": "There are 2 contaminated regions.\nOn the first day, add 5 walls to quarantine the viral region on the left. The board after the virus spreads is:\n\"\"\nOn the second day, add 5 walls to quarantine the viral region on the right. The virus is fully contained.\n\"\"" + }, + { + "example_num": 2, + "expected_input": "isInfected = [[1,1,1],[1,0,1],[1,1,1]]", + "expected_output": "4", + "explanation": "Even though there is only one cell saved, there are 4 walls built.\nNotice that walls are only built on the shared boundary of two different cells." + }, + { + "example_num": 3, + "expected_input": "isInfected = [[1,1,1,0,0,0,0,0,0],[1,0,1,0,1,1,1,1,1],[1,1,1,0,0,0,0,0,0]]", + "expected_output": "13", + "explanation": "The region on the left only builds two new walls." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c45", + "questionid": 378, + "title": "Couples Holding Hands", + "slug": "couples-holding-hands", + "description": "There are n couples sitting in 2n seats arranged in a row and want to hold hands. The people and seats are represented by an integer array row where row[i] is the ID of the person sitting in the ith seat. The couples are numbered in order, the first couple being (0, 1), the second couple being (2, 3), and so on with the last couple being (2n - 2, 2n - 1). Return the minimum number of swaps so that every couple is sitting side by side. A swap consists of choosing any two people, then they stand up and switch seats. ", + "category": [ + "Greedy", + "Depth-First Search", + "Breadth-First Search", + "Union Find", + "Graph" + ], + "complexity": "Hard", + "successrate": 56.5, + "totalsubmissions": 76653, + "totalaccepted": 43314, + "likes": 1580, + "dislikes": 85, + "hints": "Say there are N two-seat couches. For each couple, draw an edge from the couch of one partner to the couch of the other partner.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "row = [0,2,1,3]", + "expected_output": "1", + "explanation": "We only need to swap the second (row[1]) and third (row[2]) person." + }, + { + "example_num": 2, + "expected_input": "row = [3,2,0,1]", + "expected_output": "0", + "explanation": "All couples are already seated side by side." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c47", + "questionid": 380, + "title": "N-ary Tree Preorder Traversal", + "slug": "n-ary-tree-preorder-traversal", + "description": "Given the root of an n-ary tree, return the preorder traversal of its nodes' values. Nary-Tree input serialization is represented in their level order traversal. Each group of children is separated by the null value (See examples) ", + "category": [ + "Stack", + "Tree", + "Depth-First Search" + ], + "complexity": "Easy", + "successrate": 76.1, + "totalsubmissions": 295173, + "totalaccepted": 224480, + "likes": 1708, + "dislikes": 80, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [1,null,3,2,4,null,5,6]", + "expected_output": "[1,3,5,6,2,4]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]", + "expected_output": "[1,2,3,6,7,11,14,4,8,12,5,9,13,10]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c0e", + "questionid": 323, + "title": "Set Mismatch", + "slug": "set-mismatch", + "description": "You have a set of integers s, which originally contains all the numbers from 1 to n. Unfortunately, due to some error, one of the numbers in s got duplicated to another number in the set, which results in repetition of one number and loss of another number. You are given an integer array nums representing the data status of this set after the error. Find the number that occurs twice and the number that is missing and return them in the form of an array. ", + "category": [ + "Array", + "Hash Table", + "Bit Manipulation", + "Sorting" + ], + "complexity": "Easy", + "successrate": 41.3, + "totalsubmissions": 400479, + "totalaccepted": 165255, + "likes": 1865, + "dislikes": 554, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,2,2,4]", + "expected_output": "[2,3]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "nums = [1,1]", + "expected_output": "[1,2]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c0d", + "questionid": 322, + "title": "Maximum Average Subarray I", + "slug": "maximum-average-subarray-i", + "description": "You are given an integer array nums consisting of n elements, and an integer k. Find a contiguous subarray whose length is equal to k that has the maximum average value and return this value. Any answer with a calculation error less than 10-5 will be accepted. ", + "category": [ + "Array", + "Sliding Window" + ], + "complexity": "Easy", + "successrate": 43.5, + "totalsubmissions": 322079, + "totalaccepted": 140016, + "likes": 1565, + "dislikes": 156, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,12,-5,-6,50,3], k = 4", + "expected_output": "12.75000", + "explanation": "Maximum average is (12 - 5 - 6 + 50) / 4 = 51 / 4 = 12.75" + }, + { + "example_num": 2, + "expected_input": "nums = [5], k = 1", + "expected_output": "5.00000", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c16", + "questionid": 331, + "title": "Non-decreasing Array", + "slug": "non-decreasing-array", + "description": "Given an array nums with n integers, your task is to check if it could become non-decreasing by modifying at most one element. We define an array is non-decreasing if nums[i] <= nums[i + 1] holds for every i (0-based) such that (0 <= i <= n - 2). ", + "category": [ + "Array" + ], + "complexity": "Medium", + "successrate": 21.5, + "totalsubmissions": 795825, + "totalaccepted": 171208, + "likes": 3571, + "dislikes": 664, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [4,2,3]", + "expected_output": "true", + "explanation": "You could modify the first 4 to 1 to get a non-decreasing array." + }, + { + "example_num": 2, + "expected_input": "nums = [4,2,1]", + "expected_output": "false", + "explanation": "You cannot get a non-decreasing array by modifying at most one element." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c19", + "questionid": 334, + "title": "Maximum Swap", + "slug": "maximum-swap", + "description": "You are given an integer num. You can swap two digits at most once to get the maximum valued number. Return the maximum valued number you can get. ", + "category": [ + "Math", + "Greedy" + ], + "complexity": "Medium", + "successrate": 47.5, + "totalsubmissions": 346736, + "totalaccepted": 164735, + "likes": 2446, + "dislikes": 142, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "num = 2736", + "expected_output": "7236", + "explanation": "Swap the number 2 and the number 7." + }, + { + "example_num": 2, + "expected_input": "num = 9973", + "expected_output": "9973", + "explanation": "No swap." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c1c", + "questionid": 337, + "title": "Longest Continuous Increasing Subsequence", + "slug": "longest-continuous-increasing-subsequence", + "description": "Given an unsorted array of integers nums, return the length of the longest continuous increasing subsequence (i.e. subarray). The subsequence must be strictly increasing. A continuous increasing subsequence is defined by two indices l and r (l < r) such that it is [nums[l], nums[l + 1], ..., nums[r - 1], nums[r]] and for each l <= i < r, nums[i] < nums[i + 1]. ", + "category": [ + "Array" + ], + "complexity": "Easy", + "successrate": 48.3, + "totalsubmissions": 394056, + "totalaccepted": 190453, + "likes": 1660, + "dislikes": 164, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,3,5,4,7]", + "expected_output": "3", + "explanation": "The longest continuous increasing subsequence is [1,3,5] with length 3.\nEven though [1,3,5,7] is an increasing subsequence, it is not continuous as elements 5 and 7 are separated by element\n4." + }, + { + "example_num": 2, + "expected_input": "nums = [2,2,2,2,2]", + "expected_output": "1", + "explanation": "The longest continuous increasing subsequence is [2] with length 1. Note that it must be strictly\nincreasing." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c1e", + "questionid": 339, + "title": "Redundant Connection", + "slug": "redundant-connection", + "description": "In this problem, a tree is an undirected graph that is connected and has no cycles. You are given a graph that started as a tree with n nodes labeled from 1 to n, with one additional edge added. The added edge has two different vertices chosen from 1 to n, and was not an edge that already existed. The graph is represented as an array edges of length n where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the graph. Return an edge that can be removed so that the resulting graph is a tree of n nodes. If there are multiple answers, return the answer that occurs last in the input. ", + "category": [ + "Depth-First Search", + "Breadth-First Search", + "Union Find", + "Graph" + ], + "complexity": "Medium", + "successrate": 61.1, + "totalsubmissions": 317920, + "totalaccepted": 194287, + "likes": 3572, + "dislikes": 286, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "edges = [[1,2],[1,3],[2,3]]", + "expected_output": "[2,3]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "edges = [[1,2],[2,3],[3,4],[1,4],[1,5]]", + "expected_output": "[1,4]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c23", + "questionid": 344, + "title": "Top K Frequent Words", + "slug": "top-k-frequent-words", + "description": "Given an array of strings words and an integer k, return the k most frequent strings. Return the answer sorted by the frequency from highest to lowest. Sort the words with the same frequency by their lexicographical order. ", + "category": [ + "Hash Table", + "String", + "Trie", + "Sorting", + "Heap (Priority Queue)", + "Bucket Sort", + "Counting" + ], + "complexity": "Medium", + "successrate": 54.3, + "totalsubmissions": 682591, + "totalaccepted": 370829, + "likes": 4346, + "dislikes": 245, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "words = ["i","love","leetcode","i","love","coding"], k = 2", + "expected_output": "["i","love"]", + "explanation": ""i" and "love" are the two most frequent words.\nNote that "i" comes before "love" due to a lower alphabetical order." + }, + { + "example_num": 2, + "expected_input": "words = ["the","day","is","sunny","the","the","the","sunny","is","is"], k = 4", + "expected_output": "["the","is","sunny","day"]", + "explanation": ""the", "is", "sunny" and "day" are the four most frequent words, with the number of occurrence being 4, 3, 2 and 1 respectively." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c26", + "questionid": 347, + "title": "Degree of an Array", + "slug": "degree-of-an-array", + "description": "Given a non-empty array of non-negative integers nums, the degree of this array is defined as the maximum frequency of any one of its elements. Your task is to find the smallest possible length of a (contiguous) subarray of nums, that has the same degree as nums. ", + "category": [ + "Array", + "Hash Table" + ], + "complexity": "Easy", + "successrate": 55.6, + "totalsubmissions": 265235, + "totalaccepted": 147495, + "likes": 1945, + "dislikes": 1289, + "hints": "Say 5 is the only element that occurs the most number of times - for example, nums = [1, 5, 2, 3, 5, 4, 5, 6]. What is the answer?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,2,2,3,1]", + "expected_output": "2", + "explanation": "The input array has a degree of 2 because both elements 1 and 2 appear twice.\nOf the subarrays that have the same degree:\n[1, 2, 2, 3, 1], [1, 2, 2, 3], [2, 2, 3, 1], [1, 2, 2], [2, 2, 3], [2, 2]\nThe shortest length is 2. So return 2." + }, + { + "example_num": 2, + "expected_input": "nums = [1,2,2,3,1,4,2]", + "expected_output": "6", + "explanation": "The degree is 3 because the element 2 is repeated 3 times.\nSo [2,2,3,1,4,2] is the shortest subarray, therefore returning 6." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c2a", + "questionid": 351, + "title": "Subarray Product Less Than K", + "slug": "subarray-product-less-than-k", + "description": "Given an array of integers nums and an integer k, return the number of contiguous subarrays where the product of all the elements in the subarray is strictly less than k. ", + "category": [ + "Array", + "Sliding Window" + ], + "complexity": "Medium", + "successrate": 43.7, + "totalsubmissions": 368610, + "totalaccepted": 160899, + "likes": 3826, + "dislikes": 132, + "hints": "For each j, let opt(j) be the smallest i so that nums[i] * nums[i+1] * ... * nums[j] is less than k. opt is an increasing function.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [10,5,2,6], k = 100", + "expected_output": "8", + "explanation": "The 8 subarrays that have product less than 100 are:\n[10], [5], [2], [6], [10, 5], [5, 2], [2, 6], [5, 2, 6]\nNote that [10, 5, 2] is not included as the product of 100 is not strictly less than k." + }, + { + "example_num": 2, + "expected_input": "nums = [1,2,3], k = 0", + "expected_output": "0", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c2d", + "questionid": 354, + "title": "Longest Word in Dictionary", + "slug": "longest-word-in-dictionary", + "description": "Given an array of strings words representing an English Dictionary, return the longest word in words that can be built one character at a time by other words in words. If there is more than one possible answer, return the longest word with the smallest lexicographical order. If there is no answer, return the empty string. ", + "category": [ + "Array", + "Hash Table", + "String", + "Trie", + "Sorting" + ], + "complexity": "Medium", + "successrate": 50.9, + "totalsubmissions": 220173, + "totalaccepted": 112159, + "likes": 1317, + "dislikes": 1288, + "hints": "For every word in the input list, we can check whether all prefixes of that word are in the input list by using a Set.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "words = ["w","wo","wor","worl","world"]", + "expected_output": ""world"", + "explanation": "The word "world" can be built one character at a time by "w", "wo", "wor", and "worl"." + }, + { + "example_num": 2, + "expected_input": "words = ["a","banana","app","appl","ap","apply","apple"]", + "expected_output": ""apple"", + "explanation": "Both "apply" and "apple" can be built from other words in the dictionary. However, "apple" is lexicographically smaller than "apply"." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c2f", + "questionid": 356, + "title": "Self Dividing Numbers", + "slug": "self-dividing-numbers", + "description": "A self-dividing number is a number that is divisible by every digit it contains. A self-dividing number is not allowed to contain the digit zero. Given two integers left and right, return a list of all the self-dividing numbers in the range [left, right]. ", + "category": [ + "Math" + ], + "complexity": "Easy", + "successrate": 76.9, + "totalsubmissions": 226706, + "totalaccepted": 174351, + "likes": 1130, + "dislikes": 347, + "hints": "For each number in the range, check whether it is self dividing by converting that number to a character array (or string in Python), then checking that each digit is nonzero and divides the original number.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "left = 1, right = 22", + "expected_output": "[1,2,3,4,5,6,7,8,9,11,12,15,22]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "left = 47, right = 85", + "expected_output": "[48,55,66,77]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c32", + "questionid": 359, + "title": "Asteroid Collision", + "slug": "asteroid-collision", + "description": "We are given an array asteroids of integers representing asteroids in a row. For each asteroid, the absolute value represents its size, and the sign represents its direction (positive meaning right, negative meaning left). Each asteroid moves at the same speed. Find out the state of the asteroids after all collisions. If two asteroids meet, the smaller one will explode. If both are the same size, both will explode. Two asteroids moving in the same direction will never meet. ", + "category": [ + "Array", + "Stack" + ], + "complexity": "Medium", + "successrate": 44.4, + "totalsubmissions": 433907, + "totalaccepted": 192607, + "likes": 3407, + "dislikes": 267, + "hints": "Say a row of asteroids is stable. What happens when a new asteroid is added on the right?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "asteroids = [5,10,-5]", + "expected_output": "[5,10]", + "explanation": "The 10 and -5 collide resulting in 10. The 5 and 10 never collide." + }, + { + "example_num": 2, + "expected_input": "asteroids = [8,-8]", + "expected_output": "[]", + "explanation": "The 8 and -8 collide exploding each other." + }, + { + "example_num": 3, + "expected_input": "asteroids = [10,2,-5]", + "expected_output": "[10]", + "explanation": "The 2 and -5 collide resulting in -5. The 10 and -5 collide resulting in 10." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c34", + "questionid": 361, + "title": "Monotone Increasing Digits", + "slug": "monotone-increasing-digits", + "description": "An integer has monotone increasing digits if and only if each pair of adjacent digits x and y satisfy x <= y. Given an integer n, return the largest number that is less than or equal to n with monotone increasing digits. ", + "category": [ + "Math", + "Greedy" + ], + "complexity": "Medium", + "successrate": 46.7, + "totalsubmissions": 79953, + "totalaccepted": 37361, + "likes": 901, + "dislikes": 87, + "hints": "Build the answer digit by digit, adding the largest possible one that would make the number still less than or equal to N.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 10", + "expected_output": "9", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "n = 1234", + "expected_output": "1234", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "n = 332", + "expected_output": "299", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c35", + "questionid": 362, + "title": "Daily Temperatures", + "slug": "daily-temperatures", + "description": "Given an array of integers temperatures represents the daily temperatures, return an array answer such that answer[i] is the number of days you have to wait after the ith day to get a warmer temperature. If there is no future day for which this is possible, keep answer[i] == 0 instead. ", + "category": [ + "Array", + "Stack", + "Monotonic Stack" + ], + "complexity": "Medium", + "successrate": 67, + "totalsubmissions": 559365, + "totalaccepted": 374997, + "likes": 6760, + "dislikes": 155, + "hints": "If the temperature is say, 70 today, then in the future a warmer temperature must be either 71, 72, 73, ..., 99, or 100. We could remember when all of them occur next.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "temperatures = [73,74,75,71,69,72,76,73]", + "expected_output": "[1,1,4,2,1,1,0,0]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "temperatures = [30,40,50,60]", + "expected_output": "[1,1,1,0]", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "temperatures = [30,60,90]", + "expected_output": "[1,1,0]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c38", + "questionid": 365, + "title": "Find Smallest Letter Greater Than Target", + "slug": "find-smallest-letter-greater-than-target", + "description": "Given a characters array letters that is sorted in non-decreasing order and a character target, return the smallest character in the array that is larger than target. Note that the letters wrap around. ", + "category": [ + "Array", + "Binary Search" + ], + "complexity": "Easy", + "successrate": 45.2, + "totalsubmissions": 402960, + "totalaccepted": 182233, + "likes": 1541, + "dislikes": 1403, + "hints": "Try to find whether each of 26 next letters are in the given string array.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "letters = ["c","f","j"], target = "a"", + "expected_output": ""c"", + "explanation": "The smallest character that is lexicographically greater than 'a' in letters is 'c'." + }, + { + "example_num": 2, + "expected_input": "letters = ["c","f","j"], target = "c"", + "expected_output": ""f"", + "explanation": "The smallest character that is lexicographically greater than 'c' in letters is 'f'." + }, + { + "example_num": 3, + "expected_input": "letters = ["x","x","y","y"], target = "z"", + "expected_output": ""x"", + "explanation": "There are no characters in letters that is lexicographically greater than 'z' so we return letters[0]." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c3d", + "questionid": 370, + "title": "Cracking the Safe", + "slug": "cracking-the-safe", + "description": "There is a safe protected by a password. The password is a sequence of n digits where each digit can be in the range [0, k - 1]. The safe has a peculiar way of checking the password. When you enter in a sequence, it checks the most recent n digits that were entered each time you type a digit. Return any string of minimum length that will unlock the safe at some point of entering it. ", + "category": [ + "Depth-First Search", + "Graph", + "Eulerian Circuit" + ], + "complexity": "Hard", + "successrate": 54.6, + "totalsubmissions": 83640, + "totalaccepted": 45652, + "likes": 194, + "dislikes": 36, + "hints": "We can think of this problem as the problem of finding an Euler path (a path visiting every edge exactly once) on the following graph: there are $$k^{n-1}$$ nodes with each node having $$k$$ edges. It turns out this graph always has an Eulerian circuit (path starting where it ends.)\r\n\r\nWe should visit each node in \"post-order\" so as to not get stuck in the graph prematurely.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 1, k = 2", + "expected_output": ""10"", + "explanation": "The password is a single digit, so enter each digit. "01" would also unlock the safe." + }, + { + "example_num": 2, + "expected_input": "n = 2, k = 2", + "expected_output": ""01100"", + "explanation": "For each possible password:\n- "00" is typed in starting from the 4th digit.\n- "01" is typed in starting from the 1st digit.\n- "10" is typed in starting from the 3rd digit.\n- "11" is typed in starting from the 2nd digit.\nThus "01100" will unlock the safe. "10011", and "11001" would also unlock the safe." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c3e", + "questionid": 371, + "title": "Pyramid Transition Matrix", + "slug": "pyramid-transition-matrix", + "description": "You are stacking blocks to form a pyramid. Each block has a color, which is represented by a single letter. Each row of blocks contains one less block than the row beneath it and is centered on top. To make the pyramid aesthetically pleasing, there are only specific triangular patterns that are allowed. A triangular pattern consists of a single block stacked on top of two blocks. The patterns are given as a list of three-letter strings allowed, where the first two characters of a pattern represent the left and right bottom blocks respectively, and the third character is the top block. You start with a bottom row of blocks bottom, given as a single string, that you must use as the base of the pyramid. Given bottom and allowed, return true if you can build the pyramid all the way to the top such that every triangular pattern in the pyramid is in allowed, or false otherwise. ", + "category": [ + "Bit Manipulation", + "Depth-First Search", + "Breadth-First Search" + ], + "complexity": "Medium", + "successrate": 54.6, + "totalsubmissions": 49490, + "totalaccepted": 27038, + "likes": 450, + "dislikes": 427, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "bottom = "BCD", allowed = ["BCC","CDE","CEA","FFF"]", + "expected_output": "true", + "explanation": "The allowed triangular patterns are shown on the right.\nStarting from the bottom (level 3), we can build "CE" on level 2 and then build "A" on level 1.\nThere are three triangular patterns in the pyramid, which are "BCC", "CDE", and "CEA". All are allowed." + }, + { + "example_num": 2, + "expected_input": "bottom = "AAAA", allowed = ["AAB","AAC","BCD","BBE","DEF"]", + "expected_output": "false", + "explanation": "The allowed triangular patterns are shown on the right.\nStarting from the bottom (level 4), there are multiple ways to build level 3, but trying all the possibilites, you will get always stuck before building level 1." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c3f", + "questionid": 372, + "title": "Set Intersection Size At Least Two", + "slug": "set-intersection-size-at-least-two", + "description": "An integer interval [a, b] (for integers a < b) is a set of all consecutive integers from a to b, including a and b. Find the minimum size of a set S such that for every integer interval A in intervals, the intersection of S with A has a size of at least two. ", + "category": [ + "Array", + "Greedy", + "Sorting" + ], + "complexity": "Hard", + "successrate": 43.1, + "totalsubmissions": 35767, + "totalaccepted": 15431, + "likes": 445, + "dislikes": 59, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "intervals = [[1,3],[3,7],[8,9]]", + "expected_output": "5", + "explanation": "let nums = [2, 3, 4, 8, 9].\nIt can be shown that there cannot be any containing array of size 4." + }, + { + "example_num": 2, + "expected_input": "intervals = [[1,3],[1,4],[2,5],[3,5]]", + "expected_output": "3", + "explanation": "let nums = [2, 3, 4].\nIt can be shown that there cannot be any containing array of size 2." + }, + { + "example_num": 3, + "expected_input": "intervals = [[1,2],[2,3],[2,4],[4,5]]", + "expected_output": "5", + "explanation": "let nums = [1, 2, 3, 4, 5].\nIt can be shown that there cannot be any containing array of size 4." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c40", + "questionid": 373, + "title": "N-ary Tree Level Order Traversal", + "slug": "n-ary-tree-level-order-traversal", + "description": "Given an n-ary tree, return the level order traversal of its nodes' values. Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See examples). ", + "category": [ + "Tree", + "Breadth-First Search" + ], + "complexity": "Medium", + "successrate": 68.8, + "totalsubmissions": 251213, + "totalaccepted": 172915, + "likes": 1774, + "dislikes": 81, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [1,null,3,2,4,null,5,6]", + "expected_output": "[[1],[3,2,4],[5,6]]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]", + "expected_output": "[[1],[2,3,4,5],[6,7,8,9,10],[11,12,13],[14]]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c44", + "questionid": 377, + "title": "Largest Plus Sign", + "slug": "largest-plus-sign", + "description": "You are given an integer n. You have an n x n binary grid grid with all values initially 1's except for some indices given in the array mines. The ith element of the array mines is defined as mines[i] = [xi, yi] where grid[xi][yi] == 0. Return the order of the largest axis-aligned plus sign of 1's contained in grid. If there is none, return 0. An axis-aligned plus sign of 1's of order k has some center grid[r][c] == 1 along with four arms of length k - 1 going up, down, left, and right, and made of 1's. Note that there could be 0's or 1's beyond the arms of the plus sign, only the relevant area of the plus sign is checked for 1's. ", + "category": [ + "Array", + "Dynamic Programming" + ], + "complexity": "Medium", + "successrate": 48.6, + "totalsubmissions": 98947, + "totalaccepted": 48062, + "likes": 1104, + "dislikes": 189, + "hints": "For each direction such as \"left\", find left[r][c] = the number of 1s you will see before a zero starting at r, c and walking left. You can find this in N^2 time with a dp. The largest plus sign at r, c is just the minimum of left[r][c], up[r][c] etc.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 5, mines = [[4,2]]", + "expected_output": "2", + "explanation": "In the above grid, the largest plus sign can only be of order 2. One of them is shown." + }, + { + "example_num": 2, + "expected_input": "n = 1, mines = [[0,0]]", + "expected_output": "0", + "explanation": "There is no plus sign, so return 0." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c4b", + "questionid": 384, + "title": "Max Chunks To Make Sorted II", + "slug": "max-chunks-to-make-sorted-ii", + "description": "You are given an integer array arr. We split arr into some number of chunks (i.e., partitions), and individually sort each chunk. After concatenating them, the result should equal the sorted array. Return the largest number of chunks we can make to sort the array. ", + "category": [ + "Array", + "Stack", + "Greedy", + "Sorting", + "Monotonic Stack" + ], + "complexity": "Hard", + "successrate": 51.9, + "totalsubmissions": 77723, + "totalaccepted": 40366, + "likes": 1141, + "dislikes": 32, + "hints": "Each k for which some permutation of arr[:k] is equal to sorted(arr)[:k] is where we should cut each chunk.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "arr = [5,4,3,2,1]", + "expected_output": "1", + "explanation": "Splitting into two or more chunks will not return the required result.\nFor example, splitting into [5, 4], [3, 2, 1] will result in [4, 5, 1, 2, 3], which isn't sorted." + }, + { + "example_num": 2, + "expected_input": "arr = [2,1,3,4,4]", + "expected_output": "4", + "explanation": "We can split into two chunks, such as [2, 1], [3, 4, 4].\nHowever, splitting into [2, 1], [3], [4], [4] is the highest number of chunks possible." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c0f", + "questionid": 324, + "title": "Maximum Length of Pair Chain", + "slug": "maximum-length-of-pair-chain", + "description": "You are given an array of n pairs pairs where pairs[i] = [lefti, righti] and lefti < righti. A pair p2 = [c, d] follows a pair p1 = [a, b] if b < c. A chain of pairs can be formed in this fashion. Return the length longest chain which can be formed. You do not need to use up all the given intervals. You can select pairs in any order. ", + "category": [ + "Array", + "Dynamic Programming", + "Greedy", + "Sorting" + ], + "complexity": "Medium", + "successrate": 55.6, + "totalsubmissions": 192064, + "totalaccepted": 106828, + "likes": 2190, + "dislikes": 100, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "pairs = [[1,2],[2,3],[3,4]]", + "expected_output": "2", + "explanation": "The longest chain is [1,2] -> [3,4]." + }, + { + "example_num": 2, + "expected_input": "pairs = [[1,2],[7,8],[4,5]]", + "expected_output": "3", + "explanation": "The longest chain is [1,2] -> [4,5] -> [7,8]." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c12", + "questionid": 327, + "title": "Find Duplicate Subtrees", + "slug": "find-duplicate-subtrees", + "description": "Given the root of a binary tree, return all duplicate subtrees. For each kind of duplicate subtrees, you only need to return the root node of any one of them. Two trees are duplicate if they have the same structure with the same node values. ", + "category": [ + "Hash Table", + "Tree", + "Depth-First Search", + "Binary Tree" + ], + "complexity": "Medium", + "successrate": 55.7, + "totalsubmissions": 262584, + "totalaccepted": 146375, + "likes": 3150, + "dislikes": 294, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [1,2,3,4,null,2,4,null,null,4]", + "expected_output": "[[2,4],[4]]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "root = [2,1,1]", + "expected_output": "[[1]]", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "root = [2,2,2,3,null,3,null]", + "expected_output": "[[2,3],[3]]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c13", + "questionid": 328, + "title": "Two Sum IV - Input is a BST", + "slug": "two-sum-iv-input-is-a-bst", + "description": "Given the root of a Binary Search Tree and a target number k, return true if there exist two elements in the BST such that their sum is equal to the given target. ", + "category": [ + "Hash Table", + "Two Pointers", + "Tree", + "Depth-First Search", + "Breadth-First Search", + "Binary Search Tree", + "Binary Tree" + ], + "complexity": "Easy", + "successrate": 58.7, + "totalsubmissions": 515724, + "totalaccepted": 302894, + "likes": 3536, + "dislikes": 199, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [5,3,6,2,4,null,7], k = 9", + "expected_output": "true", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "root = [5,3,6,2,4,null,7], k = 28", + "expected_output": "false", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c18", + "questionid": 333, + "title": "Trim a Binary Search Tree", + "slug": "trim-a-binary-search-tree", + "description": "Given the root of a binary search tree and the lowest and highest boundaries as low and high, trim the tree so that all its elements lies in [low, high]. Trimming the tree should not change the relative structure of the elements that will remain in the tree (i.e., any node's descendant should remain a descendant). It can be proven that there is a unique answer. Return the root of the trimmed binary search tree. Note that the root may change depending on the given bounds. ", + "category": [ + "Tree", + "Depth-First Search", + "Binary Search Tree", + "Binary Tree" + ], + "complexity": "Medium", + "successrate": 66.2, + "totalsubmissions": 345046, + "totalaccepted": 228414, + "likes": 4658, + "dislikes": 236, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [1,0,2], low = 1, high = 2", + "expected_output": "[1,null,2]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "root = [3,0,4,null,2,null,null,1], low = 1, high = 3", + "expected_output": "[3,2,null,1]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c1a", + "questionid": 335, + "title": "Second Minimum Node In a Binary Tree", + "slug": "second-minimum-node-in-a-binary-tree", + "description": "Given a non-empty special binary tree consisting of nodes with the non-negative value, where each node in this tree has exactly two or zero sub-node. If the node has two sub-nodes, then this node's value is the smaller value among its two sub-nodes. More formally, the property root.val = min(root.left.val, root.right.val) always holds. Given such a binary tree, you need to output the second minimum value in the set made of all the nodes' value in the whole tree. If no such second minimum value exists, output -1 instead. ", + "category": [ + "Tree", + "Depth-First Search", + "Binary Tree" + ], + "complexity": "Easy", + "successrate": 43.6, + "totalsubmissions": 314726, + "totalaccepted": 137258, + "likes": 1191, + "dislikes": 1462, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [2,2,5,null,null,5,7]", + "expected_output": "5", + "explanation": "The smallest value is 2, the second smallest value is 5." + }, + { + "example_num": 2, + "expected_input": "root = [2,2,2]", + "expected_output": "-1", + "explanation": "The smallest value is 2, but there isn't any second smallest value." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c1b", + "questionid": 336, + "title": "Number of Longest Increasing Subsequence", + "slug": "number-of-longest-increasing-subsequence", + "description": "Given an integer array nums, return the number of longest increasing subsequences. Notice that the sequence has to be strictly increasing. ", + "category": [ + "Array", + "Dynamic Programming", + "Binary Indexed Tree", + "Segment Tree" + ], + "complexity": "Medium", + "successrate": 40.8, + "totalsubmissions": 267095, + "totalaccepted": 108909, + "likes": 3377, + "dislikes": 163, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,3,5,4,7]", + "expected_output": "2", + "explanation": "The two longest increasing subsequences are [1, 3, 4, 7] and [1, 3, 5, 7]." + }, + { + "example_num": 2, + "expected_input": "nums = [2,2,2,2,2]", + "expected_output": "5", + "explanation": "The length of the longest increasing subsequence is 1, and there are 5 increasing subsequences of length 1, so output 5." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c20", + "questionid": 341, + "title": "Longest Univalue Path", + "slug": "longest-univalue-path", + "description": "Given the root of a binary tree, return the length of the longest path, where each node in the path has the same value. This path may or may not pass through the root. The length of the path between two nodes is represented by the number of edges between them. ", + "category": [ + "Tree", + "Depth-First Search", + "Binary Tree" + ], + "complexity": "Medium", + "successrate": 39.3, + "totalsubmissions": 355853, + "totalaccepted": 139892, + "likes": 3041, + "dislikes": 607, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [5,4,5,1,1,null,5]", + "expected_output": "2", + "explanation": "The shown image shows that the longest path of the same value (i.e. 5)." + }, + { + "example_num": 2, + "expected_input": "root = [1,4,5,4,4,null,5]", + "expected_output": "2", + "explanation": "The shown image shows that the longest path of the same value (i.e. 4)." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c24", + "questionid": 345, + "title": "Max Area of Island", + "slug": "max-area-of-island", + "description": "You are given an m x n binary matrix grid. An island is a group of 1's (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water. The area of an island is the number of cells with a value 1 in the island. Return the maximum area of an island in grid. If there is no island, return 0. ", + "category": [ + "Array", + "Depth-First Search", + "Breadth-First Search", + "Union Find", + "Matrix" + ], + "complexity": "Medium", + "successrate": 69.6, + "totalsubmissions": 648302, + "totalaccepted": 450928, + "likes": 5777, + "dislikes": 144, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "grid = [[0,0,1,0,0,0,0,1,0,0,0,0,0],[0,0,0,0,0,0,0,1,1,1,0,0,0],[0,1,1,0,1,0,0,0,0,0,0,0,0],[0,1,0,0,1,1,0,0,1,0,1,0,0],[0,1,0,0,1,1,0,0,1,1,1,0,0],[0,0,0,0,0,0,0,0,0,0,1,0,0],[0,0,0,0,0,0,0,1,1,1,0,0,0],[0,0,0,0,0,0,0,1,1,0,0,0,0]]", + "expected_output": "6", + "explanation": "The answer is not 11, because the island must be connected 4-directionally." + }, + { + "example_num": 2, + "expected_input": "grid = [[0,0,0,0,0,0,0,0]]", + "expected_output": "0", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c30", + "questionid": 357, + "title": "Count Different Palindromic Subsequences", + "slug": "count-different-palindromic-subsequences", + "description": "Given a string s, return the number of different non-empty palindromic subsequences in s. Since the answer may be very large, return it modulo 109 + 7. A subsequence of a string is obtained by deleting zero or more characters from the string. A sequence is palindromic if it is equal to the sequence reversed. Two sequences a1, a2, ... and b1, b2, ... are different if there is some i for which ai != bi. ", + "category": [ + "String", + "Dynamic Programming" + ], + "complexity": "Hard", + "successrate": 44.3, + "totalsubmissions": 59687, + "totalaccepted": 26437, + "likes": 1270, + "dislikes": 68, + "hints": "Let dp(i, j) be the answer for the string T = S[i:j+1] including the empty sequence. The answer is the number of unique characters in T, plus palindromes of the form \"a_a\", \"b_b\", \"c_c\", and \"d_d\", where \"_\" represents zero or more characters.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "bccb"", + "expected_output": "6", + "explanation": "The 6 different non-empty palindromic subsequences are 'b', 'c', 'bb', 'cc', 'bcb', 'bccb'.\nNote that 'bcb' is counted only once, even though it occurs twice." + }, + { + "example_num": 2, + "expected_input": "s = "abcdabcdabcdabcdabcdabcdabcdabcddcbadcbadcbadcbadcbadcbadcbadcba"", + "expected_output": "104860361", + "explanation": "There are 3104860382 different non-empty palindromic subsequences, which is 104860361 modulo 109 + 7." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c31", + "questionid": 358, + "title": "Flood Fill", + "slug": "flood-fill", + "description": "An image is represented by an m x n integer grid image where image[i][j] represents the pixel value of the image. You are also given three integers sr, sc, and newColor. You should perform a flood fill on the image starting from the pixel image[sr][sc]. To perform a flood fill, consider the starting pixel, plus any pixels connected 4-directionally to the starting pixel of the same color as the starting pixel, plus any pixels connected 4-directionally to those pixels (also with the same color), and so on. Replace the color of all of the aforementioned pixels with newColor. Return the modified image after performing the flood fill. ", + "category": [ + "Array", + "Depth-First Search", + "Breadth-First Search", + "Matrix" + ], + "complexity": "Easy", + "successrate": 58.2, + "totalsubmissions": 673313, + "totalaccepted": 391611, + "likes": 3924, + "dislikes": 373, + "hints": "Write a recursive function that paints the pixel if it's the correct color, then recurses on neighboring pixels.", + "deleted": false, + "examples": [] + }, + { + "_id": "66f925ddfdfb8e1665720c33", + "questionid": 360, + "title": "Parse Lisp Expression", + "slug": "parse-lisp-expression", + "description": "You are given a string expression representing a Lisp-like expression to return the integer value of. The syntax for these expressions is given as follows. ", + "category": [ + "Hash Table", + "String", + "Stack", + "Recursion" + ], + "complexity": "Hard", + "successrate": 51.2, + "totalsubmissions": 35889, + "totalaccepted": 18389, + "likes": 386, + "dislikes": 304, + "hints": "* If the expression starts with a digit or '-', it's an integer: return it.\r\n\r\n* If the expression starts with a letter, it's a variable. Recall it by checking the current scope in reverse order.\r\n\r\n* Otherwise, group the tokens (variables or expressions) within this expression by counting the \"balance\" `bal` of the occurrences of `'('` minus the number of occurrences of `')'`. When the balance is zero, we have ended a token. For example, `(add 1 (add 2 3))` should have tokens `'1'` and `'(add 2 3)'`.\r\n\r\n* For add and mult expressions, evaluate each token and return the addition or multiplication of them.\r\n\r\n* For let expressions, evaluate each expression sequentially and assign it to the variable in the current scope, then return the evaluation of the final expression.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "expression = "(let x 2 (mult x (let x 3 y 4 (add x y))))"", + "expected_output": "14", + "explanation": "In the expression (add x y), when checking for the value of the variable x,\nwe check from the innermost scope to the outermost in the context of the variable we are trying to evaluate.\nSince x = 3 is found first, the value of x is 3." + }, + { + "example_num": 2, + "expected_input": "expression = "(let x 3 x 2 x)"", + "expected_output": "2", + "explanation": "Assignment in let statements is processed sequentially." + }, + { + "example_num": 3, + "expected_input": "expression = "(let x 1 y 2 x (add x y) (add x y))"", + "expected_output": "5", + "explanation": "The first (add x y) evaluates as 3, and is assigned to x.\nThe second (add x y) evaluates as 3+2 = 5." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c39", + "questionid": 366, + "title": "Min Cost Climbing Stairs", + "slug": "min-cost-climbing-stairs", + "description": "You are given an integer array cost where cost[i] is the cost of ith step on a staircase. Once you pay the cost, you can either climb one or two steps. You can either start from the step with index 0, or the step with index 1. Return the minimum cost to reach the top of the floor. ", + "category": [ + "Array", + "Dynamic Programming" + ], + "complexity": "Easy", + "successrate": 58.6, + "totalsubmissions": 769739, + "totalaccepted": 450967, + "likes": 5723, + "dislikes": 992, + "hints": "Say f[i] is the final cost to climb to the top from step i. Then f[i] = cost[i] + min(f[i+1], f[i+2]).", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "cost = [10,15,20]", + "expected_output": "15", + "explanation": "You will start at index 1.\n- Pay 15 and climb two steps to reach the top.\nThe total cost is 15." + }, + { + "example_num": 2, + "expected_input": "cost = [1,100,1,1,1,100,1,1,100,1]", + "expected_output": "6", + "explanation": "You will start at index 0.\n- Pay 1 and climb two steps to reach index 2.\n- Pay 1 and climb two steps to reach index 4.\n- Pay 1 and climb two steps to reach index 6.\n- Pay 1 and climb one step to reach index 7.\n- Pay 1 and climb two steps to reach index 9.\n- Pay 1 and climb one step to reach the top.\nThe total cost is 6." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c48", + "questionid": 381, + "title": "N-ary Tree Postorder Traversal", + "slug": "n-ary-tree-postorder-traversal", + "description": "Given the root of an n-ary tree, return the postorder traversal of its nodes' values. Nary-Tree input serialization is represented in their level order traversal. Each group of children is separated by the null value (See examples) ", + "category": [ + "Stack", + "Tree", + "Depth-First Search" + ], + "complexity": "Easy", + "successrate": 76.1, + "totalsubmissions": 234316, + "totalaccepted": 178336, + "likes": 1553, + "dislikes": 82, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [1,null,3,2,4,null,5,6]", + "expected_output": "[5,6,3,2,4,1]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]", + "expected_output": "[2,6,14,11,7,3,12,8,4,13,9,10,5,1]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c50", + "questionid": 389, + "title": "Sliding Puzzle", + "slug": "sliding-puzzle", + "description": "On an 2 x 3 board, there are five tiles labeled from 1 to 5, and an empty square represented by 0. A move consists of choosing 0 and a 4-directionally adjacent number and swapping it. The state of the board is solved if and only if the board is [[1,2,3],[4,5,0]]. Given the puzzle board board, return the least number of moves required so that the state of the board is solved. If it is impossible for the state of the board to be solved, return -1. ", + "category": [ + "Array", + "Breadth-First Search", + "Matrix" + ], + "complexity": "Hard", + "successrate": 63.1, + "totalsubmissions": 111608, + "totalaccepted": 70414, + "likes": 1461, + "dislikes": 37, + "hints": "Perform a breadth-first-search, where the nodes are the puzzle boards and edges are if two puzzle boards can be transformed into one another with one move.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "board = [[1,2,3],[4,0,5]]", + "expected_output": "1", + "explanation": "Swap the 0 and the 5 in one move." + }, + { + "example_num": 2, + "expected_input": "board = [[1,2,3],[5,4,0]]", + "expected_output": "-1", + "explanation": "No number of moves will make the board solved." + }, + { + "example_num": 3, + "expected_input": "board = [[4,1,2],[5,0,3]]", + "expected_output": "5", + "explanation": "5 is the smallest number of moves that solves the board.\nAn example path:\nAfter move 0: [[4,1,2],[5,0,3]]\nAfter move 1: [[4,1,2],[0,5,3]]\nAfter move 2: [[0,1,2],[4,5,3]]\nAfter move 3: [[1,0,2],[4,5,3]]\nAfter move 4: [[1,2,0],[4,5,3]]\nAfter move 5: [[1,2,3],[4,5,0]]" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c4c", + "questionid": 385, + "title": "Max Chunks To Make Sorted", + "slug": "max-chunks-to-make-sorted", + "description": "You are given an integer array arr of length n that represents a permutation of the integers in the range [0, n - 1]. We split arr into some number of chunks (i.e., partitions), and individually sort each chunk. After concatenating them, the result should equal the sorted array. Return the largest number of chunks we can make to sort the array. ", + "category": [ + "Array", + "Stack", + "Greedy", + "Sorting", + "Monotonic Stack" + ], + "complexity": "Medium", + "successrate": 57.6, + "totalsubmissions": 122156, + "totalaccepted": 70386, + "likes": 1828, + "dislikes": 182, + "hints": "The first chunk can be found as the smallest k for which A[:k+1] == [0, 1, 2, ...k]; then we repeat this process.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "arr = [4,3,2,1,0]", + "expected_output": "1", + "explanation": "Splitting into two or more chunks will not return the required result.\nFor example, splitting into [4, 3], [2, 1, 0] will result in [3, 4, 0, 1, 2], which isn't sorted." + }, + { + "example_num": 2, + "expected_input": "arr = [1,0,2,3,4]", + "expected_output": "4", + "explanation": "We can split into two chunks, such as [1, 0], [2, 3, 4].\nHowever, splitting into [1, 0], [2], [3], [4] is the highest number of chunks possible." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c54", + "questionid": 393, + "title": "K-th Symbol in Grammar", + "slug": "k-th-symbol-in-grammar", + "description": "We build a table of n rows (1-indexed). We start by writing 0 in the 1st row. Now in every subsequent row, we look at the previous row and replace each occurrence of 0 with 01, and each occurrence of 1 with 10. Given two integer n and k, return the kth (1-indexed) symbol in the nth row of a table of n rows. ", + "category": [ + "Math", + "Bit Manipulation", + "Recursion" + ], + "complexity": "Medium", + "successrate": 39.9, + "totalsubmissions": 208528, + "totalaccepted": 83191, + "likes": 1671, + "dislikes": 246, + "hints": "Try to represent the current (N, K) in terms of some (N-1, prevK). What is prevK ?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 1, k = 1", + "expected_output": "0", + "explanation": "row 1: 0" + }, + { + "example_num": 2, + "expected_input": "n = 2, k = 1", + "expected_output": "0", + "explanation": "row 1: 0\nrow 2: 01" + }, + { + "example_num": 3, + "expected_input": "n = 2, k = 2", + "expected_output": "1", + "explanation": "row 1: 0\nrow 2: 01" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c56", + "questionid": 395, + "title": "Rabbits in Forest", + "slug": "rabbits-in-forest", + "description": "There is a forest with an unknown number of rabbits. We asked n rabbits \"How many rabbits have the same color as you?\" and collected the answers in an integer array answers where answers[i] is the answer of the ith rabbit. Given the array answers, return the minimum number of rabbits that could be in the forest. ", + "category": [ + "Array", + "Hash Table", + "Math", + "Greedy" + ], + "complexity": "Medium", + "successrate": 55.7, + "totalsubmissions": 64908, + "totalaccepted": 36151, + "likes": 709, + "dislikes": 484, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "answers = [1,1,2]", + "expected_output": "5", + "explanation": "The two rabbits that answered "1" could both be the same color, say red.\nThe rabbit that answered "2" can't be red or the answers would be inconsistent.\nSay the rabbit that answered "2" was blue.\nThen there should be 2 other blue rabbits in the forest that didn't answer into the array.\nThe smallest possible number of rabbits in the forest is therefore 5: 3 that answered plus 2 that didn't." + }, + { + "example_num": 2, + "expected_input": "answers = [10,10,10]", + "expected_output": "11", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c60", + "questionid": 405, + "title": "Rotate String", + "slug": "rotate-string", + "description": "Given two strings s and goal, return true if and only if s can become goal after some number of shifts on s. A shift on s consists of moving the leftmost character of s to the rightmost position. ", + "category": [ + "String", + "String Matching" + ], + "complexity": "Easy", + "successrate": 52.1, + "totalsubmissions": 277996, + "totalaccepted": 144895, + "likes": 1783, + "dislikes": 84, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = \"abcde\", goal = \"cdeab\"", + "expected_output": "true", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "s = \"abcde\", goal = \"abced\"", + "expected_output": "false", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c61", + "questionid": 406, + "title": "Smallest Rotation with Highest Score", + "slug": "smallest-rotation-with-highest-score", + "description": "You are given an array nums. You can rotate it by a non-negative integer k so that the array becomes [nums[k], nums[k + 1], ... nums[nums.length - 1], nums[0], nums[1], ..., nums[k-1]]. Afterward, any entries that are less than or equal to their index are worth one point. Return the rotation index k that corresponds to the highest score we can achieve if we rotated nums by it. If there are multiple answers, return the smallest such index k. ", + "category": [ + "Array", + "Prefix Sum" + ], + "complexity": "Hard", + "successrate": 47.4, + "totalsubmissions": 18253, + "totalaccepted": 8659, + "likes": 351, + "dislikes": 21, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [2,3,1,4,0]", + "expected_output": "3", + "explanation": "Scores for each k are listed below: \nk = 0, nums = [2,3,1,4,0], score 2\nk = 1, nums = [3,1,4,0,2], score 3\nk = 2, nums = [1,4,0,2,3], score 3\nk = 3, nums = [4,0,2,3,1], score 4\nk = 4, nums = [0,2,3,1,4], score 3\nSo we should choose k = 3, which has the highest score." + }, + { + "example_num": 2, + "expected_input": "nums = [1,3,0,2,4]", + "expected_output": "0", + "explanation": "nums will always have 3 points no matter how it shifts.\nSo we will choose the smallest k, which is 0." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c67", + "questionid": 412, + "title": "Chalkboard XOR Game", + "slug": "chalkboard-xor-game", + "description": "You are given an array of integers nums represents the numbers written on a chalkboard. Alice and Bob take turns erasing exactly one number from the chalkboard, with Alice starting first. If erasing a number causes the bitwise XOR of all the elements of the chalkboard to become 0, then that player loses. The bitwise XOR of one element is that element itself, and the bitwise XOR of no elements is 0. Also, if any player starts their turn with the bitwise XOR of all the elements of the chalkboard equal to 0, then that player wins. Return true if and only if Alice wins the game, assuming both players play optimally. ", + "category": [ + "Array", + "Math", + "Bit Manipulation", + "Brainteaser", + "Game Theory" + ], + "complexity": "Hard", + "successrate": 53.3, + "totalsubmissions": 12094, + "totalaccepted": 6444, + "likes": 126, + "dislikes": 235, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,1,2]", + "expected_output": "false", + "explanation": "Alice has two choices: erase 1 or erase 2. \nIf she erases 1, the nums array becomes [1, 2]. The bitwise XOR of all the elements of the chalkboard is 1 XOR 2 = 3. Now Bob can remove any element he wants, because Alice will be the one to erase the last element and she will lose. \nIf Alice erases 2 first, now nums become [1, 1]. The bitwise XOR of all the elements of the chalkboard is 1 XOR 1 = 0. Alice will lose." + }, + { + "example_num": 2, + "expected_input": "nums = [0,1]", + "expected_output": "true", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "nums = [1,2,3]", + "expected_output": "true", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c6a", + "questionid": 415, + "title": "Largest Sum of Averages", + "slug": "largest-sum-of-averages", + "description": "You are given an integer array nums and an integer k. You can partition the array into at most k non-empty adjacent subarrays. The score of a partition is the sum of the averages of each subarray. Note that the partition must use every integer in nums, and that the score is not necessarily an integer. Return the maximum score you can achieve of all the possible partitions. Answers within 10-6 of the actual answer will be accepted. ", + "category": [ + "Array", + "Dynamic Programming" + ], + "complexity": "Medium", + "successrate": 52.4, + "totalsubmissions": 75480, + "totalaccepted": 39546, + "likes": 1547, + "dislikes": 76, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [9,1,2,3,9], k = 3", + "expected_output": "20.00000", + "explanation": "The best choice is to partition nums into [9], [1, 2, 3], [9]. The answer is 9 + (1 + 2 + 3) / 3 + 9 = 20.\nWe could have also partitioned nums into [9, 1], [2], [3, 9], for example.\nThat partition would lead to a score of 5 + 2 + 6 = 13, which is worse." + }, + { + "example_num": 2, + "expected_input": "nums = [1,2,3,4,5,6,7], k = 4", + "expected_output": "20.50000", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c6d", + "questionid": 418, + "title": "Ambiguous Coordinates", + "slug": "ambiguous-coordinates", + "description": "We had some 2-dimensional coordinates, like \"(1, 3)\" or \"(2, 0.5)\". Then, we removed all commas, decimal points, and spaces and ended up with the string s. Return a list of strings representing all possibilities for what our original coordinates could have been. Our original representation never had extraneous zeroes, so we never started with numbers like \"00\", \"0.0\", \"0.00\", \"1.0\", \"001\", \"00.01\", or any other number that can be represented with fewer digits. Also, a decimal point within a number never occurs without at least one digit occurring before it, so we never started with numbers like \".1\". The final answer list can be returned in any order. All coordinates in the final answer have exactly one space between them (occurring after the comma.) ", + "category": [ + "String", + "Backtracking" + ], + "complexity": "Medium", + "successrate": 55.9, + "totalsubmissions": 45529, + "totalaccepted": 25467, + "likes": 251, + "dislikes": 588, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "(123)"", + "expected_output": "["(1, 2.3)","(1, 23)","(1.2, 3)","(12, 3)"]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "s = "(0123)"", + "expected_output": "["(0, 1.23)","(0, 12.3)","(0, 123)","(0.1, 2.3)","(0.1, 23)","(0.12, 3)"]", + "explanation": "0.0, 00, 0001 or 00.01 are not allowed." + }, + { + "example_num": 3, + "expected_input": "s = "(00011)"", + "expected_output": "["(0, 0.011)","(0.001, 1)"]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c71", + "questionid": 422, + "title": "Card Flipping Game", + "slug": "card-flipping-game", + "description": "You are given n cards, with a positive integer printed on the front and back of each card (possibly different). You can flip any number of cards (possibly zero). After choosing the front and the back of each card, you will pick each card, and if the integer printed on the back of this card is not printed on the front of any other card, then this integer is good. You are given two integer array fronts and backs where fronts[i] and backs[i] are the integers printer on the front and the back of the ith card respectively. Return the smallest good and integer after flipping the cards. If there are no good integers, return 0. Note that a flip swaps the front and back numbers, so the value on the front is now on the back and vice versa. ", + "category": [ + "Array", + "Hash Table" + ], + "complexity": "Medium", + "successrate": 44.6, + "totalsubmissions": 28904, + "totalaccepted": 12902, + "likes": 110, + "dislikes": 628, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "fronts = [1,2,4,4,7], backs = [1,3,4,1,3]", + "expected_output": "2", + "explanation": "If we flip the second card, the face up numbers are [1,3,4,4,7] and the face down are [1,2,4,1,3].\n2 is the minimum good integer as it appears facing down but not facing up.\nIt can be shown that 2 is the minimum possible good integer obtainable after flipping some cards." + }, + { + "example_num": 2, + "expected_input": "fronts = [1], backs = [1]", + "expected_output": "0", + "explanation": "There are no good integers no matter how we flip the cards, so we return 0." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c7c", + "questionid": 433, + "title": "Magic Squares In Grid", + "slug": "magic-squares-in-grid", + "description": "A 3 x 3 magic square is a 3 x 3 grid filled with distinct numbers from 1 to 9 such that each row, column, and both diagonals all have the same sum. Given a row x col grid of integers, how many 3 x 3 \"magic square\" subgrids are there?  (Each subgrid is contiguous). ", + "category": [ + "Array", + "Math", + "Matrix" + ], + "complexity": "Medium", + "successrate": 38.3, + "totalsubmissions": 83432, + "totalaccepted": 31992, + "likes": 245, + "dislikes": 1450, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "grid = [[4,3,8,4],[9,5,1,9],[2,7,6,2]]", + "expected_output": "1\nExplanation: \nThe following subgrid is a 3 x 3 magic square:\n\"\"\nwhile this one is not:\n\"\"\nIn total, there is only one magic square inside the given grid.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "grid = [[8]]", + "expected_output": "0", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c7e", + "questionid": 435, + "title": "Guess the Word", + "slug": "guess-the-word", + "description": "This is an interactive problem. You are given an array of unique strings wordlist where wordlist[i] is 6 letters long, and one word in this list is chosen as secret. You may call Master.guess(word) to guess a word. The guessed word should have type string and must be from the original list with 6 lowercase letters. This function returns an integer type, representing the number of exact matches (value and position) of your guess to the secret word. Also, if your guess is not in the given wordlist, it will return -1 instead. For each test case, you have exactly 10 guesses to guess the word. At the end of any number of calls, if you have made 10 or fewer calls to Master.guess and at least one of these guesses was secret, then you pass the test case. ", + "category": [ + "Array", + "Math", + "String", + "Interactive", + "Game Theory" + ], + "complexity": "Hard", + "successrate": 43.1, + "totalsubmissions": 263498, + "totalaccepted": 113453, + "likes": 1196, + "dislikes": 1331, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "secret = "acckzz", words = ["acckzz","ccbazz","eiowzz","abcczz"], allowedGuesses = 10", + "expected_output": "You guessed the secret word correctly.", + "explanation": "master.guess("aaaaaa") returns -1, because "aaaaaa" is not in wordlist.\nmaster.guess("acckzz") returns 6, because "acckzz" is secret and has all 6 matches.\nmaster.guess("ccbazz") returns 3, because "ccbazz" has 3 matches.\nmaster.guess("eiowzz") returns 2, because "eiowzz" has 2 matches.\nmaster.guess("abcczz") returns 4, because "abcczz" has 4 matches.\nWe made 5 calls to master.guess, and one of them was the secret, so we pass the test case." + }, + { + "example_num": 2, + "expected_input": "secret = "hamada", words = ["hamada","khaled"], allowedGuesses = 10", + "expected_output": "You guessed the secret word correctly.", + "explanation": "Since there are two words, you can guess both." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c81", + "questionid": 438, + "title": "Shortest Path Visiting All Nodes", + "slug": "shortest-path-visiting-all-nodes", + "description": "You have an undirected, connected graph of n nodes labeled from 0 to n - 1. You are given an array graph where graph[i] is a list of all the nodes connected with node i by an edge. Return the length of the shortest path that visits every node. You may start and stop at any node, you may revisit nodes multiple times, and you may reuse edges. ", + "category": [ + "Dynamic Programming", + "Bit Manipulation", + "Breadth-First Search", + "Graph", + "Bitmask" + ], + "complexity": "Hard", + "successrate": 61.2, + "totalsubmissions": 90353, + "totalaccepted": 55288, + "likes": 2362, + "dislikes": 121, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "graph = [[1,2,3],[0],[0],[0]]", + "expected_output": "4", + "explanation": "One possible path is [1,0,2,0,3]" + }, + { + "example_num": 2, + "expected_input": "graph = [[1],[0,2,4],[1,3,4],[2],[1,2]]", + "expected_output": "4", + "explanation": "One possible path is [0,1,4,2,3]" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c82", + "questionid": 439, + "title": "Shifting Letters", + "slug": "shifting-letters", + "description": "You are given a string s of lowercase English letters and an integer array shifts of the same length. Call the shift() of a letter, the next letter in the alphabet, (wrapping around so that 'z' becomes 'a'). Now for each shifts[i] = x, we want to shift the first i + 1 letters of s, x times. Return the final string after all such shifts to s are applied. ", + "category": [ + "Array", + "String" + ], + "complexity": "Medium", + "successrate": 45.4, + "totalsubmissions": 157075, + "totalaccepted": 71387, + "likes": 849, + "dislikes": 96, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "abc", shifts = [3,5,9]", + "expected_output": ""rpl"", + "explanation": "We start with "abc".\nAfter shifting the first 1 letters of s by 3, we have "dbc".\nAfter shifting the first 2 letters of s by 5, we have "igc".\nAfter shifting the first 3 letters of s by 9, we have "rpl", the answer." + }, + { + "example_num": 2, + "expected_input": "s = "aaa", shifts = [1,2,3]", + "expected_output": ""gfd"", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c88", + "questionid": 445, + "title": "Mirror Reflection", + "slug": "mirror-reflection", + "description": "There is a special square room with mirrors on each of the four walls. Except for the southwest corner, there are receptors on each of the remaining corners, numbered 0, 1, and 2. The square room has walls of length p and a laser ray from the southwest corner first meets the east wall at a distance q from the 0th receptor. Given the two integers p and q, return the number of the receptor that the ray meets first. The test cases are guaranteed so that the ray will meet a receptor eventually. ", + "category": [ + "Math", + "Geometry" + ], + "complexity": "Medium", + "successrate": 59.6, + "totalsubmissions": 44050, + "totalaccepted": 26258, + "likes": 366, + "dislikes": 712, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "p = 2, q = 1", + "expected_output": "2", + "explanation": "The ray meets receptor 2 the first time it gets reflected back to the left wall." + }, + { + "example_num": 2, + "expected_input": "p = 3, q = 1", + "expected_output": "1", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c4d", + "questionid": 386, + "title": "Jewels and Stones", + "slug": "jewels-and-stones", + "description": "You're given strings jewels representing the types of stones that are jewels, and stones representing the stones you have. Each character in stones is a type of stone you have. You want to know how many of the stones you have are also jewels. Letters are case sensitive, so \"a\" is considered a different type of stone from \"A\". ", + "category": [ + "Hash Table", + "String" + ], + "complexity": "Easy", + "successrate": 87.7, + "totalsubmissions": 832734, + "totalaccepted": 730256, + "likes": 3471, + "dislikes": 484, + "hints": "For each stone, check if it is a jewel.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "jewels = \"aA\", stones = \"aAAbbbb\"", + "expected_output": "3", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "jewels = \"z\", stones = \"ZZ\"", + "expected_output": "0", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c4e", + "questionid": 387, + "title": "Search in a Binary Search Tree", + "slug": "search-in-a-binary-search-tree", + "description": "You are given the root of a binary search tree (BST) and an integer val. Find the node in the BST that the node's value equals val and return the subtree rooted with that node. If such a node does not exist, return null. ", + "category": [ + "Tree", + "Binary Search Tree", + "Binary Tree" + ], + "complexity": "Easy", + "successrate": 76.3, + "totalsubmissions": 614317, + "totalaccepted": 468905, + "likes": 3234, + "dislikes": 150, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [4,2,7,1,3], val = 2", + "expected_output": "[2,1,3]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "root = [4,2,7,1,3], val = 5", + "expected_output": "[]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c4f", + "questionid": 388, + "title": "Insert into a Binary Search Tree", + "slug": "insert-into-a-binary-search-tree", + "description": "You are given the root node of a binary search tree (BST) and a value to insert into the tree. Return the root node of the BST after the insertion. It is guaranteed that the new value does not exist in the original BST. Notice that there may exist multiple valid ways for the insertion, as long as the tree remains a BST after insertion. You can return any of them. ", + "category": [ + "Tree", + "Binary Search Tree", + "Binary Tree" + ], + "complexity": "Medium", + "successrate": 74.9, + "totalsubmissions": 398561, + "totalaccepted": 298712, + "likes": 3244, + "dislikes": 141, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [4,2,7,1,3], val = 5", + "expected_output": "[4,2,7,1,3,5]", + "explanation": "Another accepted tree is:\n\"\"" + }, + { + "example_num": 2, + "expected_input": "root = [40,20,60,10,30,50,70], val = 25", + "expected_output": "[40,20,60,10,30,50,70,null,null,25]", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "root = [4,2,7,1,3,null,null,null,null,null,null], val = 5", + "expected_output": "[4,2,7,1,3,5]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c5c", + "questionid": 401, + "title": "Custom Sort String", + "slug": "custom-sort-string", + "description": "You are given two strings order and s. All the words of order are unique and were sorted in some custom order previously. Permute the characters of s so that they match the order that order was sorted. More specifically, if a character x occurs before a character y in order, then x should occur before y in the permuted string. Return any permutation of s that satisfies this property. ", + "category": [ + "Hash Table", + "String", + "Sorting" + ], + "complexity": "Medium", + "successrate": 69, + "totalsubmissions": 253659, + "totalaccepted": 175117, + "likes": 1969, + "dislikes": 285, + "hints": "", + "deleted": false, + "examples": [] + }, + { + "_id": "66f925ddfdfb8e1665720c5e", + "questionid": 403, + "title": "Preimage Size of Factorial Zeroes Function", + "slug": "preimage-size-of-factorial-zeroes-function", + "description": "Let f(x) be the number of zeroes at the end of x!. Recall that x! = 1 * 2 * 3 * ... * x and by convention, 0! = 1. Given an integer k, return the number of non-negative integers x have the property that f(x) = k. ", + "category": [ + "Math", + "Binary Search" + ], + "complexity": "Hard", + "successrate": 41.6, + "totalsubmissions": 28933, + "totalaccepted": 12050, + "likes": 298, + "dislikes": 68, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "k = 0", + "expected_output": "5", + "explanation": "0!, 1!, 2!, 3!, and 4! end with k = 0 zeroes." + }, + { + "example_num": 2, + "expected_input": "k = 5", + "expected_output": "0", + "explanation": "There is no x such that x! ends in k = 5 zeroes." + }, + { + "example_num": 3, + "expected_input": "k = 3", + "expected_output": "5", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c62", + "questionid": 407, + "title": "Champagne Tower", + "slug": "champagne-tower", + "description": "We stack glasses in a pyramid, where the first row has 1 glass, the second row has 2 glasses, and so on until the 100th row.  Each glass holds one cup of champagne. Then, some champagne is poured into the first glass at the top.  When the topmost glass is full, any excess liquid poured will fall equally to the glass immediately to the left and right of it.  When those glasses become full, any excess champagne will fall equally to the left and right of those glasses, and so on.  (A glass at the bottom row has its excess champagne fall on the floor.) For example, after one cup of champagne is poured, the top most glass is full.  After two cups of champagne are poured, the two glasses on the second row are half full.  After three cups of champagne are poured, those two cups become full - there are 3 full glasses total now.  After four cups of champagne are poured, the third row has the middle glass half full, and the two outside glasses are a quarter full, as pictured below. Now after pouring some non-negative integer cups of champagne, return how full the jth glass in the ith row is (both i and j are 0-indexed.) ", + "category": [ + "Dynamic Programming" + ], + "complexity": "Medium", + "successrate": 51.2, + "totalsubmissions": 146739, + "totalaccepted": 75161, + "likes": 2315, + "dislikes": 128, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "poured = 1, query_row = 1, query_glass = 1", + "expected_output": "0.00000", + "explanation": "We poured 1 cup of champange to the top glass of the tower (which is indexed as (0, 0)). There will be no excess liquid so all the glasses under the top glass will remain empty." + }, + { + "example_num": 2, + "expected_input": "poured = 2, query_row = 1, query_glass = 1", + "expected_output": "0.50000", + "explanation": "We poured 2 cups of champange to the top glass of the tower (which is indexed as (0, 0)). There is one cup of excess liquid. The glass indexed as (1, 0) and the glass indexed as (1, 1) will share the excess liquid equally, and each will get half cup of champange." + }, + { + "example_num": 3, + "expected_input": "poured = 100000009, query_row = 33, query_glass = 17", + "expected_output": "1.00000", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c63", + "questionid": 408, + "title": "Minimum Swaps To Make Sequences Increasing", + "slug": "minimum-swaps-to-make-sequences-increasing", + "description": "You are given two integer arrays of the same length nums1 and nums2. In one operation, you are allowed to swap nums1[i] with nums2[i]. Return the minimum number of needed operations to make nums1 and nums2 strictly increasing. The test cases are generated so that the given input always makes it possible. An array arr is strictly increasing if and only if arr[0] < arr[1] < arr[2] < ... < arr[arr.length - 1]. ", + "category": [ + "Array", + "Dynamic Programming" + ], + "complexity": "Hard", + "successrate": 39.2, + "totalsubmissions": 133894, + "totalaccepted": 52429, + "likes": 1974, + "dislikes": 123, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums1 = [1,3,5,4], nums2 = [1,2,3,7]", + "expected_output": "1", + "explanation": "Swap nums1[3] and nums2[3]. Then the sequences are:\nnums1 = [1, 3, 5, 7] and nums2 = [1, 2, 3, 4]\nwhich are both strictly increasing." + }, + { + "example_num": 2, + "expected_input": "nums1 = [0,3,5,8,9], nums2 = [2,1,4,6,9]", + "expected_output": "1", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c65", + "questionid": 410, + "title": "Split Array With Same Average", + "slug": "split-array-with-same-average", + "description": "You are given an integer array nums. You should move each element of nums into one of the two arrays A and B such that A and B are non-empty, and average(A) == average(B). Return true if it is possible to achieve that and false otherwise. Note that for an array arr, average(arr) is the sum of all the elements of arr over the length of arr. ", + "category": [ + "Array", + "Math", + "Dynamic Programming", + "Bit Manipulation", + "Bitmask" + ], + "complexity": "Hard", + "successrate": 26.5, + "totalsubmissions": 95370, + "totalaccepted": 25304, + "likes": 804, + "dislikes": 115, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,2,3,4,5,6,7,8]", + "expected_output": "true", + "explanation": "We can split the array into [1,4,5,8] and [2,3,6,7], and both of them have an average of 4.5." + }, + { + "example_num": 2, + "expected_input": "nums = [3,1]", + "expected_output": "false", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c69", + "questionid": 414, + "title": "Largest Triangle Area", + "slug": "largest-triangle-area", + "description": "Given an array of points on the X-Y plane points where points[i] = [xi, yi], return the area of the largest triangle that can be formed by any three different points. Answers within 10-5 of the actual answer will be accepted. ", + "category": [ + "Array", + "Math", + "Geometry" + ], + "complexity": "Easy", + "successrate": 59.6, + "totalsubmissions": 54067, + "totalaccepted": 32240, + "likes": 332, + "dislikes": 1318, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "points = [[0,0],[0,1],[1,0],[0,2],[2,0]]", + "expected_output": "2.00000", + "explanation": "The five points are shown in the above figure. The red triangle is the largest." + }, + { + "example_num": 2, + "expected_input": "points = [[1,0],[0,0],[0,1]]", + "expected_output": "0.50000", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c6b", + "questionid": 416, + "title": "Binary Tree Pruning", + "slug": "binary-tree-pruning", + "description": "Given the root of a binary tree, return the same tree where every subtree (of the given tree) not containing a 1 has been removed. A subtree of a node node is node plus every node that is a descendant of node. ", + "category": [ + "Tree", + "Depth-First Search", + "Binary Tree" + ], + "complexity": "Medium", + "successrate": 71, + "totalsubmissions": 196440, + "totalaccepted": 139432, + "likes": 2373, + "dislikes": 66, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [1,null,0,0,1]", + "expected_output": "[1,null,0,null,1]", + "explanation": "Only the red nodes satisfy the property "every subtree not containing a 1".\nThe diagram on the right represents the answer." + }, + { + "example_num": 2, + "expected_input": "root = [1,0,1,0,0,0,1]", + "expected_output": "[1,null,1,null,1]", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "root = [1,1,0,1,1,0,1,0]", + "expected_output": "[1,1,0,1,1,null,1]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c6f", + "questionid": 420, + "title": "Most Common Word", + "slug": "most-common-word", + "description": "Given a string paragraph and a string array of the banned words banned, return the most frequent word that is not banned. It is guaranteed there is at least one word that is not banned, and that the answer is unique. The words in paragraph are case-insensitive and the answer should be returned in lowercase. ", + "category": [ + "Hash Table", + "String", + "Counting" + ], + "complexity": "Easy", + "successrate": 45.2, + "totalsubmissions": 626728, + "totalaccepted": 283564, + "likes": 1245, + "dislikes": 2543, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "paragraph = "Bob hit a ball, the hit BALL flew far after it was hit.", banned = ["hit"]", + "expected_output": ""ball"", + "explanation": ""hit" occurs 3 times, but it is a banned word.\n"ball" occurs twice (and no other word does), so it is the most frequent non-banned word in the paragraph. \nNote that words in the paragraph are not case sensitive,\nthat punctuation is ignored (even if adjacent to words, such as "ball,"), \nand that "hit" isn't the answer even though it occurs more because it is banned." + }, + { + "example_num": 2, + "expected_input": "paragraph = "a.", banned = []", + "expected_output": ""a"", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c72", + "questionid": 423, + "title": "Binary Trees With Factors", + "slug": "binary-trees-with-factors", + "description": "Given an array of unique integers, arr, where each integer arr[i] is strictly greater than 1. We make a binary tree using these integers, and each number may be used for any number of times. Each non-leaf node's value should be equal to the product of the values of its children. Return the number of binary trees we can make. The answer may be too large so return the answer modulo 109 + 7. ", + "category": [ + "Array", + "Hash Table", + "Dynamic Programming" + ], + "complexity": "Medium", + "successrate": 43.7, + "totalsubmissions": 83583, + "totalaccepted": 36507, + "likes": 834, + "dislikes": 101, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "arr = [2,4]", + "expected_output": "3", + "explanation": "We can make these trees: [2], [4], [4, 2, 2]" + }, + { + "example_num": 2, + "expected_input": "arr = [2,4,5,10]", + "expected_output": "7", + "explanation": "We can make these trees: [2], [4], [5], [10], [4, 2, 2], [10, 2, 5], [10, 5, 2]." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c74", + "questionid": 425, + "title": "Count Unique Characters of All Substrings of a Given String", + "slug": "count-unique-characters-of-all-substrings-of-a-given-string", + "description": "Let's define a function countUniqueChars(s) that returns the number of unique characters on s. Given a string s, return the sum of countUniqueChars(t) where t is a substring of s. Notice that some substrings can be repeated so in this case you have to count the repeated ones too. ", + "category": [ + "String", + "Dynamic Programming" + ], + "complexity": "Hard", + "successrate": 49.7, + "totalsubmissions": 78320, + "totalaccepted": 38959, + "likes": 1243, + "dislikes": 169, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "ABC"", + "expected_output": "10\nExplanation: All possible substrings are: "A","B","C","AB","BC" and "ABC".\nEvery substring is composed with only unique letters.\nSum of lengths of all substring is 1 + 1 + 1 + 2 + 2 + 3 = 10", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "s = "ABA"", + "expected_output": "8\nExplanation: The same as example 1, except countUniqueChars("ABA") = 1.", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "s = "LEETCODE"", + "expected_output": "92", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c75", + "questionid": 426, + "title": "Consecutive Numbers Sum", + "slug": "consecutive-numbers-sum", + "description": "Given an integer n, return the number of ways you can write n as the sum of consecutive positive integers. ", + "category": [ + "Math", + "Enumeration" + ], + "complexity": "Hard", + "successrate": 41, + "totalsubmissions": 164713, + "totalaccepted": 67555, + "likes": 998, + "dislikes": 1209, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 5", + "expected_output": "2", + "explanation": "5 = 2 + 3" + }, + { + "example_num": 2, + "expected_input": "n = 9", + "expected_output": "3", + "explanation": "9 = 4 + 5 = 2 + 3 + 4" + }, + { + "example_num": 3, + "expected_input": "n = 15", + "expected_output": "4", + "explanation": "15 = 8 + 7 = 4 + 5 + 6 = 1 + 2 + 3 + 4 + 5" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c79", + "questionid": 430, + "title": "Image Overlap", + "slug": "image-overlap", + "description": "You are given two images, img1 and img2, represented as binary, square matrices of size n x n. A binary matrix has only 0s and 1s as values. We translate one image however we choose by sliding all the 1 bits left, right, up, and/or down any number of units. We then place it on top of the other image. We can then calculate the overlap by counting the number of positions that have a 1 in both images. Note also that a translation does not include any kind of rotation. Any 1 bits that are translated outside of the matrix borders are erased. Return the largest possible overlap. ", + "category": [ + "Array", + "Matrix" + ], + "complexity": "Medium", + "successrate": 61.3, + "totalsubmissions": 77230, + "totalaccepted": 47304, + "likes": 100, + "dislikes": 29, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "img1 = [[1,1,0],[0,1,0],[0,1,0]], img2 = [[0,0,0],[0,1,1],[0,0,1]]", + "expected_output": "3", + "explanation": "We translate img1 to right by 1 unit and down by 1 unit.\n\"\"\nThe number of positions that have a 1 in both images is 3 (shown in red).\n\"\"" + }, + { + "example_num": 2, + "expected_input": "img1 = [[1]], img2 = [[1]]", + "expected_output": "1", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "img1 = [[0]], img2 = [[0]]", + "expected_output": "0", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c7b", + "questionid": 432, + "title": "New 21 Game", + "slug": "new-21-game", + "description": "Alice plays the following game, loosely based on the card game \"21\". Alice starts with 0 points and draws numbers while she has less than k points. During each draw, she gains an integer number of points randomly from the range [1, maxPts], where maxPts is an integer. Each draw is independent and the outcomes have equal probabilities. Alice stops drawing numbers when she gets k or more points. Return the probability that Alice has n or fewer points. Answers within 10-5 of the actual answer are considered accepted. ", + "category": [ + "Math", + "Dynamic Programming", + "Sliding Window", + "Probability and Statistics" + ], + "complexity": "Medium", + "successrate": 36, + "totalsubmissions": 86086, + "totalaccepted": 31029, + "likes": 942, + "dislikes": 629, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 10, k = 1, maxPts = 10", + "expected_output": "1.00000", + "explanation": "Alice gets a single card, then stops." + }, + { + "example_num": 2, + "expected_input": "n = 6, k = 1, maxPts = 10", + "expected_output": "0.60000", + "explanation": "Alice gets a single card, then stops.\nIn 6 out of 10 possibilities, she is at or below 6 points." + }, + { + "example_num": 3, + "expected_input": "n = 21, k = 17, maxPts = 10", + "expected_output": "0.73278", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c8b", + "questionid": 448, + "title": "Score After Flipping Matrix", + "slug": "score-after-flipping-matrix", + "description": "You are given an m x n binary matrix grid. A move consists of choosing any row or column and toggling each value in that row or column (i.e., changing all 0's to 1's, and all 1's to 0's). Every row of the matrix is interpreted as a binary number, and the score of the matrix is the sum of these numbers. Return the highest possible score after making any number of moves (including zero moves). ", + "category": [ + "Array", + "Greedy", + "Bit Manipulation", + "Matrix" + ], + "complexity": "Medium", + "successrate": 74.8, + "totalsubmissions": 45815, + "totalaccepted": 34267, + "likes": 1024, + "dislikes": 162, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "grid = [[0,0,1,1],[1,0,1,0],[1,1,0,0]]", + "expected_output": "39", + "explanation": "0b1111 + 0b1001 + 0b1111 = 15 + 9 + 15 = 39" + }, + { + "example_num": 2, + "expected_input": "grid = [[0]]", + "expected_output": "1", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c51", + "questionid": 390, + "title": "Binary Search", + "slug": "binary-search", + "description": "Given an array of integers nums which is sorted in ascending order, and an integer target, write a function to search target in nums. If target exists, then return its index. Otherwise, return -1. You must write an algorithm with O(log n) runtime complexity. ", + "category": [ + "Array", + "Binary Search" + ], + "complexity": "Easy", + "successrate": 55.3, + "totalsubmissions": 1475426, + "totalaccepted": 816061, + "likes": 4525, + "dislikes": 106, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [-1,0,3,5,9,12], target = 9", + "expected_output": "4", + "explanation": "9 exists in nums and its index is 4" + }, + { + "example_num": 2, + "expected_input": "nums = [-1,0,3,5,9,12], target = 2", + "expected_output": "-1", + "explanation": "2 does not exist in nums so return -1" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c53", + "questionid": 392, + "title": "Swim in Rising Water", + "slug": "swim-in-rising-water", + "description": "You are given an n x n integer matrix grid where each value grid[i][j] represents the elevation at that point (i, j). The rain starts to fall. At time t, the depth of the water everywhere is t. You can swim from a square to another 4-directionally adjacent square if and only if the elevation of both squares individually are at most t. You can swim infinite distances in zero time. Of course, you must stay within the boundaries of the grid during your swim. Return the least time until you can reach the bottom right square (n - 1, n - 1) if you start at the top left square (0, 0). ", + "category": [ + "Array", + "Binary Search", + "Depth-First Search", + "Breadth-First Search", + "Union Find", + "Heap (Priority Queue)", + "Matrix" + ], + "complexity": "Hard", + "successrate": 58.7, + "totalsubmissions": 126837, + "totalaccepted": 74390, + "likes": 1876, + "dislikes": 133, + "hints": "Use either Dijkstra's, or binary search for the best time T for which you can reach the end if you only step on squares at most T.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "grid = [[0,2],[1,3]]", + "expected_output": "3\nExplanation:\nAt time 0, you are in grid location (0, 0).\nYou cannot go anywhere else because 4-directionally adjacent neighbors have a higher elevation than t = 0.\nYou cannot reach point (1, 1) until time 3.\nWhen the depth of water is 3, we can swim anywhere inside the grid.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "grid = [[0,1,2,3,4],[24,23,22,21,5],[12,13,14,15,16],[11,17,18,19,20],[10,9,8,7,6]]", + "expected_output": "16", + "explanation": "The final route is shown.\nWe need to wait until time 16 so that (0, 0) and (4, 4) are connected." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c52", + "questionid": 391, + "title": "Swap Adjacent in LR String", + "slug": "swap-adjacent-in-lr-string", + "description": "In a string composed of 'L', 'R', and 'X' characters, like \"RXXLRXRXL\", a move consists of either replacing one occurrence of \"XL\" with \"LX\", or replacing one occurrence of \"RX\" with \"XR\". Given the starting string start and the ending string end, return True if and only if there exists a sequence of moves to transform one string to the other. ", + "category": [ + "Two Pointers", + "String" + ], + "complexity": "Medium", + "successrate": 36.3, + "totalsubmissions": 144772, + "totalaccepted": 52578, + "likes": 782, + "dislikes": 682, + "hints": "Think of the L and R's as people on a horizontal line, where X is a space. The people can't cross each other, and also you can't go from XRX to RXX.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "start = "RXXLRXRXL", end = "XRLXXRRLX"", + "expected_output": "true", + "explanation": "We can transform start to end following these steps:\nRXXLRXRXL ->\nXRXLRXRXL ->\nXRLXRXRXL ->\nXRLXXRRXL ->\nXRLXXRRLX" + }, + { + "example_num": 2, + "expected_input": "start = "X", end = "L"", + "expected_output": "false", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c57", + "questionid": 396, + "title": "Transform to Chessboard", + "slug": "transform-to-chessboard", + "description": "You are given an n x n binary grid board. In each move, you can swap any two rows with each other, or any two columns with each other. Return the minimum number of moves to transform the board into a chessboard board. If the task is impossible, return -1. A chessboard board is a board where no 0's and no 1's are 4-directionally adjacent. ", + "category": [ + "Array", + "Math", + "Bit Manipulation", + "Matrix" + ], + "complexity": "Hard", + "successrate": 52, + "totalsubmissions": 28761, + "totalaccepted": 14953, + "likes": 287, + "dislikes": 282, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "board = [[0,1,1,0],[0,1,1,0],[1,0,0,1],[1,0,0,1]]", + "expected_output": "2", + "explanation": "One potential sequence of moves is shown.\nThe first move swaps the first and second column.\nThe second move swaps the second and third row." + }, + { + "example_num": 2, + "expected_input": "board = [[0,1],[1,0]]", + "expected_output": "0", + "explanation": "Also note that the board with 0 in the top left corner, is also a valid chessboard." + }, + { + "example_num": 3, + "expected_input": "board = [[1,0],[1,0]]", + "expected_output": "-1", + "explanation": "No matter what sequence of moves you make, you cannot end with a valid chessboard." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c58", + "questionid": 397, + "title": "Minimum Distance Between BST Nodes", + "slug": "minimum-distance-between-bst-nodes", + "description": "Given the root of a Binary Search Tree (BST), return the minimum difference between the values of any two different nodes in the tree. ", + "category": [ + "Tree", + "Depth-First Search", + "Breadth-First Search", + "Binary Search Tree", + "Binary Tree" + ], + "complexity": "Easy", + "successrate": 56, + "totalsubmissions": 212326, + "totalaccepted": 118984, + "likes": 1591, + "dislikes": 311, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [4,2,6,1,3]", + "expected_output": "1", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "root = [1,0,48,null,null,12,49]", + "expected_output": "1", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c5d", + "questionid": 402, + "title": "Number of Matching Subsequences", + "slug": "number-of-matching-subsequences", + "description": "Given a string s and an array of strings words, return the number of words[i] that is a subsequence of s. A subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters. ", + "category": [ + "Hash Table", + "String", + "Trie", + "Sorting" + ], + "complexity": "Medium", + "successrate": 50.5, + "totalsubmissions": 253208, + "totalaccepted": 127852, + "likes": 2889, + "dislikes": 148, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "abcde", words = ["a","bb","acd","ace"]", + "expected_output": "3", + "explanation": "There are three strings in words that are a subsequence of s: "a", "acd", "ace"." + }, + { + "example_num": 2, + "expected_input": "s = "dsahjpjauf", words = ["ahjpjau","ja","ahbwzgqnuk","tnmlanowax"]", + "expected_output": "2", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c5f", + "questionid": 404, + "title": "Number of Subarrays with Bounded Maximum", + "slug": "number-of-subarrays-with-bounded-maximum", + "description": "Given an integer array nums and two integers left and right, return the number of contiguous non-empty subarrays such that the value of the maximum array element in that subarray is in the range [left, right]. The test cases are generated so that the answer will fit in a 32-bit integer. ", + "category": [ + "Array", + "Two Pointers" + ], + "complexity": "Medium", + "successrate": 52.4, + "totalsubmissions": 99463, + "totalaccepted": 52087, + "likes": 1596, + "dislikes": 92, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [2,1,4,3], left = 2, right = 3", + "expected_output": "3", + "explanation": "There are three subarrays that meet the requirements: [2], [2, 1], [3]." + }, + { + "example_num": 2, + "expected_input": "nums = [2,9,2,5,6], left = 2, right = 8", + "expected_output": "7", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c64", + "questionid": 409, + "title": "Find Eventual Safe States", + "slug": "find-eventual-safe-states", + "description": "There is a directed graph of n nodes with each node labeled from 0 to n - 1. The graph is represented by a 0-indexed 2D integer array graph where graph[i] is an integer array of nodes adjacent to node i, meaning there is an edge from node i to each node in graph[i]. A node is a terminal node if there are no outgoing edges. A node is a safe node if every possible path starting from that node leads to a terminal node. Return an array containing all the safe nodes of the graph. The answer should be sorted in ascending order. ", + "category": [ + "Depth-First Search", + "Breadth-First Search", + "Graph", + "Topological Sort" + ], + "complexity": "Medium", + "successrate": 52.5, + "totalsubmissions": 145782, + "totalaccepted": 76472, + "likes": 2014, + "dislikes": 313, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "graph = [[1,2],[2,3],[5],[0],[5],[],[]]", + "expected_output": "[2,4,5,6]", + "explanation": "The given graph is shown above.\nNodes 5 and 6 are terminal nodes as there are no outgoing edges from either of them.\nEvery path starting at nodes 2, 4, 5, and 6 all lead to either node 5 or 6." + }, + { + "example_num": 2, + "expected_input": "graph = [[1,2,3,4],[1,2],[3,4],[0,4],[]]", + "expected_output": "[4]", + "explanation": "Only node 4 is a terminal node, and every path starting at node 4 leads to node 4." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c66", + "questionid": 411, + "title": "Max Increase to Keep City Skyline", + "slug": "max-increase-to-keep-city-skyline", + "description": "There is a city composed of n x n blocks, where each block contains a single building shaped like a vertical square prism. You are given a 0-indexed n x n integer matrix grid where grid[r][c] represents the height of the building located in the block at row r and column c. A city's skyline is the the outer contour formed by all the building when viewing the side of the city from a distance. The skyline from each cardinal direction north, east, south, and west may be different. We are allowed to increase the height of any number of buildings by any amount (the amount can be different per building). The height of a 0-height building can also be increased. However, increasing the height of a building should not affect the city's skyline from any cardinal direction. Return the maximum total sum that the height of the buildings can be increased by without changing the city's skyline from any cardinal direction. ", + "category": [ + "Array", + "Greedy", + "Matrix" + ], + "complexity": "Medium", + "successrate": 85.5, + "totalsubmissions": 143254, + "totalaccepted": 122448, + "likes": 1688, + "dislikes": 413, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "grid = [[3,0,8,4],[2,4,5,7],[9,2,6,3],[0,3,1,0]]", + "expected_output": "35", + "explanation": "The building heights are shown in the center of the above image.\nThe skylines when viewed from each cardinal direction are drawn in red.\nThe grid after increasing the height of buildings without affecting skylines is:\ngridNew = [ [8, 4, 8, 7],\n [7, 4, 7, 7],\n [9, 4, 8, 7],\n [3, 3, 3, 3] ]" + }, + { + "example_num": 2, + "expected_input": "grid = [[0,0,0],[0,0,0],[0,0,0]]", + "expected_output": "0", + "explanation": "Increasing the height of any building will result in the skyline changing." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c68", + "questionid": 413, + "title": "Subdomain Visit Count", + "slug": "subdomain-visit-count", + "description": "A website domain \"discuss.leetcode.com\" consists of various subdomains. At the top level, we have \"com\", at the next level, we have \"leetcode.com\" and at the lowest level, \"discuss.leetcode.com\". When we visit a domain like \"discuss.leetcode.com\", we will also visit the parent domains \"leetcode.com\" and \"com\" implicitly. A count-paired domain is a domain that has one of the two formats \"rep d1.d2.d3\" or \"rep d1.d2\" where rep is the number of visits to the domain and d1.d2.d3 is the domain itself. Given an array of count-paired domains cpdomains, return an array of the count-paired domains of each subdomain in the input. You may return the answer in any order. ", + "category": [ + "Array", + "Hash Table", + "String", + "Counting" + ], + "complexity": "Medium", + "successrate": 74.2, + "totalsubmissions": 228000, + "totalaccepted": 169116, + "likes": 1050, + "dislikes": 1109, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "cpdomains = ["9001 discuss.leetcode.com"]", + "expected_output": "["9001 leetcode.com","9001 discuss.leetcode.com","9001 com"]", + "explanation": "We only have one website domain: "discuss.leetcode.com".\nAs discussed above, the subdomain "leetcode.com" and "com" will also be visited. So they will all be visited 9001 times." + }, + { + "example_num": 2, + "expected_input": "cpdomains = ["900 google.mail.com", "50 yahoo.com", "1 intel.mail.com", "5 wiki.org"]", + "expected_output": "["901 mail.com","50 yahoo.com","900 google.mail.com","5 wiki.org","5 org","1 intel.mail.com","951 com"]", + "explanation": "We will visit "google.mail.com" 900 times, "yahoo.com" 50 times, "intel.mail.com" once and "wiki.org" 5 times.\nFor the subdomains, we will visit "mail.com" 900 + 1 = 901 times, "com" 900 + 50 + 1 = 951 times, and "org" 5 times." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c70", + "questionid": 421, + "title": "Shortest Distance to a Character", + "slug": "shortest-distance-to-a-character", + "description": "Given a string s and a character c that occurs in s, return an array of integers answer where answer.length == s.length and answer[i] is the distance from index i to the closest occurrence of character c in s. The distance between two indices i and j is abs(i - j), where abs is the absolute value function. ", + "category": [ + "Array", + "Two Pointers", + "String" + ], + "complexity": "Easy", + "successrate": 70.9, + "totalsubmissions": 184202, + "totalaccepted": 130681, + "likes": 2162, + "dislikes": 120, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "loveleetcode", c = "e"", + "expected_output": "[3,2,1,0,1,0,0,1,2,2,1,0]", + "explanation": "The character 'e' appears at indices 3, 5, 6, and 11 (0-indexed).\nThe closest occurrence of 'e' for index 0 is at index 3, so the distance is abs(0 - 3) = 3.\nThe closest occurrence of 'e' for index 1 is at index 3, so the distance is abs(1 - 3) = 2.\nFor index 4, there is a tie between the 'e' at index 3 and the 'e' at index 5, but the distance is still the same: abs(4 - 3) == abs(4 - 5) = 1.\nThe closest occurrence of 'e' for index 8 is at index 6, so the distance is abs(8 - 6) = 2." + }, + { + "example_num": 2, + "expected_input": "s = "aaab", c = "b"", + "expected_output": "[3,2,1,0]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c76", + "questionid": 427, + "title": "Positions of Large Groups", + "slug": "positions-of-large-groups", + "description": "In a string s of lowercase letters, these letters form consecutive groups of the same character. For example, a string like s = \"abbxxxxzyy\" has the groups \"a\", \"bb\", \"xxxx\", \"z\", and \"yy\". A group is identified by an interval [start, end], where start and end denote the start and end indices (inclusive) of the group. In the above example, \"xxxx\" has the interval [3,6]. A group is considered large if it has 3 or more characters. Return the intervals of every large group sorted in increasing order by start index. ", + "category": [ + "String" + ], + "complexity": "Easy", + "successrate": 51.4, + "totalsubmissions": 137434, + "totalaccepted": 70621, + "likes": 619, + "dislikes": 111, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "abbxxxxzzy"", + "expected_output": "[[3,6]]", + "explanation": ""xxxx" is the only large group with start index 3 and end index 6." + }, + { + "example_num": 2, + "expected_input": "s = "abc"", + "expected_output": "[]", + "explanation": "We have groups "a", "b", and "c", none of which are large groups." + }, + { + "example_num": 3, + "expected_input": "s = "abcdddeeeeaabbbcd"", + "expected_output": "[[3,5],[6,9],[12,14]]", + "explanation": "The large groups are "ddd", "eeee", and "bbb"." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c77", + "questionid": 428, + "title": "Flipping an Image", + "slug": "flipping-an-image", + "description": "Given an n x n binary matrix image, flip the image horizontally, then invert it, and return the resulting image. To flip an image horizontally means that each row of the image is reversed. To invert an image means that each 0 is replaced by 1, and each 1 is replaced by 0. ", + "category": [ + "Array", + "Two Pointers", + "Matrix", + "Simulation" + ], + "complexity": "Easy", + "successrate": 79.7, + "totalsubmissions": 365811, + "totalaccepted": 291381, + "likes": 2060, + "dislikes": 201, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "image = [[1,1,0],[1,0,1],[0,0,0]]", + "expected_output": "[[1,0,0],[0,1,0],[1,1,1]]", + "explanation": "First reverse each row: [[0,1,1],[1,0,1],[0,0,0]].\nThen, invert the image: [[1,0,0],[0,1,0],[1,1,1]]" + }, + { + "example_num": 2, + "expected_input": "image = [[1,1,0,0],[1,0,0,1],[0,1,1,1],[1,0,1,0]]", + "expected_output": "[[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]]", + "explanation": "First reverse each row: [[0,0,1,1],[1,0,0,1],[1,1,1,0],[0,1,0,1]].\nThen invert the image: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]]" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c78", + "questionid": 429, + "title": "Sum of Distances in Tree", + "slug": "sum-of-distances-in-tree", + "description": "There is an undirected connected tree with n nodes labeled from 0 to n - 1 and n - 1 edges. You are given the integer n and the array edges where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the tree. Return an array answer of length n where answer[i] is the sum of the distances between the ith node in the tree and all other nodes. ", + "category": [ + "Dynamic Programming", + "Tree", + "Depth-First Search", + "Graph" + ], + "complexity": "Hard", + "successrate": 52.9, + "totalsubmissions": 76967, + "totalaccepted": 40727, + "likes": 2472, + "dislikes": 58, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 6, edges = [[0,1],[0,2],[2,3],[2,4],[2,5]]", + "expected_output": "[8,12,6,10,10,10]", + "explanation": "The tree is shown above.\nWe can see that dist(0,1) + dist(0,2) + dist(0,3) + dist(0,4) + dist(0,5)\nequals 1 + 1 + 2 + 2 + 2 = 8.\nHence, answer[0] = 8, and so on." + }, + { + "example_num": 2, + "expected_input": "n = 1, edges = []", + "expected_output": "[0]", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "n = 2, edges = [[1,0]]", + "expected_output": "[1,1]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c7d", + "questionid": 434, + "title": "Keys and Rooms", + "slug": "keys-and-rooms", + "description": "There are n rooms labeled from 0 to n - 1 and all the rooms are locked except for room 0. Your goal is to visit all the rooms. However, you cannot enter a locked room without having its key. When you visit a room, you may find a set of distinct keys in it. Each key has a number on it, denoting which room it unlocks, and you can take all of them with you to unlock the other rooms. Given an array rooms where rooms[i] is the set of keys that you can obtain if you visited room i, return true if you can visit all the rooms, or false otherwise. ", + "category": [ + "Depth-First Search", + "Breadth-First Search", + "Graph" + ], + "complexity": "Medium", + "successrate": 68.9, + "totalsubmissions": 274493, + "totalaccepted": 189061, + "likes": 2954, + "dislikes": 172, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "rooms = [[1],[2],[3],[]]", + "expected_output": "true", + "explanation": "We visit room 0 and pick up key 1.\nWe then visit room 1 and pick up key 2.\nWe then visit room 2 and pick up key 3.\nWe then visit room 3.\nSince we were able to visit every room, we return true." + }, + { + "example_num": 2, + "expected_input": "rooms = [[1,3],[3,0,1],[2],[0]]", + "expected_output": "false", + "explanation": "We can not enter room number 2 since the only key that unlocks it is in that room." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c85", + "questionid": 442, + "title": "Loud and Rich", + "slug": "loud-and-rich", + "description": "There is a group of n people labeled from 0 to n - 1 where each person has a different amount of money and a different level of quietness. You are given an array richer where richer[i] = [ai, bi] indicates that ai has more money than bi and an integer array quiet where quiet[i] is the quietness of the ith person. All the given data in richer are logically correct (i.e., the data will not lead you to a situation where x is richer than y and y is richer than x at the same time). Return an integer array answer where answer[x] = y if y is the least quiet person (that is, the person y with the smallest value of quiet[y]) among all people who definitely have equal to or more money than the person x. ", + "category": [ + "Array", + "Depth-First Search", + "Graph", + "Topological Sort" + ], + "complexity": "Medium", + "successrate": 56.6, + "totalsubmissions": 41245, + "totalaccepted": 23326, + "likes": 616, + "dislikes": 544, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "richer = [[1,0],[2,1],[3,1],[3,7],[4,3],[5,3],[6,3]], quiet = [3,2,5,4,6,1,7,0]", + "expected_output": "[5,5,2,5,4,5,6,7]", + "explanation": "answer[0] = 5.\nPerson 5 has more money than 3, which has more money than 1, which has more money than 0.\nThe only person who is quieter (has lower quiet[x]) is person 7, but it is not clear if they have more money than person 0.\nanswer[7] = 7.\nAmong all people that definitely have equal to or more money than person 7 (which could be persons 3, 4, 5, 6, or 7), the person who is the quietest (has lower quiet[x]) is person 7.\nThe other answers can be filled out with similar reasoning." + }, + { + "example_num": 2, + "expected_input": "richer = [], quiet = [0]", + "expected_output": "[0]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c55", + "questionid": 394, + "title": "Reaching Points", + "slug": "reaching-points", + "description": "Given four integers sx, sy, tx, and ty, return true if it is possible to convert the point (sx, sy) to the point (tx, ty) through some operations, or false otherwise. The allowed operation on some point (x, y) is to convert it to either (x, x + y) or (x + y, y). ", + "category": [ + "Math" + ], + "complexity": "Hard", + "successrate": 31.6, + "totalsubmissions": 131046, + "totalaccepted": 41397, + "likes": 936, + "dislikes": 161, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "sx = 1, sy = 1, tx = 3, ty = 5", + "expected_output": "true", + "explanation": "One series of moves that transforms the starting point to the target is:\n(1, 1) -> (1, 2)\n(1, 2) -> (3, 2)\n(3, 2) -> (3, 5)" + }, + { + "example_num": 2, + "expected_input": "sx = 1, sy = 1, tx = 2, ty = 2", + "expected_output": "false", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "sx = 1, sy = 1, tx = 1, ty = 1", + "expected_output": "true", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c59", + "questionid": 398, + "title": "Letter Case Permutation", + "slug": "letter-case-permutation", + "description": "Given a string s, you can transform every letter individually to be lowercase or uppercase to create another string. Return a list of all possible strings we could create. Return the output in any order. ", + "category": [ + "String", + "Backtracking", + "Bit Manipulation" + ], + "complexity": "Medium", + "successrate": 72.3, + "totalsubmissions": 288601, + "totalaccepted": 208542, + "likes": 3215, + "dislikes": 142, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "a1b2"", + "expected_output": "["a1b2","a1B2","A1b2","A1B2"]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "s = "3z4"", + "expected_output": "["3z4","3Z4"]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c5a", + "questionid": 399, + "title": "K-th Smallest Prime Fraction", + "slug": "k-th-smallest-prime-fraction", + "description": "You are given a sorted integer array arr containing 1 and prime numbers, where all the integers of arr are unique. You are also given an integer k. For every i and j where 0 <= i < j < arr.length, we consider the fraction arr[i] / arr[j]. Return the kth smallest fraction considered. Return your answer as an array of integers of size 2, where answer[0] == arr[i] and answer[1] == arr[j]. ", + "category": [ + "Array", + "Binary Search", + "Heap (Priority Queue)" + ], + "complexity": "Hard", + "successrate": 48.4, + "totalsubmissions": 53283, + "totalaccepted": 25777, + "likes": 741, + "dislikes": 37, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "arr = [1,2,3,5], k = 3", + "expected_output": "[2,5]", + "explanation": "The fractions to be considered in sorted order are:\n1/5, 1/3, 2/5, 1/2, 3/5, and 2/3.\nThe third fraction is 2/5." + }, + { + "example_num": 2, + "expected_input": "arr = [1,7], k = 1", + "expected_output": "[1,7]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c5b", + "questionid": 400, + "title": "Cheapest Flights Within K Stops", + "slug": "cheapest-flights-within-k-stops", + "description": "There are n cities connected by some number of flights. You are given an array flights where flights[i] = [fromi, toi, pricei] indicates that there is a flight from city fromi to city toi with cost pricei. You are also given three integers src, dst, and k, return the cheapest price from src to dst with at most k stops. If there is no such route, return -1. ", + "category": [ + "Dynamic Programming", + "Depth-First Search", + "Breadth-First Search", + "Graph", + "Heap (Priority Queue)", + "Shortest Path" + ], + "complexity": "Medium", + "successrate": 36.1, + "totalsubmissions": 631258, + "totalaccepted": 227605, + "likes": 4765, + "dislikes": 212, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 4, flights = [[0,1,100],[1,2,100],[2,0,100],[1,3,600],[2,3,200]], src = 0, dst = 3, k = 1", + "expected_output": "700", + "explanation": "The graph is shown above.\nThe optimal path with at most 1 stop from city 0 to 3 is marked in red and has cost 100 + 600 = 700.\nNote that the path through cities [0,1,2,3] is cheaper but is invalid because it uses 2 stops." + }, + { + "example_num": 2, + "expected_input": "n = 3, flights = [[0,1,100],[1,2,100],[0,2,500]], src = 0, dst = 2, k = 1", + "expected_output": "200", + "explanation": "The graph is shown above.\nThe optimal path with at most 1 stop from city 0 to 2 is marked in red and has cost 100 + 100 = 200." + }, + { + "example_num": 3, + "expected_input": "n = 3, flights = [[0,1,100],[1,2,100],[0,2,500]], src = 0, dst = 2, k = 0", + "expected_output": "500", + "explanation": "The graph is shown above.\nThe optimal path with no stops from city 0 to 2 is marked in red and has cost 500." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c6c", + "questionid": 417, + "title": "Bus Routes", + "slug": "bus-routes", + "description": "You are given an array routes representing bus routes where routes[i] is a bus route that the ith bus repeats forever. You will start at the bus stop source (You are not on any bus initially), and you want to go to the bus stop target. You can travel between bus stops by buses only. Return the least number of buses you must take to travel from source to target. Return -1 if it is not possible. ", + "category": [ + "Array", + "Hash Table", + "Breadth-First Search" + ], + "complexity": "Hard", + "successrate": 45.3, + "totalsubmissions": 183370, + "totalaccepted": 83037, + "likes": 1992, + "dislikes": 51, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "routes = [[1,2,7],[3,6,7]], source = 1, target = 6", + "expected_output": "2", + "explanation": "The best strategy is take the first bus to the bus stop 7, then take the second bus to the bus stop 6." + }, + { + "example_num": 2, + "expected_input": "routes = [[7,12],[4,5,15],[6],[15,19],[9,12,13]], source = 15, target = 12", + "expected_output": "-1", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c6e", + "questionid": 419, + "title": "Linked List Components", + "slug": "linked-list-components", + "description": "You are given the head of a linked list containing unique integer values and an integer array nums that is a subset of the linked list values. Return the number of connected components in nums where two values are connected if they appear consecutively in the linked list. ", + "category": [ + "Hash Table", + "Linked List" + ], + "complexity": "Medium", + "successrate": 58, + "totalsubmissions": 117314, + "totalaccepted": 68083, + "likes": 696, + "dislikes": 1743, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "head = [0,1,2,3], nums = [0,1,3]", + "expected_output": "2", + "explanation": "0 and 1 are connected, so [0, 1] and [3] are the two connected components." + }, + { + "example_num": 2, + "expected_input": "head = [0,1,2,3,4], nums = [0,3,1,4]", + "expected_output": "2", + "explanation": "0 and 1 are connected, 3 and 4 are connected, so [0, 1] and [3, 4] are the two connected components." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c73", + "questionid": 424, + "title": "Making A Large Island", + "slug": "making-a-large-island", + "description": "You are given an n x n binary matrix grid. You are allowed to change at most one 0 to be 1. Return the size of the largest island in grid after applying this operation. An island is a 4-directionally connected group of 1s. ", + "category": [ + "Array", + "Depth-First Search", + "Breadth-First Search", + "Union Find", + "Matrix" + ], + "complexity": "Hard", + "successrate": 44.7, + "totalsubmissions": 236442, + "totalaccepted": 105794, + "likes": 2242, + "dislikes": 48, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "grid = [[1,0],[0,1]]", + "expected_output": "3", + "explanation": "Change one 0 to 1 and connect two 1s, then we get an island with area = 3." + }, + { + "example_num": 2, + "expected_input": "grid = [[1,1],[1,0]]", + "expected_output": "4\nExplanation: Change the 0 to 1 and make the island bigger, only one island with area = 4.", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "grid = [[1,1],[1,1]]", + "expected_output": "4", + "explanation": "Can't change any 0 to 1, only one island with area = 4." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c7a", + "questionid": 431, + "title": "Rectangle Overlap", + "slug": "rectangle-overlap", + "description": "An axis-aligned rectangle is represented as a list [x1, y1, x2, y2], where (x1, y1) is the coordinate of its bottom-left corner, and (x2, y2) is the coordinate of its top-right corner. Its top and bottom edges are parallel to the X-axis, and its left and right edges are parallel to the Y-axis. Two rectangles overlap if the area of their intersection is positive. To be clear, two rectangles that only touch at the corner or edges do not overlap. Given two axis-aligned rectangles rec1 and rec2, return true if they overlap, otherwise return false. ", + "category": [ + "Math", + "Geometry" + ], + "complexity": "Easy", + "successrate": 43.1, + "totalsubmissions": 232372, + "totalaccepted": 100219, + "likes": 1385, + "dislikes": 383, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "rec1 = [0,0,2,2], rec2 = [1,1,3,3]", + "expected_output": "true", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "rec1 = [0,0,1,1], rec2 = [1,0,2,1]", + "expected_output": "false", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "rec1 = [0,0,1,1], rec2 = [2,2,3,3]", + "expected_output": "false", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c7f", + "questionid": 436, + "title": "Backspace String Compare", + "slug": "backspace-string-compare", + "description": "Given two strings s and t, return true if they are equal when both are typed into empty text editors. '#' means a backspace character. Note that after backspacing an empty text, the text will continue empty. ", + "category": [ + "Two Pointers", + "String", + "Stack", + "Simulation" + ], + "complexity": "Easy", + "successrate": 47.3, + "totalsubmissions": 860272, + "totalaccepted": 406718, + "likes": 3801, + "dislikes": 185, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "ab#c", t = "ad#c"", + "expected_output": "true", + "explanation": "Both s and t become "ac"." + }, + { + "example_num": 2, + "expected_input": "s = "ab##", t = "c#d#"", + "expected_output": "true", + "explanation": "Both s and t become ""." + }, + { + "example_num": 3, + "expected_input": "s = "a#c", t = "b"", + "expected_output": "false", + "explanation": "s becomes "c" while t becomes "b"." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c80", + "questionid": 437, + "title": "Hand of Straights", + "slug": "hand-of-straights", + "description": "Alice has some number of cards and she wants to rearrange the cards into groups so that each group is of size groupSize, and consists of groupSize consecutive cards. Given an integer array hand where hand[i] is the value written on the ith card and an integer groupSize, return true if she can rearrange the cards, or false otherwise. ", + "category": [ + "Array", + "Hash Table", + "Greedy", + "Sorting" + ], + "complexity": "Medium", + "successrate": 56.2, + "totalsubmissions": 153110, + "totalaccepted": 86064, + "likes": 1322, + "dislikes": 113, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "hand = [1,2,3,6,2,3,4,7,8], groupSize = 3", + "expected_output": "true", + "explanation": "Alice's hand can be rearranged as [1,2,3],[2,3,4],[6,7,8]" + }, + { + "example_num": 2, + "expected_input": "hand = [1,2,3,4,5], groupSize = 4", + "expected_output": "false", + "explanation": "Alice's hand can not be rearranged into groups of 4." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c83", + "questionid": 440, + "title": "Maximize Distance to Closest Person", + "slug": "maximize-distance-to-closest-person", + "description": "You are given an array representing a row of seats where seats[i] = 1 represents a person sitting in the ith seat, and seats[i] = 0 represents that the ith seat is empty (0-indexed). There is at least one empty seat, and at least one person sitting. Alex wants to sit in the seat such that the distance between him and the closest person to him is maximized. Return that maximum distance to the closest person. ", + "category": [ + "Array" + ], + "complexity": "Medium", + "successrate": 47.4, + "totalsubmissions": 359728, + "totalaccepted": 170547, + "likes": 2552, + "dislikes": 163, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "seats = [1,0,0,0,1,0,1]", + "expected_output": "2\nExplanation: \nIf Alex sits in the second open seat (i.e. seats[2]), then the closest person has distance 2.\nIf Alex sits in any other open seat, the closest person has distance 1.\nThus, the maximum distance to the closest person is 2.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "seats = [1,0,0,0]", + "expected_output": "3\nExplanation: \nIf Alex sits in the last seat (i.e. seats[3]), the closest person is 3 seats away.\nThis is the maximum distance possible, so the answer is 3.", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "seats = [0,1]", + "expected_output": "1", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c84", + "questionid": 441, + "title": "Rectangle Area II", + "slug": "rectangle-area-ii", + "description": "You are given a 2D array of axis-aligned rectangles. Each rectangle[i] = [xi1, yi1, xi2, yi2] denotes the ith rectangle where (xi1, yi1) are the coordinates of the bottom-left corner, and (xi2, yi2) are the coordinates of the top-right corner. Calculate the total area covered by all rectangles in the plane. Any area covered by two or more rectangles should only be counted once. Return the total area. Since the answer may be too large, return it modulo 109 + 7. ", + "category": [ + "Array", + "Segment Tree", + "Line Sweep", + "Ordered Set" + ], + "complexity": "Hard", + "successrate": 53.3, + "totalsubmissions": 54704, + "totalaccepted": 29148, + "likes": 772, + "dislikes": 51, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "rectangles = [[0,0,2,2],[1,0,2,3],[1,0,3,1]]", + "expected_output": "6", + "explanation": "A total area of 6 is covered by all three rectangles, as illustrated in the picture.\nFrom (1,1) to (2,2), the green and red rectangles overlap.\nFrom (1,0) to (2,3), all three rectangles overlap." + }, + { + "example_num": 2, + "expected_input": "rectangles = [[0,0,1000000000,1000000000]]", + "expected_output": "49", + "explanation": "The answer is 1018 modulo (109 + 7), which is 49." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c86", + "questionid": 443, + "title": "Car Fleet", + "slug": "car-fleet", + "description": "There are n cars going to the same destination along a one-lane road. The destination is target miles away. You are given two integer array position and speed, both of length n, where position[i] is the position of the ith car and speed[i] is the speed of the ith car (in miles per hour). A car can never pass another car ahead of it, but it can catch up to it and drive bumper to bumper at the same speed. The faster car will slow down to match the slower car's speed. The distance between these two cars is ignored (i.e., they are assumed to have the same position). A car fleet is some non-empty set of cars driving at the same position and same speed. Note that a single car is also a car fleet. If a car catches up to a car fleet right at the destination point, it will still be considered as one car fleet. Return the number of car fleets that will arrive at the destination. ", + "category": [ + "Array", + "Stack", + "Sorting", + "Monotonic Stack" + ], + "complexity": "Medium", + "successrate": 48, + "totalsubmissions": 160651, + "totalaccepted": 77114, + "likes": 1333, + "dislikes": 397, + "hints": "", + "deleted": false, + "examples": [] + }, + { + "_id": "66f925ddfdfb8e1665720c87", + "questionid": 444, + "title": "K-Similar Strings", + "slug": "k-similar-strings", + "description": "Strings s1 and s2 are k-similar (for some non-negative integer k) if we can swap the positions of two letters in s1 exactly k times so that the resulting string equals s2. Given two anagrams s1 and s2, return the smallest k for which s1 and s2 are k-similar. ", + "category": [ + "String", + "Breadth-First Search" + ], + "complexity": "Hard", + "successrate": 39.3, + "totalsubmissions": 81593, + "totalaccepted": 32042, + "likes": 801, + "dislikes": 48, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s1 = "ab", s2 = "ba"", + "expected_output": "1", + "explanation": "The two string are 1-similar because we can use one swap to change s1 to s2: "ab" --> "ba"." + }, + { + "example_num": 2, + "expected_input": "s1 = "abc", s2 = "bca"", + "expected_output": "2", + "explanation": "The two strings are 2-similar because we can use two swaps to change s1 to s2: "abc" --> "bac" --> "bca"." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c89", + "questionid": 446, + "title": "Buddy Strings", + "slug": "buddy-strings", + "description": "Given two strings s and goal, return true if you can swap two letters in s so the result is equal to goal, otherwise, return false. Swapping letters is defined as taking two indices i and j (0-indexed) such that i != j and swapping the characters at s[i] and s[j]. ", + "category": [ + "Hash Table", + "String" + ], + "complexity": "Easy", + "successrate": 28.8, + "totalsubmissions": 408704, + "totalaccepted": 117591, + "likes": 1384, + "dislikes": 879, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "ab", goal = "ba"", + "expected_output": "true", + "explanation": "You can swap s[0] = 'a' and s[1] = 'b' to get "ba", which is equal to goal." + }, + { + "example_num": 2, + "expected_input": "s = "ab", goal = "ab"", + "expected_output": "false", + "explanation": "The only letters you can swap are s[0] = 'a' and s[1] = 'b', which results in "ba" != goal." + }, + { + "example_num": 3, + "expected_input": "s = "aa", goal = "aa"", + "expected_output": "true", + "explanation": "You can swap s[0] = 'a' and s[1] = 'a' to get "aa", which is equal to goal." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c8a", + "questionid": 447, + "title": "Lemonade Change", + "slug": "lemonade-change", + "description": "At a lemonade stand, each lemonade costs $5. Customers are standing in a queue to buy from you and order one at a time (in the order specified by bills). Each customer will only buy one lemonade and pay with either a $5, $10, or $20 bill. You must provide the correct change to each customer so that the net transaction is that the customer pays $5. Note that you do not have any change in hand at first. Given an integer array bills where bills[i] is the bill the ith customer pays, return true if you can provide every customer with the correct change, or false otherwise. ", + "category": [ + "Array", + "Greedy" + ], + "complexity": "Easy", + "successrate": 52.4, + "totalsubmissions": 180709, + "totalaccepted": 94723, + "likes": 1206, + "dislikes": 120, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "bills = [5,5,5,10,20]", + "expected_output": "true", + "explanation": "From the first 3 customers, we collect three $5 bills in order.\nFrom the fourth customer, we collect a $10 bill and give back a $5.\nFrom the fifth customer, we give a $10 bill and a $5 bill.\nSince all customers got correct change, we output true." + }, + { + "example_num": 2, + "expected_input": "bills = [5,5,10,10,20]", + "expected_output": "false", + "explanation": "From the first two customers in order, we collect two $5 bills.\nFor the next two customers in order, we collect a $10 bill and give back a $5 bill.\nFor the last customer, we can not give the change of $15 back because we only have two $10 bills.\nSince not every customer received the correct change, the answer is false." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c8f", + "questionid": 452, + "title": "Transpose Matrix", + "slug": "transpose-matrix", + "description": "Given a 2D integer array matrix, return the transpose of matrix. The transpose of a matrix is the matrix flipped over its main diagonal, switching the matrix's row and column indices. ", + "category": [ + "Array", + "Matrix", + "Simulation" + ], + "complexity": "Easy", + "successrate": 61.1, + "totalsubmissions": 213787, + "totalaccepted": 130561, + "likes": 1139, + "dislikes": 371, + "hints": "We don't need any special algorithms to do this. You just need to know what the transpose of a matrix looks like. Rows become columns and vice versa!", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "matrix = [[1,2,3],[4,5,6],[7,8,9]]", + "expected_output": "[[1,4,7],[2,5,8],[3,6,9]]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "matrix = [[1,2,3],[4,5,6]]", + "expected_output": "[[1,4],[2,5],[3,6]]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c8d", + "questionid": 450, + "title": "All Nodes Distance K in Binary Tree", + "slug": "all-nodes-distance-k-in-binary-tree", + "description": "Given the root of a binary tree, the value of a target node target, and an integer k, return an array of the values of all nodes that have a distance k from the target node. You can return the answer in any order. ", + "category": [ + "Tree", + "Depth-First Search", + "Breadth-First Search", + "Binary Tree" + ], + "complexity": "Medium", + "successrate": 61, + "totalsubmissions": 369754, + "totalaccepted": 225513, + "likes": 6051, + "dislikes": 125, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [3,5,1,6,2,0,8,null,null,7,4], target = 5, k = 2", + "expected_output": "[7,4,1]\nExplanation: The nodes that are a distance 2 from the target node (with value 5) have values 7, 4, and 1.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "root = [1], target = 1, k = 3", + "expected_output": "[]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c91", + "questionid": 454, + "title": "Reordered Power of 2", + "slug": "reordered-power-of-2", + "description": "You are given an integer n. We reorder the digits in any order (including the original order) such that the leading digit is not zero. Return true if and only if we can do this so that the resulting number is a power of two. ", + "category": [ + "Math", + "Sorting", + "Counting", + "Enumeration" + ], + "complexity": "Medium", + "successrate": 61.3, + "totalsubmissions": 66480, + "totalaccepted": 40760, + "likes": 577, + "dislikes": 170, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 1", + "expected_output": "true", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "n = 10", + "expected_output": "false", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c93", + "questionid": 456, + "title": "Minimum Number of Refueling Stops", + "slug": "minimum-number-of-refueling-stops", + "description": "A car travels from a starting position to a destination which is target miles east of the starting position. There are gas stations along the way. The gas stations are represented as an array stations where stations[i] = [positioni, fueli] indicates that the ith gas station is positioni miles east of the starting position and has fueli liters of gas. The car starts with an infinite tank of gas, which initially has startFuel liters of fuel in it. It uses one liter of gas per one mile that it drives. When the car reaches a gas station, it may stop and refuel, transferring all the gas from the station into the car. Return the minimum number of refueling stops the car must make in order to reach its destination. If it cannot reach the destination, return -1. Note that if the car reaches a gas station with 0 fuel left, the car can still refuel there. If the car reaches the destination with 0 fuel left, it is still considered to have arrived. ", + "category": [ + "Array", + "Dynamic Programming", + "Greedy", + "Heap (Priority Queue)" + ], + "complexity": "Hard", + "successrate": 35.7, + "totalsubmissions": 195665, + "totalaccepted": 69794, + "likes": 2436, + "dislikes": 48, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "target = 1, startFuel = 1, stations = []", + "expected_output": "0", + "explanation": "We can reach the target without refueling." + }, + { + "example_num": 2, + "expected_input": "target = 100, startFuel = 1, stations = [[10,100]]", + "expected_output": "-1", + "explanation": "We can not reach the target (or even the first gas station)." + }, + { + "example_num": 3, + "expected_input": "target = 100, startFuel = 10, stations = [[10,60],[20,30],[30,30],[60,40]]", + "expected_output": "2", + "explanation": "We start with 10 liters of fuel.\nWe drive to position 10, expending 10 liters of fuel. We refuel from 0 liters to 60 liters of gas.\nThen, we drive from position 10 to position 60 (expending 50 liters of fuel),\nand refuel from 10 liters to 50 liters of gas. We then drive to and reach the target.\nWe made 2 refueling stops along the way, so we return 2." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c98", + "questionid": 461, + "title": "Stone Game", + "slug": "stone-game", + "description": "Alice and Bob play a game with piles of stones. There are an even number of piles arranged in a row, and each pile has a positive integer number of stones piles[i]. The objective of the game is to end with the most stones. The total number of stones across all the piles is odd, so there are no ties. Alice and Bob take turns, with Alice starting first. Each turn, a player takes the entire pile of stones either from the beginning or from the end of the row. This continues until there are no more piles left, at which point the person with the most stones wins. Assuming Alice and Bob play optimally, return true if Alice wins the game, or false if Bob wins. ", + "category": [ + "Array", + "Math", + "Dynamic Programming", + "Game Theory" + ], + "complexity": "Medium", + "successrate": 69.1, + "totalsubmissions": 221144, + "totalaccepted": 152873, + "likes": 1943, + "dislikes": 1996, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "piles = [5,3,4,5]", + "expected_output": "true", + "explanation": "Alice starts first, and can only take the first 5 or the last 5.\nSay she takes the first 5, so that the row becomes [3, 4, 5].\nIf Bob takes 3, then the board is [4, 5], and Alice takes 5 to win with 10 points.\nIf Bob takes the last 5, then the board is [3, 4], and Alice takes 4 to win with 9 points.\nThis demonstrated that taking the first 5 was a winning move for Alice, so we return true." + }, + { + "example_num": 2, + "expected_input": "piles = [3,7,2,3]", + "expected_output": "true", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c9a", + "questionid": 463, + "title": "Profitable Schemes", + "slug": "profitable-schemes", + "description": "There is a group of n members, and a list of various crimes they could commit. The ith crime generates a profit[i] and requires group[i] members to participate in it. If a member participates in one crime, that member can't participate in another crime. Let's call a profitable scheme any subset of these crimes that generates at least minProfit profit, and the total number of members participating in that subset of crimes is at most n. Return the number of schemes that can be chosen. Since the answer may be very large, return it modulo 109 + 7. ", + "category": [ + "Array", + "Dynamic Programming" + ], + "complexity": "Hard", + "successrate": 40.7, + "totalsubmissions": 36113, + "totalaccepted": 14689, + "likes": 443, + "dislikes": 40, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 5, minProfit = 3, group = [2,2], profit = [2,3]", + "expected_output": "2", + "explanation": "To make a profit of at least 3, the group could either commit crimes 0 and 1, or just crime 1.\nIn total, there are 2 schemes." + }, + { + "example_num": 2, + "expected_input": "n = 10, minProfit = 5, group = [2,3,5], profit = [6,7,8]", + "expected_output": "7", + "explanation": "To make a profit of at least 5, the group could commit any crimes, as long as they commit one.\nThere are 7 possible schemes: (0), (1), (2), (0,1), (0,2), (1,2), and (0,1,2)." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c9b", + "questionid": 464, + "title": "Random Pick with Weight", + "slug": "random-pick-with-weight", + "description": "You are given a 0-indexed array of positive integers w where w[i] describes the weight of the ith index. You need to implement the function pickIndex(), which randomly picks an index in the range [0, w.length - 1] (inclusive) and returns it. The probability of picking an index i is w[i] / sum(w). ", + "category": [ + "Math", + "Binary Search", + "Prefix Sum", + "Randomized" + ], + "complexity": "Medium", + "successrate": 46.1, + "totalsubmissions": 625439, + "totalaccepted": 288036, + "likes": 679, + "dislikes": 241, + "hints": "", + "deleted": false, + "examples": [] + }, + { + "_id": "66f925ddfdfb8e1665720ca6", + "questionid": 475, + "title": "All Possible Full Binary Trees", + "slug": "all-possible-full-binary-trees", + "description": "Given an integer n, return a list of all possible full binary trees with n nodes. Each node of each tree in the answer must have Node.val == 0. Each element of the answer is the root node of one possible tree. You may return the final list of trees in any order. A full binary tree is a binary tree where each node has exactly 0 or 2 children. ", + "category": [ + "Dynamic Programming", + "Tree", + "Recursion", + "Memoization", + "Binary Tree" + ], + "complexity": "Medium", + "successrate": 79.4, + "totalsubmissions": 104069, + "totalaccepted": 82629, + "likes": 2544, + "dislikes": 187, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 7", + "expected_output": "[[0,0,0,null,null,0,0,null,null,0,0],[0,0,0,null,null,0,0,0,0],[0,0,0,0,0,0,0],[0,0,0,0,0,null,null,null,null,0,0],[0,0,0,0,0,null,null,0,0]]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "n = 3", + "expected_output": "[[0,0,0]]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720cab", + "questionid": 480, + "title": "Numbers At Most N Given Digit Set", + "slug": "numbers-at-most-n-given-digit-set", + "description": "Given an array of digits which is sorted in non-decreasing order. You can write numbers using each digits[i] as many times as we want. For example, if digits = ['1','3','5'], we may write numbers such as '13', '551', and '1351315'. Return the number of positive integers that can be generated that are less than or equal to a given integer n. ", + "category": [ + "Array", + "Math", + "Binary Search", + "Dynamic Programming" + ], + "complexity": "Hard", + "successrate": 40.9, + "totalsubmissions": 86168, + "totalaccepted": 35238, + "likes": 1041, + "dislikes": 88, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "digits = ["1","3","5","7"], n = 100", + "expected_output": "20\nExplanation: \nThe 20 numbers that can be written are:\n1, 3, 5, 7, 11, 13, 15, 17, 31, 33, 35, 37, 51, 53, 55, 57, 71, 73, 75, 77.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "digits = ["1","4","9"], n = 1000000000", + "expected_output": "29523\nExplanation: \nWe can write 3 one digit numbers, 9 two digit numbers, 27 three digit numbers,\n81 four digit numbers, 243 five digit numbers, 729 six digit numbers,\n2187 seven digit numbers, 6561 eight digit numbers, and 19683 nine digit numbers.\nIn total, this is 29523 integers that can be written using the digits array.", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "digits = ["7"], n = 8", + "expected_output": "1", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720cad", + "questionid": 482, + "title": "Super Palindromes", + "slug": "super-palindromes", + "description": "Let's say a positive integer is a super-palindrome if it is a palindrome, and it is also the square of a palindrome. Given two positive integers left and right represented as strings, return the number of super-palindromes integers in the inclusive range [left, right]. ", + "category": [ + "Math", + "Enumeration" + ], + "complexity": "Hard", + "successrate": 39.4, + "totalsubmissions": 54331, + "totalaccepted": 21385, + "likes": 301, + "dislikes": 377, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "left = "4", right = "1000"", + "expected_output": "4\nExplanation: 4, 9, 121, and 484 are superpalindromes.\nNote that 676 is not a superpalindrome: 26 * 26 = 676, but 26 is not a palindrome.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "left = "1", right = "2"", + "expected_output": "1", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720caf", + "questionid": 484, + "title": "Smallest Range I", + "slug": "smallest-range-i", + "description": "You are given an integer array nums and an integer k. In one operation, you can choose any index i where 0 <= i < nums.length and change nums[i] to nums[i] + x where x is an integer from the range [-k, k]. You can apply this operation at most once for each index i. The score of nums is the difference between the maximum and minimum elements in nums. Return the minimum score of nums after applying the mentioned operation at most once for each index in it. ", + "category": [ + "Array", + "Math" + ], + "complexity": "Easy", + "successrate": 67.2, + "totalsubmissions": 88513, + "totalaccepted": 59504, + "likes": 422, + "dislikes": 1601, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1], k = 0", + "expected_output": "0", + "explanation": "The score is max(nums) - min(nums) = 1 - 1 = 0." + }, + { + "example_num": 2, + "expected_input": "nums = [0,10], k = 2", + "expected_output": "6", + "explanation": "Change nums to be [2, 8]. The score is max(nums) - min(nums) = 8 - 2 = 6." + }, + { + "example_num": 3, + "expected_input": "nums = [1,3,6], k = 3", + "expected_output": "0", + "explanation": "Change nums to be [4, 4, 4]. The score is max(nums) - min(nums) = 4 - 4 = 0." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720cb3", + "questionid": 488, + "title": "Maximum Sum Circular Subarray", + "slug": "maximum-sum-circular-subarray", + "description": "Given a circular integer array nums of length n, return the maximum possible sum of a non-empty subarray of nums. A circular array means the end of the array connects to the beginning of the array. Formally, the next element of nums[i] is nums[(i + 1) % n] and the previous element of nums[i] is nums[(i - 1 + n) % n]. A subarray may only include each element of the fixed buffer nums at most once. Formally, for a subarray nums[i], nums[i + 1], ..., nums[j], there does not exist i <= k1, k2 <= j with k1 % n == k2 % n. ", + "category": [ + "Array", + "Divide and Conquer", + "Dynamic Programming", + "Queue", + "Monotonic Queue" + ], + "complexity": "Medium", + "successrate": 37.1, + "totalsubmissions": 306473, + "totalaccepted": 113682, + "likes": 3034, + "dislikes": 139, + "hints": "For those of you who are familiar with the Kadane's algorithm, think in terms of that. For the newbies, Kadane's algorithm is used to finding the maximum sum subarray from a given array. This problem is a twist on that idea and it is advisable to read up on that algorithm first before starting this problem. Unless you already have a great algorithm brewing up in your mind in which case, go right ahead! What is an alternate way of representing a circular array so that it appears to be a straight array?\r\nEssentially, there are two cases of this problem that we need to take care of. Let's look at the figure below to understand those two cases: The first case can be handled by the good old Kadane's algorithm. However, is there a smarter way of going about handling the second case as well?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,-2,3,-2]", + "expected_output": "3", + "explanation": "Subarray [3] has maximum sum 3." + }, + { + "example_num": 2, + "expected_input": "nums = [5,-3,5]", + "expected_output": "10", + "explanation": "Subarray [5,5] has maximum sum 5 + 5 = 10." + }, + { + "example_num": 3, + "expected_input": "nums = [-3,-2,-3]", + "expected_output": "-2", + "explanation": "Subarray [-2] has maximum sum -2." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720cb8", + "questionid": 493, + "title": "Flip String to Monotone Increasing", + "slug": "flip-string-to-monotone-increasing", + "description": "A binary string is monotone increasing if it consists of some number of 0's (possibly none), followed by some number of 1's (also possibly none). You are given a binary string s. You can flip s[i] changing it from 0 to 1 or from 1 to 0. Return the minimum number of flips to make s monotone increasing. ", + "category": [ + "String", + "Dynamic Programming" + ], + "complexity": "Medium", + "successrate": 58.7, + "totalsubmissions": 150284, + "totalaccepted": 88180, + "likes": 1907, + "dislikes": 82, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "00110"", + "expected_output": "1", + "explanation": "We flip the last digit to get 00111." + }, + { + "example_num": 2, + "expected_input": "s = "010110"", + "expected_output": "2", + "explanation": "We flip to get 011111, or alternatively 000111." + }, + { + "example_num": 3, + "expected_input": "s = "00011000"", + "expected_output": "2", + "explanation": "We flip to get 00000000." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720cba", + "questionid": 495, + "title": "Unique Email Addresses", + "slug": "unique-email-addresses", + "description": "Every valid email consists of a local name and a domain name, separated by the '@' sign. Besides lowercase letters, the email may contain one or more '.' or '+'. If you add periods '.' between some characters in the local name part of an email address, mail sent there will be forwarded to the same address without dots in the local name. Note that this rule does not apply to domain names. If you add a plus '+' in the local name, everything after the first plus sign will be ignored. This allows certain emails to be filtered. Note that this rule does not apply to domain names. It is possible to use both of these rules at the same time. Given an array of strings emails where we send one email to each emails[i], return the number of different addresses that actually receive mails. ", + "category": [ + "Array", + "Hash Table", + "String" + ], + "complexity": "Easy", + "successrate": 67.4, + "totalsubmissions": 518797, + "totalaccepted": 349584, + "likes": 1749, + "dislikes": 244, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "emails = ["test.email+alex@leetcode.com","test.e.mail+bob.cathy@leetcode.com","testemail+david@lee.tcode.com"]", + "expected_output": "2", + "explanation": ""testemail@leetcode.com" and "testemail@lee.tcode.com" actually receive mails." + }, + { + "example_num": 2, + "expected_input": "emails = ["a@leetcode.com","b@leetcode.com","c@leetcode.com"]", + "expected_output": "3", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720cbb", + "questionid": 496, + "title": "Binary Subarrays With Sum", + "slug": "binary-subarrays-with-sum", + "description": "Given a binary array nums and an integer goal, return the number of non-empty subarrays with a sum goal. A subarray is a contiguous part of the array. ", + "category": [ + "Array", + "Hash Table", + "Sliding Window", + "Prefix Sum" + ], + "complexity": "Medium", + "successrate": 48.7, + "totalsubmissions": 92313, + "totalaccepted": 44969, + "likes": 1303, + "dislikes": 44, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,0,1,0,1], goal = 2", + "expected_output": "4", + "explanation": "The 4 subarrays are bolded and underlined below:\n[1,0,1,0,1]\n[1,0,1,0,1]\n[1,0,1,0,1]\n[1,0,1,0,1]" + }, + { + "example_num": 2, + "expected_input": "nums = [0,0,0,0,0], goal = 0", + "expected_output": "15", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720cbc", + "questionid": 497, + "title": "Minimum Falling Path Sum", + "slug": "minimum-falling-path-sum", + "description": "Given an n x n array of integers matrix, return the minimum sum of any falling path through matrix. A falling path starts at any element in the first row and chooses the element in the next row that is either directly below or diagonally left/right. Specifically, the next element from position (row, col) will be (row + 1, col - 1), (row + 1, col), or (row + 1, col + 1). ", + "category": [ + "Array", + "Dynamic Programming", + "Matrix" + ], + "complexity": "Medium", + "successrate": 67.3, + "totalsubmissions": 180018, + "totalaccepted": 121207, + "likes": 2215, + "dislikes": 92, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "matrix = [[2,1,3],[6,5,4],[7,8,9]]", + "expected_output": "13", + "explanation": "There are two falling paths with a minimum sum as shown." + }, + { + "example_num": 2, + "expected_input": "matrix = [[-19,57],[-40,-5]]", + "expected_output": "-59", + "explanation": "The falling path with a minimum sum is shown." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720cc5", + "questionid": 506, + "title": "Most Stones Removed with Same Row or Column", + "slug": "most-stones-removed-with-same-row-or-column", + "description": "On a 2D plane, we place n stones at some integer coordinate points. Each coordinate point may have at most one stone. A stone can be removed if it shares either the same row or the same column as another stone that has not been removed. Given an array stones of length n where stones[i] = [xi, yi] represents the location of the ith stone, return the largest possible number of stones that can be removed. ", + "category": [ + "Depth-First Search", + "Union Find", + "Graph" + ], + "complexity": "Medium", + "successrate": 56.3, + "totalsubmissions": 177705, + "totalaccepted": 100011, + "likes": 2367, + "dislikes": 504, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "stones = [[0,0],[0,1],[1,0],[1,2],[2,1],[2,2]]", + "expected_output": "5", + "explanation": "One way to remove 5 stones is as follows:\n1. Remove stone [2,2] because it shares the same row as [2,1].\n2. Remove stone [2,1] because it shares the same column as [0,1].\n3. Remove stone [1,2] because it shares the same row as [1,0].\n4. Remove stone [1,0] because it shares the same column as [0,0].\n5. Remove stone [0,1] because it shares the same row as [0,0].\nStone [0,0] cannot be removed since it does not share a row/column with another stone still on the plane." + }, + { + "example_num": 2, + "expected_input": "stones = [[0,0],[0,2],[1,1],[2,0],[2,2]]", + "expected_output": "3", + "explanation": "One way to make 3 moves is as follows:\n1. Remove stone [2,2] because it shares the same row as [2,0].\n2. Remove stone [2,0] because it shares the same column as [0,0].\n3. Remove stone [0,2] because it shares the same row as [0,0].\nStones [0,0] and [1,1] cannot be removed since they do not share a row/column with another stone still on the plane." + }, + { + "example_num": 3, + "expected_input": "stones = [[0,0]]", + "expected_output": "0", + "explanation": "[0,0] is the only stone on the plane, so you cannot remove it." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720cca", + "questionid": 511, + "title": "Check Completeness of a Binary Tree", + "slug": "check-completeness-of-a-binary-tree", + "description": "Given the root of a binary tree, determine if it is a complete binary tree. In a complete binary tree, every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h. ", + "category": [ + "Tree", + "Breadth-First Search", + "Binary Tree" + ], + "complexity": "Medium", + "successrate": 53.6, + "totalsubmissions": 213148, + "totalaccepted": 114298, + "likes": 1891, + "dislikes": 28, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [1,2,3,4,5,6]", + "expected_output": "true", + "explanation": "Every level before the last is full (ie. levels with node-values {1} and {2, 3}), and all nodes in the last level ({4, 5, 6}) are as far left as possible." + }, + { + "example_num": 2, + "expected_input": "root = [1,2,3,4,5,null,7]", + "expected_output": "false", + "explanation": "The node with value 7 isn't as far left as possible." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c90", + "questionid": 453, + "title": "Binary Gap", + "slug": "binary-gap", + "description": "Given a positive integer n, find and return the longest distance between any two adjacent 1's in the binary representation of n. If there are no two adjacent 1's, return 0. Two 1's are adjacent if there are only 0's separating them (possibly no 0's). The distance between two 1's is the absolute difference between their bit positions. For example, the two 1's in \"1001\" have a distance of 3. ", + "category": [ + "Math", + "Bit Manipulation" + ], + "complexity": "Easy", + "successrate": 61.8, + "totalsubmissions": 93801, + "totalaccepted": 57939, + "likes": 422, + "dislikes": 590, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 22", + "expected_output": "2", + "explanation": "22 in binary is "10110".\nThe first adjacent pair of 1's is "10110" with a distance of 2.\nThe second adjacent pair of 1's is "10110" with a distance of 1.\nThe answer is the largest of these two distances, which is 2.\nNote that "10110" is not a valid pair since there is a 1 separating the two 1's underlined." + }, + { + "example_num": 2, + "expected_input": "n = 8", + "expected_output": "0", + "explanation": "8 in binary is "1000".\nThere are not any adjacent pairs of 1's in the binary representation of 8, so we return 0." + }, + { + "example_num": 3, + "expected_input": "n = 5", + "expected_output": "2", + "explanation": "5 in binary is "101"." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c94", + "questionid": 457, + "title": "Implement Rand10() Using Rand7()", + "slug": "implement-rand10-using-rand7", + "description": "Given the API rand7() that generates a uniform random integer in the range [1, 7], write a function rand10() that generates a uniform random integer in the range [1, 10]. You can only call the API rand7(), and you shouldn't call any other API. Please do not use a language's built-in random API. Each test case will have one internal argument n, the number of times that your implemented function rand10() will be called while testing. Note that this is not an argument passed to rand10(). ", + "category": [ + "Math", + "Rejection Sampling", + "Randomized", + "Probability and Statistics" + ], + "complexity": "Medium", + "successrate": 46.8, + "totalsubmissions": 132350, + "totalaccepted": 61882, + "likes": 864, + "dislikes": 283, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 1", + "expected_output": "[2]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "n = 2", + "expected_output": "[2,8]", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "n = 3", + "expected_output": "[3,8,10]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c96", + "questionid": 459, + "title": "Koko Eating Bananas", + "slug": "koko-eating-bananas", + "description": "Koko loves to eat bananas. There are n piles of bananas, the ith pile has piles[i] bananas. The guards have gone and will come back in h hours. Koko can decide her bananas-per-hour eating speed of k. Each hour, she chooses some pile of bananas and eats k bananas from that pile. If the pile has less than k bananas, she eats all of them instead and will not eat any more bananas during this hour. Koko likes to eat slowly but still wants to finish eating all the bananas before the guards return. Return the minimum integer k such that she can eat all the bananas within h hours. ", + "category": [ + "Array", + "Binary Search" + ], + "complexity": "Medium", + "successrate": 54.7, + "totalsubmissions": 306246, + "totalaccepted": 167396, + "likes": 3982, + "dislikes": 177, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "piles = [3,6,7,11], h = 8", + "expected_output": "4", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "piles = [30,11,23,4,20], h = 5", + "expected_output": "30", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "piles = [30,11,23,4,20], h = 6", + "expected_output": "23", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c9c", + "questionid": 465, + "title": "Boats to Save People", + "slug": "boats-to-save-people", + "description": "You are given an array people where people[i] is the weight of the ith person, and an infinite number of boats where each boat can carry a maximum weight of limit. Each boat carries at most two people at the same time, provided the sum of the weight of those people is at most limit. Return the minimum number of boats to carry every given person. ", + "category": [ + "Array", + "Two Pointers", + "Greedy", + "Sorting" + ], + "complexity": "Medium", + "successrate": 52.4, + "totalsubmissions": 270544, + "totalaccepted": 141888, + "likes": 2974, + "dislikes": 79, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "people = [1,2], limit = 3", + "expected_output": "1", + "explanation": "1 boat (1, 2)" + }, + { + "example_num": 2, + "expected_input": "people = [3,2,2,1], limit = 3", + "expected_output": "3", + "explanation": "3 boats (1, 2), (2) and (3)" + }, + { + "example_num": 3, + "expected_input": "people = [3,5,3,4], limit = 5", + "expected_output": "4", + "explanation": "4 boats (3), (3), (4), (5)" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c9e", + "questionid": 467, + "title": "Projection Area of 3D Shapes", + "slug": "projection-area-of-3d-shapes", + "description": "You are given an n x n grid where we place some 1 x 1 x 1 cubes that are axis-aligned with the x, y, and z axes. Each value v = grid[i][j] represents a tower of v cubes placed on top of the cell (i, j). We view the projection of these cubes onto the xy, yz, and zx planes. A projection is like a shadow, that maps our 3-dimensional figure to a 2-dimensional plane. We are viewing the \"shadow\" when looking at the cubes from the top, the front, and the side. Return the total area of all three projections. ", + "category": [ + "Array", + "Math", + "Geometry", + "Matrix" + ], + "complexity": "Easy", + "successrate": 70, + "totalsubmissions": 57337, + "totalaccepted": 40133, + "likes": 390, + "dislikes": 1140, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "grid = [[1,2],[3,4]]", + "expected_output": "17", + "explanation": "Here are the three projections ("shadows") of the shape made with each axis-aligned plane." + }, + { + "example_num": 2, + "expected_input": "grid = [[2]]", + "expected_output": "5", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "grid = [[1,0],[0,2]]", + "expected_output": "8", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720ca4", + "questionid": 473, + "title": "Construct Binary Tree from Preorder and Postorder Traversal", + "slug": "construct-binary-tree-from-preorder-and-postorder-traversal", + "description": "Given two integer arrays, preorder and postorder where preorder is the preorder traversal of a binary tree of distinct values and postorder is the postorder traversal of the same tree, reconstruct and return the binary tree. If there exist multiple answers, you can return any of them. ", + "category": [ + "Array", + "Hash Table", + "Divide and Conquer", + "Tree", + "Binary Tree" + ], + "complexity": "Medium", + "successrate": 69.9, + "totalsubmissions": 99810, + "totalaccepted": 69719, + "likes": 1833, + "dislikes": 85, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "preorder = [1,2,4,5,3,6,7], postorder = [4,5,2,6,7,3,1]", + "expected_output": "[1,2,3,4,5,6,7]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "preorder = [1], postorder = [1]", + "expected_output": "[1]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720ca5", + "questionid": 474, + "title": "Sum of Subsequence Widths", + "slug": "sum-of-subsequence-widths", + "description": "The width of a sequence is the difference between the maximum and minimum elements in the sequence. Given an array of integers nums, return the sum of the widths of all the non-empty subsequences of nums. Since the answer may be very large, return it modulo 109 + 7. A subsequence is a sequence that can be derived from an array by deleting some or no elements without changing the order of the remaining elements. For example, [3,6,2,7] is a subsequence of the array [0,3,1,6,2,2,7]. ", + "category": [ + "Array", + "Math", + "Sorting" + ], + "complexity": "Hard", + "successrate": 35.4, + "totalsubmissions": 42660, + "totalaccepted": 15081, + "likes": 489, + "dislikes": 139, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [2,1,3]", + "expected_output": "6\nExplanation: The subsequences are [1], [2], [3], [2,1], [2,3], [1,3], [2,1,3].\nThe corresponding widths are 0, 0, 0, 1, 1, 2, 2.\nThe sum of these widths is 6.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "nums = [2]", + "expected_output": "0", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720ca9", + "questionid": 478, + "title": "Bitwise ORs of Subarrays", + "slug": "bitwise-ors-of-subarrays", + "description": "We have an array arr of non-negative integers. For every (contiguous) subarray sub = [arr[i], arr[i + 1], ..., arr[j]] (with i <= j), we take the bitwise OR of all the elements in sub, obtaining a result arr[i] | arr[i + 1] | ... | arr[j]. Return the number of possible results. Results that occur more than once are only counted once in the final answer ", + "category": [ + "Array", + "Dynamic Programming", + "Bit Manipulation" + ], + "complexity": "Medium", + "successrate": 36.3, + "totalsubmissions": 71422, + "totalaccepted": 25906, + "likes": 946, + "dislikes": 176, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "arr = [0]", + "expected_output": "1", + "explanation": "There is only one possible result: 0." + }, + { + "example_num": 2, + "expected_input": "arr = [1,1,2]", + "expected_output": "3", + "explanation": "The possible subarrays are [1], [1], [2], [1, 1], [1, 2], [1, 1, 2].\nThese yield the results 1, 1, 2, 1, 3, 3.\nThere are 3 unique values, so the answer is 3." + }, + { + "example_num": 3, + "expected_input": "arr = [1,2,4]", + "expected_output": "6", + "explanation": "The possible results are 1, 2, 3, 4, 6, and 7." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720caa", + "questionid": 479, + "title": "Orderly Queue", + "slug": "orderly-queue", + "description": "You are given a string s and an integer k. You can choose one of the first k letters of s and append it at the end of the string.. Return the lexicographically smallest string you could have after applying the mentioned step any number of moves. ", + "category": [ + "Math", + "String", + "Sorting" + ], + "complexity": "Hard", + "successrate": 58.5, + "totalsubmissions": 43905, + "totalaccepted": 25691, + "likes": 556, + "dislikes": 354, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "cba", k = 1", + "expected_output": ""acb"", + "explanation": "In the first move, we move the 1st character 'c' to the end, obtaining the string "bac".\nIn the second move, we move the 1st character 'b' to the end, obtaining the final result "acb"." + }, + { + "example_num": 2, + "expected_input": "s = "baaca", k = 3", + "expected_output": ""aaabc"", + "explanation": "In the first move, we move the 1st character 'b' to the end, obtaining the string "aacab".\nIn the second move, we move the 3rd character 'c' to the end, obtaining the final result "aaabc"." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720cac", + "questionid": 481, + "title": "Sort Array By Parity", + "slug": "sort-array-by-parity", + "description": "Given an integer array nums, move all the even integers at the beginning of the array followed by all the odd integers. Return any array that satisfies this condition. ", + "category": [ + "Array", + "Two Pointers", + "Sorting" + ], + "complexity": "Easy", + "successrate": 74.8, + "totalsubmissions": 580427, + "totalaccepted": 434203, + "likes": 2633, + "dislikes": 111, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [3,1,2,4]", + "expected_output": "[2,4,3,1]", + "explanation": "The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted." + }, + { + "example_num": 2, + "expected_input": "nums = [0]", + "expected_output": "[0]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720cb0", + "questionid": 485, + "title": "Smallest Range II", + "slug": "smallest-range-ii", + "description": "You are given an integer array nums and an integer k. For each index i where 0 <= i < nums.length, change nums[i] to be either nums[i] + k or nums[i] - k. The score of nums is the difference between the maximum and minimum elements in nums. Return the minimum score of nums after changing the values at each index. ", + "category": [ + "Array", + "Math", + "Greedy", + "Sorting" + ], + "complexity": "Medium", + "successrate": 32.7, + "totalsubmissions": 100920, + "totalaccepted": 32973, + "likes": 1067, + "dislikes": 351, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1], k = 0", + "expected_output": "0", + "explanation": "The score is max(nums) - min(nums) = 1 - 1 = 0." + }, + { + "example_num": 2, + "expected_input": "nums = [0,10], k = 2", + "expected_output": "6", + "explanation": "Change nums to be [2, 8]. The score is max(nums) - min(nums) = 8 - 2 = 6." + }, + { + "example_num": 3, + "expected_input": "nums = [1,3,6], k = 3", + "expected_output": "3", + "explanation": "Change nums to be [4, 6, 3]. The score is max(nums) - min(nums) = 6 - 3 = 3." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720cb7", + "questionid": 492, + "title": "Long Pressed Name", + "slug": "long-pressed-name", + "description": "Your friend is typing his name into a keyboard. Sometimes, when typing a character c, the key might get long pressed, and the character will be typed 1 or more times. You examine the typed characters of the keyboard. Return True if it is possible that it was your friends name, with some characters (possibly none) being long pressed. ", + "category": [ + "Two Pointers", + "String" + ], + "complexity": "Easy", + "successrate": 34.7, + "totalsubmissions": 264403, + "totalaccepted": 91843, + "likes": 1579, + "dislikes": 240, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "name = "alex", typed = "aaleex"", + "expected_output": "true\nExplanation: 'a' and 'e' in 'alex' were long pressed.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "name = "saeed", typed = "ssaaedd"", + "expected_output": "false\nExplanation: 'e' must have been pressed twice, but it was not in the typed output.", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720cc1", + "questionid": 502, + "title": "Distinct Subsequences II", + "slug": "distinct-subsequences-ii", + "description": "Given a string s, return the number of distinct non-empty subsequences of s. Since the answer may be very large, return it modulo 109 + 7. ", + "category": [ + "String", + "Dynamic Programming" + ], + "complexity": "Hard", + "successrate": 44.2, + "totalsubmissions": 60215, + "totalaccepted": 26643, + "likes": 1076, + "dislikes": 27, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "abc"", + "expected_output": "7", + "explanation": "The 7 distinct subsequences are "a", "b", "c", "ab", "ac", "bc", and "abc"." + }, + { + "example_num": 2, + "expected_input": "s = "aba"", + "expected_output": "6", + "explanation": "The 6 distinct subsequences are "a", "b", "ab", "aa", "ba", and "aba"." + }, + { + "example_num": 3, + "expected_input": "s = "aaa"", + "expected_output": "3", + "explanation": "The 3 distinct subsequences are "a", "aa" and "aaa"." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720ccb", + "questionid": 512, + "title": "Regions Cut By Slashes", + "slug": "regions-cut-by-slashes", + "description": "An n x n grid is composed of 1 x 1 squares where each 1 x 1 square consists of a '/', '\\', or blank space ' '. These characters divide the square into contiguous regions. Given the grid grid represented as a string array, return the number of regions. Note that backslash characters are escaped, so a '\\' is represented as '\\\\'. ", + "category": [ + "Depth-First Search", + "Breadth-First Search", + "Union Find", + "Graph" + ], + "complexity": "Medium", + "successrate": 68.6, + "totalsubmissions": 52702, + "totalaccepted": 36142, + "likes": 2035, + "dislikes": 397, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "grid = [" /","/ "]", + "expected_output": "2", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "grid = [" /"," "]", + "expected_output": "1", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "grid = ["/\\\\","\\\\/"]", + "expected_output": "5\nExplanation: Recall that because \\ characters are escaped, "\\\\/" refers to \\/, and "/\\\\" refers to /\\.", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c8c", + "questionid": 449, + "title": "Shortest Subarray with Sum at Least K", + "slug": "shortest-subarray-with-sum-at-least-k", + "description": "Given an integer array nums and an integer k, return the length of the shortest non-empty subarray of nums with a sum of at least k. If there is no such subarray, return -1. A subarray is a contiguous part of an array. ", + "category": [ + "Array", + "Binary Search", + "Queue", + "Sliding Window", + "Heap (Priority Queue)", + "Prefix Sum", + "Monotonic Queue" + ], + "complexity": "Hard", + "successrate": 26.2, + "totalsubmissions": 263462, + "totalaccepted": 68923, + "likes": 2814, + "dislikes": 74, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1], k = 1", + "expected_output": "1", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "nums = [1,2], k = 4", + "expected_output": "-1", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "nums = [2,-1,2], k = 3", + "expected_output": "3", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c92", + "questionid": 455, + "title": "Advantage Shuffle", + "slug": "advantage-shuffle", + "description": "You are given two integer arrays nums1 and nums2 both of the same length. The advantage of nums1 with respect to nums2 is the number of indices i for which nums1[i] > nums2[i]. Return any permutation of nums1 that maximizes its advantage with respect to nums2. ", + "category": [ + "Array", + "Greedy", + "Sorting" + ], + "complexity": "Medium", + "successrate": 51.2, + "totalsubmissions": 102654, + "totalaccepted": 52584, + "likes": 1221, + "dislikes": 78, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums1 = [2,7,11,15], nums2 = [1,10,4,11]", + "expected_output": "[2,11,7,15]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "nums1 = [12,24,8,32], nums2 = [13,25,32,11]", + "expected_output": "[24,32,8,12]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c95", + "questionid": 458, + "title": "Leaf-Similar Trees", + "slug": "leaf-similar-trees", + "description": "Consider all the leaves of a binary tree, from left to right order, the values of those leaves form a leaf value sequence. For example, in the given tree above, the leaf value sequence is (6, 7, 4, 9, 8). Two binary trees are considered leaf-similar if their leaf value sequence is the same. Return true if and only if the two given trees with head nodes root1 and root2 are leaf-similar. ", + "category": [ + "Tree", + "Depth-First Search", + "Binary Tree" + ], + "complexity": "Easy", + "successrate": 65, + "totalsubmissions": 249610, + "totalaccepted": 162142, + "likes": 1648, + "dislikes": 55, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root1 = [3,5,1,6,2,9,8,null,null,7,4], root2 = [3,5,1,6,7,4,2,null,null,null,null,null,null,9,8]", + "expected_output": "true", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "root1 = [1,2,3], root2 = [1,3,2]", + "expected_output": "false", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c9f", + "questionid": 468, + "title": "Uncommon Words from Two Sentences", + "slug": "uncommon-words-from-two-sentences", + "description": "A sentence is a string of single-space separated words where each word consists only of lowercase letters. A word is uncommon if it appears exactly once in one of the sentences, and does not appear in the other sentence. Given two sentences s1 and s2, return a list of all the uncommon words. You may return the answer in any order. ", + "category": [ + "Hash Table", + "String" + ], + "complexity": "Easy", + "successrate": 65.5, + "totalsubmissions": 147023, + "totalaccepted": 96368, + "likes": 898, + "dislikes": 137, + "hints": "", + "deleted": false, + "examples": [] + }, + { + "_id": "66f925ddfdfb8e1665720ca0", + "questionid": 469, + "title": "Spiral Matrix III", + "slug": "spiral-matrix-iii", + "description": "You start at the cell (rStart, cStart) of an rows x cols grid facing east. The northwest corner is at the first row and column in the grid, and the southeast corner is at the last row and column. You will walk in a clockwise spiral shape to visit every position in this grid. Whenever you move outside the grid's boundary, we continue our walk outside the grid (but may return to the grid boundary later.). Eventually, we reach all rows * cols spaces of the grid. Return an array of coordinates representing the positions of the grid in the order you visited them. ", + "category": [ + "Array", + "Matrix", + "Simulation" + ], + "complexity": "Medium", + "successrate": 72.4, + "totalsubmissions": 46878, + "totalaccepted": 33947, + "likes": 514, + "dislikes": 563, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "rows = 1, cols = 4, rStart = 0, cStart = 0", + "expected_output": "[[0,0],[0,1],[0,2],[0,3]]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "rows = 5, cols = 6, rStart = 1, cStart = 4", + "expected_output": "[[1,4],[1,5],[2,5],[2,4],[2,3],[1,3],[0,3],[0,4],[0,5],[3,5],[3,4],[3,3],[3,2],[2,2],[1,2],[0,2],[4,5],[4,4],[4,3],[4,2],[4,1],[3,1],[2,1],[1,1],[0,1],[4,0],[3,0],[2,0],[1,0],[0,0]]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720ca1", + "questionid": 470, + "title": "Possible Bipartition", + "slug": "possible-bipartition", + "description": "We want to split a group of n people (labeled from 1 to n) into two groups of any size. Each person may dislike some other people, and they should not go into the same group. Given the integer n and the array dislikes where dislikes[i] = [ai, bi] indicates that the person labeled ai does not like the person labeled bi, return true if it is possible to split everyone into two groups in this way. ", + "category": [ + "Depth-First Search", + "Breadth-First Search", + "Union Find", + "Graph" + ], + "complexity": "Medium", + "successrate": 47.3, + "totalsubmissions": 221370, + "totalaccepted": 104627, + "likes": 2240, + "dislikes": 51, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 4, dislikes = [[1,2],[1,3],[2,4]]", + "expected_output": "true", + "explanation": "The first group has [1,4], and the second group has [2,3]." + }, + { + "example_num": 2, + "expected_input": "n = 3, dislikes = [[1,2],[1,3],[2,3]]", + "expected_output": "false", + "explanation": "We need at least 3 groups to divide them. We cannot put them in two groups." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720ca8", + "questionid": 477, + "title": "Increasing Order Search Tree", + "slug": "increasing-order-search-tree", + "description": "Given the root of a binary search tree, rearrange the tree in in-order so that the leftmost node in the tree is now the root of the tree, and every node has no left child and only one right child. ", + "category": [ + "Stack", + "Tree", + "Depth-First Search", + "Binary Search Tree", + "Binary Tree" + ], + "complexity": "Easy", + "successrate": 76.2, + "totalsubmissions": 219615, + "totalaccepted": 167325, + "likes": 2301, + "dislikes": 595, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [5,3,6,2,4,null,8,1,null,null,null,7,9]", + "expected_output": "[1,null,2,null,3,null,4,null,5,null,6,null,7,null,8,null,9]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "root = [5,1,7]", + "expected_output": "[1,null,5,null,7]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720cae", + "questionid": 483, + "title": "Sum of Subarray Minimums", + "slug": "sum-of-subarray-minimums", + "description": "Given an array of integers arr, find the sum of min(b), where b ranges over every (contiguous) subarray of arr. Since the answer may be large, return the answer modulo 109 + 7. ", + "category": [ + "Array", + "Dynamic Programming", + "Stack", + "Monotonic Stack" + ], + "complexity": "Medium", + "successrate": 33.8, + "totalsubmissions": 216848, + "totalaccepted": 73305, + "likes": 3363, + "dislikes": 225, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "arr = [3,1,2,4]", + "expected_output": "17", + "explanation": "Subarrays are [3], [1], [2], [4], [3,1], [1,2], [2,4], [3,1,2], [1,2,4], [3,1,2,4]. \nMinimums are 3, 1, 2, 4, 1, 1, 2, 1, 1, 1.\nSum is 17." + }, + { + "example_num": 2, + "expected_input": "arr = [11,81,94,43,3]", + "expected_output": "444", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720cb1", + "questionid": 486, + "title": "Sort an Array", + "slug": "sort-an-array", + "description": "Given an array of integers nums, sort the array in ascending order. ", + "category": [ + "Array", + "Divide and Conquer", + "Sorting", + "Heap (Priority Queue)", + "Merge Sort", + "Bucket Sort", + "Radix Sort", + "Counting Sort" + ], + "complexity": "Medium", + "successrate": 61.5, + "totalsubmissions": 416971, + "totalaccepted": 256327, + "likes": 2012, + "dislikes": 517, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [5,2,3,1]", + "expected_output": "[1,2,3,5]", + "explanation": "After sorting the array, the positions of some numbers are not changed (for example, 2 and 3), while the positions of other numbers are changed (for example, 1 and 5)." + }, + { + "example_num": 2, + "expected_input": "nums = [5,1,1,2,0,0]", + "expected_output": "[0,0,1,1,2,5]", + "explanation": "Note that the values of nums are not necessairly unique." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720cb2", + "questionid": 487, + "title": "Word Subsets", + "slug": "word-subsets", + "description": "You are given two string arrays words1 and words2. A string b is a subset of string a if every letter in b occurs in a including multiplicity. A string a from words1 is universal if for every string b in words2, b is a subset of a. Return an array of all the universal strings in words1. You may return the answer in any order. ", + "category": [ + "Array", + "Hash Table", + "String" + ], + "complexity": "Medium", + "successrate": 52.7, + "totalsubmissions": 94448, + "totalaccepted": 49763, + "likes": 948, + "dislikes": 126, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "words1 = ["amazon","apple","facebook","google","leetcode"], words2 = ["e","o"]", + "expected_output": "["facebook","google","leetcode"]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "words1 = ["amazon","apple","facebook","google","leetcode"], words2 = ["l","e"]", + "expected_output": "["apple","google","leetcode"]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720cb4", + "questionid": 489, + "title": "Sort Array By Parity II", + "slug": "sort-array-by-parity-ii", + "description": "Given an array of integers nums, half of the integers in nums are odd, and the other half are even. Sort the array so that whenever nums[i] is odd, i is odd, and whenever nums[i] is even, i is even. Return any answer array that satisfies this condition. ", + "category": [ + "Array", + "Two Pointers", + "Sorting" + ], + "complexity": "Easy", + "successrate": 70.6, + "totalsubmissions": 257460, + "totalaccepted": 181873, + "likes": 1705, + "dislikes": 70, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [4,2,5,7]", + "expected_output": "[4,5,2,7]", + "explanation": "[4,7,2,5], [2,5,4,7], [2,7,4,5] would also have been accepted." + }, + { + "example_num": 2, + "expected_input": "nums = [2,3]", + "expected_output": "[2,3]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720cb9", + "questionid": 494, + "title": "Minimize Malware Spread II", + "slug": "minimize-malware-spread-ii", + "description": "You are given a network of n nodes represented as an n x n adjacency matrix graph, where the ith node is directly connected to the jth node if graph[i][j] == 1. Some nodes initial are initially infected by malware. Whenever two nodes are directly connected, and at least one of those two nodes is infected by malware, both nodes will be infected by malware. This spread of malware will continue until no more nodes can be infected in this manner. Suppose M(initial) is the final number of nodes infected with malware in the entire network after the spread of malware stops. We will remove exactly one node from initial, completely removing it and any connections from this node to any other node. Return the node that, if removed, would minimize M(initial). If multiple nodes could be removed to minimize M(initial), return such a node with the smallest index. ", + "category": [ + "Array", + "Depth-First Search", + "Breadth-First Search", + "Union Find", + "Matrix" + ], + "complexity": "Hard", + "successrate": 42.2, + "totalsubmissions": 36043, + "totalaccepted": 15199, + "likes": 417, + "dislikes": 69, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "graph = [[1,1,0],[1,1,0],[0,0,1]], initial = [0,1]", + "expected_output": "0", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "graph = [[1,1,0],[1,1,1],[0,1,1]], initial = [0,1]", + "expected_output": "1", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "graph = [[1,1,0,0],[1,1,1,0],[0,1,1,1],[0,0,1,1]], initial = [0,1]", + "expected_output": "1", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720cbf", + "questionid": 500, + "title": "Range Sum of BST", + "slug": "range-sum-of-bst", + "description": "Given the root node of a binary search tree and two integers low and high, return the sum of values of all nodes with a value in the inclusive range [low, high]. ", + "category": [ + "Tree", + "Depth-First Search", + "Binary Search Tree", + "Binary Tree" + ], + "complexity": "Easy", + "successrate": 85.1, + "totalsubmissions": 705825, + "totalaccepted": 600407, + "likes": 4038, + "dislikes": 332, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [10,5,15,3,7,null,18], low = 7, high = 15", + "expected_output": "32", + "explanation": "Nodes 7, 10, and 15 are in the range [7, 15]. 7 + 10 + 15 = 32." + }, + { + "example_num": 2, + "expected_input": "root = [10,5,15,3,7,13,18,1,null,6], low = 6, high = 10", + "expected_output": "23", + "explanation": "Nodes 6, 7, and 10 are in the range [6, 10]. 6 + 7 + 10 = 23." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720cc3", + "questionid": 504, + "title": "Minimum Increment to Make Array Unique", + "slug": "minimum-increment-to-make-array-unique", + "description": "You are given an integer array nums. In one move, you can pick an index i where 0 <= i < nums.length and increment nums[i] by 1. Return the minimum number of moves to make every value in nums unique. ", + "category": [ + "Array", + "Greedy", + "Sorting", + "Counting" + ], + "complexity": "Medium", + "successrate": 49, + "totalsubmissions": 106854, + "totalaccepted": 52368, + "likes": 1026, + "dislikes": 43, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,2,2]", + "expected_output": "1", + "explanation": "After 1 move, the array could be [1, 2, 3]." + }, + { + "example_num": 2, + "expected_input": "nums = [3,2,1,2,1,7]", + "expected_output": "6", + "explanation": "After 6 moves, the array could be [3, 4, 1, 2, 5, 7].\nIt can be shown that it is impossible for the array to have all unique values with 5 or less moves." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720cc6", + "questionid": 507, + "title": "Verifying an Alien Dictionary", + "slug": "verifying-an-alien-dictionary", + "description": "In an alien language, surprisingly, they also use English lowercase letters, but possibly in a different order. The order of the alphabet is some permutation of lowercase letters. Given a sequence of words written in the alien language, and the order of the alphabet, return true if and only if the given words are sorted lexicographically in this alien language. ", + "category": [ + "Array", + "Hash Table", + "String" + ], + "complexity": "Easy", + "successrate": 52.5, + "totalsubmissions": 655595, + "totalaccepted": 344275, + "likes": 2739, + "dislikes": 916, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "words = ["hello","leetcode"], order = "hlabcdefgijkmnopqrstuvwxyz"", + "expected_output": "true\nExplanation: As 'h' comes before 'l' in this language, then the sequence is sorted.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "words = ["word","world","row"], order = "worldabcefghijkmnpqstuvxyz"", + "expected_output": "false\nExplanation: As 'd' comes after 'l' in this language, then words[0] > words[1], hence the sequence is unsorted.", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "words = ["apple","app"], order = "abcdefghijklmnopqrstuvwxyz"", + "expected_output": "false\nExplanation: The first three characters "app" match, and the second string is shorter (in size.) According to lexicographical rules "apple" > "app", because 'l' > '∅', where '∅' is defined as the blank character which is less than any other character (More info).", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720cc7", + "questionid": 508, + "title": "Array of Doubled Pairs", + "slug": "array-of-doubled-pairs", + "description": "Given an integer array of even length arr, return true if it is possible to reorder arr such that arr[2 * i + 1] = 2 * arr[2 * i] for every 0 <= i < len(arr) / 2, or false otherwise. ", + "category": [ + "Array", + "Hash Table", + "Greedy", + "Sorting" + ], + "complexity": "Medium", + "successrate": 38.7, + "totalsubmissions": 181540, + "totalaccepted": 70184, + "likes": 1075, + "dislikes": 127, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "arr = [3,1,3,6]", + "expected_output": "false", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "arr = [2,1,2,6]", + "expected_output": "false", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "arr = [4,-2,2,-4]", + "expected_output": "true", + "explanation": "We can take two groups, [-2,-4] and [2,4] to form [-2,-4,2,4] or [2,4,-2,-4]." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720cc9", + "questionid": 510, + "title": "Tallest Billboard", + "slug": "tallest-billboard", + "description": "You are installing a billboard and want it to have the largest height. The billboard will have two steel supports, one on each side. Each steel support must be an equal height. You are given a collection of rods that can be welded together. For example, if you have rods of lengths 1, 2, and 3, you can weld them together to make a support of length 6. Return the largest possible height of your billboard installation. If you cannot support the billboard, return 0. ", + "category": [ + "Array", + "Dynamic Programming" + ], + "complexity": "Hard", + "successrate": 39.9, + "totalsubmissions": 32430, + "totalaccepted": 12945, + "likes": 651, + "dislikes": 23, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "rods = [1,2,3,6]", + "expected_output": "6", + "explanation": "We have two disjoint subsets {1,2,3} and {6}, which have the same sum = 6." + }, + { + "example_num": 2, + "expected_input": "rods = [1,2,3,4,5,6]", + "expected_output": "10", + "explanation": "We have two disjoint subsets {2,3,5} and {4,6}, which have the same sum = 10." + }, + { + "example_num": 3, + "expected_input": "rods = [1,2]", + "expected_output": "0", + "explanation": "The billboard cannot be supported, so we return 0." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c8e", + "questionid": 451, + "title": "Smallest Subtree with all the Deepest Nodes", + "slug": "smallest-subtree-with-all-the-deepest-nodes", + "description": "Given the root of a binary tree, the depth of each node is the shortest distance to the root. Return the smallest subtree such that it contains all the deepest nodes in the original tree. A node is called the deepest if it has the largest depth possible among any node in the entire tree. The subtree of a node is a tree consisting of that node, plus the set of all descendants of that node. ", + "category": [ + "Hash Table", + "Tree", + "Depth-First Search", + "Breadth-First Search", + "Binary Tree" + ], + "complexity": "Medium", + "successrate": 67.8, + "totalsubmissions": 150133, + "totalaccepted": 101824, + "likes": 1917, + "dislikes": 324, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [3,5,1,6,2,0,8,null,null,7,4]", + "expected_output": "[2,7,4]", + "explanation": "We return the node with value 2, colored in yellow in the diagram.\nThe nodes coloured in blue are the deepest nodes of the tree.\nNotice that nodes 5, 3 and 2 contain the deepest nodes in the tree but node 2 is the smallest subtree among them, so we return it." + }, + { + "example_num": 2, + "expected_input": "root = [1]", + "expected_output": "[1]", + "explanation": "The root is the deepest node in the tree." + }, + { + "example_num": 3, + "expected_input": "root = [0,1,3,null,2]", + "expected_output": "[2]", + "explanation": "The deepest node in the tree is 2, the valid subtrees are the subtrees of nodes 2, 1 and 0 but the subtree of node 2 is the smallest." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c97", + "questionid": 460, + "title": "Middle of the Linked List", + "slug": "middle-of-the-linked-list", + "description": "Given the head of a singly linked list, return the middle node of the linked list. If there are two middle nodes, return the second middle node. ", + "category": [ + "Linked List", + "Two Pointers" + ], + "complexity": "Easy", + "successrate": 72.6, + "totalsubmissions": 861365, + "totalaccepted": 625120, + "likes": 5116, + "dislikes": 129, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "head = [1,2,3,4,5]", + "expected_output": "[3,4,5]", + "explanation": "The middle node of the list is node 3." + }, + { + "example_num": 2, + "expected_input": "head = [1,2,3,4,5,6]", + "expected_output": "[4,5,6]", + "explanation": "Since the list has two middle nodes with values 3 and 4, we return the second one." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c99", + "questionid": 462, + "title": "Nth Magical Number", + "slug": "nth-magical-number", + "description": "A positive integer is magical if it is divisible by either a or b. Given the three integers n, a, and b, return the nth magical number. Since the answer may be very large, return it modulo 109 + 7. ", + "category": [ + "Math", + "Binary Search" + ], + "complexity": "Hard", + "successrate": 35.8, + "totalsubmissions": 81480, + "totalaccepted": 29143, + "likes": 962, + "dislikes": 134, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 1, a = 2, b = 3", + "expected_output": "2", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "n = 4, a = 2, b = 3", + "expected_output": "6", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720c9d", + "questionid": 466, + "title": "Reachable Nodes In Subdivided Graph", + "slug": "reachable-nodes-in-subdivided-graph", + "description": "You are given an undirected graph (the \"original graph\") with n nodes labeled from 0 to n - 1. You decide to subdivide each edge in the graph into a chain of nodes, with the number of new nodes varying between each edge. The graph is given as a 2D array of edges where edges[i] = [ui, vi, cnti] indicates that there is an edge between nodes ui and vi in the original graph, and cnti is the total number of new nodes that you will subdivide the edge into. Note that cnti == 0 means you will not subdivide the edge. To subdivide the edge [ui, vi], replace it with (cnti + 1) new edges and cnti new nodes. The new nodes are x1, x2, ..., xcnti, and the new edges are [ui, x1], [x1, x2], [x2, x3], ..., [xcnti-1, xcnti], [xcnti, vi]. In this new graph, you want to know how many nodes are reachable from the node 0, where a node is reachable if the distance is maxMoves or less. Given the original graph and maxMoves, return the number of nodes that are reachable from node 0 in the new graph. ", + "category": [ + "Graph", + "Heap (Priority Queue)", + "Shortest Path" + ], + "complexity": "Hard", + "successrate": 49.9, + "totalsubmissions": 40284, + "totalaccepted": 20114, + "likes": 523, + "dislikes": 199, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "edges = [[0,1,10],[0,2,1],[1,2,2]], maxMoves = 6, n = 3", + "expected_output": "13", + "explanation": "The edge subdivisions are shown in the image above.\nThe nodes that are reachable are highlighted in yellow." + }, + { + "example_num": 2, + "expected_input": "edges = [[0,1,4],[1,2,6],[0,2,8],[1,3,1]], maxMoves = 10, n = 4", + "expected_output": "23", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "edges = [[1,2,4],[1,4,5],[1,3,1],[2,3,4],[3,4,5]], maxMoves = 17, n = 5", + "expected_output": "1", + "explanation": "Node 0 is disconnected from the rest of the graph, so only node 0 is reachable." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720ca2", + "questionid": 471, + "title": "Super Egg Drop", + "slug": "super-egg-drop", + "description": "You are given k identical eggs and you have access to a building with n floors labeled from 1 to n. You know that there exists a floor f where 0 <= f <= n such that any egg dropped at a floor higher than f will break, and any egg dropped at or below floor f will not break. Each move, you may take an unbroken egg and drop it from any floor x (where 1 <= x <= n). If the egg breaks, you can no longer use it. However, if the egg does not break, you may reuse it in future moves. Return the minimum number of moves that you need to determine with certainty what the value of f is. ", + "category": [ + "Math", + "Binary Search", + "Dynamic Programming" + ], + "complexity": "Hard", + "successrate": 27.2, + "totalsubmissions": 164494, + "totalaccepted": 44710, + "likes": 2338, + "dislikes": 130, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "k = 1, n = 2", + "expected_output": "2\nExplanation: \nDrop the egg from floor 1. If it breaks, we know that f = 0.\nOtherwise, drop the egg from floor 2. If it breaks, we know that f = 1.\nIf it does not break, then we know f = 2.\nHence, we need at minimum 2 moves to determine with certainty what the value of f is.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "k = 2, n = 6", + "expected_output": "3", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "k = 3, n = 14", + "expected_output": "4", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720ca3", + "questionid": 472, + "title": "Fair Candy Swap", + "slug": "fair-candy-swap", + "description": "Alice and Bob have a different total number of candies. You are given two integer arrays aliceSizes and bobSizes where aliceSizes[i] is the number of candies of the ith box of candy that Alice has and bobSizes[j] is the number of candies of the jth box of candy that Bob has. Since they are friends, they would like to exchange one candy box each so that after the exchange, they both have the same total amount of candy. The total amount of candy a person has is the sum of the number of candies in each box they have. Return an integer array answer where answer[0] is the number of candies in the box that Alice must exchange, and answer[1] is the number of candies in the box that Bob must exchange. If there are multiple answers, you may return any one of them. It is guaranteed that at least one answer exists. ", + "category": [ + "Array", + "Hash Table", + "Binary Search", + "Sorting" + ], + "complexity": "Easy", + "successrate": 60.4, + "totalsubmissions": 133364, + "totalaccepted": 80560, + "likes": 1249, + "dislikes": 230, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "aliceSizes = [1,1], bobSizes = [2,2]", + "expected_output": "[1,2]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "aliceSizes = [1,2], bobSizes = [2,3]", + "expected_output": "[1,2]", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "aliceSizes = [2], bobSizes = [1,3]", + "expected_output": "[2,3]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720ca7", + "questionid": 476, + "title": "Monotonic Array", + "slug": "monotonic-array", + "description": "An array is monotonic if it is either monotone increasing or monotone decreasing. An array nums is monotone increasing if for all i <= j, nums[i] <= nums[j]. An array nums is monotone decreasing if for all i <= j, nums[i] >= nums[j]. Given an integer array nums, return true if the given array is monotonic, or false otherwise. ", + "category": [ + "Array" + ], + "complexity": "Easy", + "successrate": 58.4, + "totalsubmissions": 345603, + "totalaccepted": 202002, + "likes": 1478, + "dislikes": 54, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,2,2,3]", + "expected_output": "true", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "nums = [6,5,4,4]", + "expected_output": "true", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "nums = [1,3,2]", + "expected_output": "false", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720cb5", + "questionid": 490, + "title": "3Sum With Multiplicity", + "slug": "3sum-with-multiplicity", + "description": "Given an integer array arr, and an integer target, return the number of tuples i, j, k such that i < j < k and arr[i] + arr[j] + arr[k] == target. As the answer can be very large, return it modulo 109 + 7. ", + "category": [ + "Array", + "Hash Table", + "Two Pointers", + "Sorting", + "Counting" + ], + "complexity": "Medium", + "successrate": 45.4, + "totalsubmissions": 188183, + "totalaccepted": 85475, + "likes": 2186, + "dislikes": 265, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "arr = [1,1,2,2,3,3,4,4,5,5], target = 8", + "expected_output": "20\nExplanation: \nEnumerating by the values (arr[i], arr[j], arr[k]):\n(1, 2, 5) occurs 8 times;\n(1, 3, 4) occurs 8 times;\n(2, 2, 4) occurs 2 times;\n(2, 3, 3) occurs 2 times.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "arr = [1,1,2,2,2,2], target = 5", + "expected_output": "12\nExplanation: \narr[i] = 1, arr[j] = arr[k] = 2 occurs 12 times:\nWe choose one 1 from [1,1] in 2 ways,\nand two 2s from [2,2,2,2] in 6 ways.", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "arr = [2,1,3], target = 6", + "expected_output": "1", + "explanation": "(1, 2, 3) occured one time in the array so we return 1." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720cb6", + "questionid": 491, + "title": "Minimize Malware Spread", + "slug": "minimize-malware-spread", + "description": "You are given a network of n nodes represented as an n x n adjacency matrix graph, where the ith node is directly connected to the jth node if graph[i][j] == 1. Some nodes initial are initially infected by malware. Whenever two nodes are directly connected, and at least one of those two nodes is infected by malware, both nodes will be infected by malware. This spread of malware will continue until no more nodes can be infected in this manner. Suppose M(initial) is the final number of nodes infected with malware in the entire network after the spread of malware stops. We will remove exactly one node from initial. Return the node that, if removed, would minimize M(initial). If multiple nodes could be removed to minimize M(initial), return such a node with the smallest index. Note that if a node was removed from the initial list of infected nodes, it might still be infected later due to the malware spread. ", + "category": [ + "Array", + "Depth-First Search", + "Breadth-First Search", + "Union Find", + "Matrix" + ], + "complexity": "Hard", + "successrate": 41.9, + "totalsubmissions": 87853, + "totalaccepted": 36826, + "likes": 607, + "dislikes": 407, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "graph = [[1,1,0],[1,1,0],[0,0,1]], initial = [0,1]", + "expected_output": "0", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "graph = [[1,0,0],[0,1,0],[0,0,1]], initial = [0,2]", + "expected_output": "0", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "graph = [[1,1,1],[1,1,1],[1,1,1]], initial = [1,2]", + "expected_output": "1", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720cbd", + "questionid": 498, + "title": "Shortest Bridge", + "slug": "shortest-bridge", + "description": "You are given an n x n binary matrix grid where 1 represents land and 0 represents water. An island is a 4-directionally connected group of 1's not connected to any other 1's. There are exactly two islands in grid. You may change 0's to 1's to connect the two islands to form one island. Return the smallest number of 0's you must flip to connect the two islands. ", + "category": [ + "Array", + "Depth-First Search", + "Breadth-First Search", + "Matrix" + ], + "complexity": "Medium", + "successrate": 52.7, + "totalsubmissions": 169542, + "totalaccepted": 89265, + "likes": 2481, + "dislikes": 127, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "grid = [[0,1],[1,0]]", + "expected_output": "1", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "grid = [[0,1,0],[0,0,0],[0,0,1]]", + "expected_output": "2", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "grid = [[1,1,1,1,1],[1,0,0,0,1],[1,0,1,0,1],[1,0,0,0,1],[1,1,1,1,1]]", + "expected_output": "1", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720cbe", + "questionid": 499, + "title": "Stamping The Sequence", + "slug": "stamping-the-sequence", + "description": "You are given two strings stamp and target. Initially, there is a string s of length target.length with all s[i] == '?'. In one turn, you can place stamp over s and replace every letter in the s with the corresponding letter from stamp. We want to convert s to target using at most 10 * target.length turns. Return an array of the index of the left-most letter being stamped at each turn. If we cannot obtain target from s within 10 * target.length turns, return an empty array. ", + "category": [ + "String", + "Stack", + "Greedy", + "Queue" + ], + "complexity": "Hard", + "successrate": 53.6, + "totalsubmissions": 44732, + "totalaccepted": 23964, + "likes": 531, + "dislikes": 125, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "stamp = "abc", target = "ababc"", + "expected_output": "[0,2]", + "explanation": "Initially s = "?????".\n- Place stamp at index 0 to get "abc??".\n- Place stamp at index 2 to get "ababc".\n[1,0,2] would also be accepted as an answer, as well as some other answers." + }, + { + "example_num": 2, + "expected_input": "stamp = "abca", target = "aabcaca"", + "expected_output": "[3,0,1]", + "explanation": "Initially s = "???????".\n- Place stamp at index 3 to get "???abca".\n- Place stamp at index 0 to get "abcabca".\n- Place stamp at index 1 to get "aabcaca"." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720cc0", + "questionid": 501, + "title": "Minimum Area Rectangle", + "slug": "minimum-area-rectangle", + "description": "You are given an array of points in the X-Y plane points where points[i] = [xi, yi]. Return the minimum area of a rectangle formed from these points, with sides parallel to the X and Y axes. If there is not any such rectangle, return 0. ", + "category": [ + "Array", + "Hash Table", + "Math", + "Geometry", + "Sorting" + ], + "complexity": "Medium", + "successrate": 53.5, + "totalsubmissions": 189171, + "totalaccepted": 101237, + "likes": 1426, + "dislikes": 223, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "points = [[1,1],[1,3],[3,1],[3,3],[2,2]]", + "expected_output": "4", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "points = [[1,1],[1,3],[3,1],[3,3],[4,1],[4,3]]", + "expected_output": "2", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720cc2", + "questionid": 503, + "title": "Find the Shortest Superstring", + "slug": "find-the-shortest-superstring", + "description": "Given an array of strings words, return the smallest string that contains each string in words as a substring. If there are multiple valid strings of the smallest length, return any of them. You may assume that no string in words is a substring of another string in words. ", + "category": [ + "Array", + "String", + "Dynamic Programming", + "Bit Manipulation", + "Bitmask" + ], + "complexity": "Hard", + "successrate": 45.4, + "totalsubmissions": 51494, + "totalaccepted": 23384, + "likes": 1002, + "dislikes": 126, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "words = ["alex","loves","leetcode"]", + "expected_output": ""alexlovesleetcode"", + "explanation": "All permutations of "alex","loves","leetcode" would also be accepted." + }, + { + "example_num": 2, + "expected_input": "words = ["catg","ctaagt","gcta","ttca","atgcatc"]", + "expected_output": ""gctaagttcatgcatc"", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720cc4", + "questionid": 505, + "title": "Validate Stack Sequences", + "slug": "validate-stack-sequences", + "description": "Given two integer arrays pushed and popped each with distinct values, return true if this could have been the result of a sequence of push and pop operations on an initially empty stack, or false otherwise. ", + "category": [ + "Array", + "Stack", + "Simulation" + ], + "complexity": "Medium", + "successrate": 67.6, + "totalsubmissions": 259252, + "totalaccepted": 175192, + "likes": 3509, + "dislikes": 61, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "pushed = [1,2,3,4,5], popped = [4,5,3,2,1]", + "expected_output": "true", + "explanation": "We might do the following sequence:\npush(1), push(2), push(3), push(4),\npop() -> 4,\npush(5),\npop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1" + }, + { + "example_num": 2, + "expected_input": "pushed = [1,2,3,4,5], popped = [4,3,5,1,2]", + "expected_output": "false", + "explanation": "1 cannot be popped before 2." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720cc8", + "questionid": 509, + "title": "Delete Columns to Make Sorted II", + "slug": "delete-columns-to-make-sorted-ii", + "description": "You are given an array of n strings strs, all of the same length. We may choose any deletion indices, and we delete all the characters in those indices for each string. For example, if we have strs = [\"abcdef\",\"uvwxyz\"] and deletion indices {0, 2, 3}, then the final array after deletions is [\"bef\", \"vyz\"]. Suppose we chose a set of deletion indices answer such that after deletions, the final array has its elements in lexicographic order (i.e., strs[0] <= strs[1] <= strs[2] <= ... <= strs[n - 1]). Return the minimum possible value of answer.length. ", + "category": [ + "Array", + "String", + "Greedy" + ], + "complexity": "Medium", + "successrate": 34.2, + "totalsubmissions": 44573, + "totalaccepted": 15248, + "likes": 443, + "dislikes": 69, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "strs = ["ca","bb","ac"]", + "expected_output": "1", + "explanation": "After deleting the first column, strs = ["a", "b", "c"].\nNow strs is in lexicographic order (ie. strs[0] <= strs[1] <= strs[2]).\nWe require at least 1 deletion since initially strs was not in lexicographic order, so the answer is 1." + }, + { + "example_num": 2, + "expected_input": "strs = ["xc","yb","za"]", + "expected_output": "0", + "explanation": "strs is already in lexicographic order, so we do not need to delete anything.\nNote that the rows of strs are not necessarily in lexicographic order:\ni.e., it is NOT necessarily true that (strs[0][0] <= strs[0][1] <= ...)" + }, + { + "example_num": 3, + "expected_input": "strs = ["zyx","wvu","tsr"]", + "expected_output": "3", + "explanation": "We have to delete every column." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720ccd", + "questionid": 514, + "title": "Maximum Width Ramp", + "slug": "maximum-width-ramp", + "description": "A ramp in an integer array nums is a pair (i, j) for which i < j and nums[i] <= nums[j]. The width of such a ramp is j - i. Given an integer array nums, return the maximum width of a ramp in nums. If there is no ramp in nums, return 0. ", + "category": [ + "Array", + "Stack", + "Monotonic Stack" + ], + "complexity": "Medium", + "successrate": 48.2, + "totalsubmissions": 68082, + "totalaccepted": 32790, + "likes": 1125, + "dislikes": 35, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [6,0,8,2,1,5]", + "expected_output": "4", + "explanation": "The maximum width ramp is achieved at (i, j) = (1, 5): nums[1] = 0 and nums[5] = 5." + }, + { + "example_num": 2, + "expected_input": "nums = [9,8,1,0,1,9,4,0,4,1]", + "expected_output": "7", + "explanation": "The maximum width ramp is achieved at (i, j) = (2, 9): nums[2] = 1 and nums[9] = 1." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720cd1", + "questionid": 518, + "title": "Binary Tree Cameras", + "slug": "binary-tree-cameras", + "description": "You are given the root of a binary tree. We install cameras on the tree nodes where each camera at a node can monitor its parent, itself, and its immediate children. Return the minimum number of cameras needed to monitor all nodes of the tree. ", + "category": [ + "Dynamic Programming", + "Tree", + "Depth-First Search", + "Binary Tree" + ], + "complexity": "Hard", + "successrate": 41.8, + "totalsubmissions": 151382, + "totalaccepted": 63331, + "likes": 2594, + "dislikes": 33, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [0,0,null,0,0]", + "expected_output": "1", + "explanation": "One camera is enough to monitor all nodes if placed as shown." + }, + { + "example_num": 2, + "expected_input": "root = [0,0,null,0,null,0,null,null,0]", + "expected_output": "2", + "explanation": "At least two cameras are needed to monitor all nodes of the tree. The above image shows one of the valid configurations of camera placement." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720cd4", + "questionid": 521, + "title": "K Closest Points to Origin", + "slug": "k-closest-points-to-origin", + "description": "Given an array of points where points[i] = [xi, yi] represents a point on the X-Y plane and an integer k, return the k closest points to the origin (0, 0). The distance between two points on the X-Y plane is the Euclidean distance (i.e., ˆš(x1 - x2)2 + (y1 - y2)2). You may return the answer in any order. The answer is guaranteed to be unique (except for the order that it is in). ", + "category": [ + "Array", + "Math", + "Divide and Conquer", + "Geometry", + "Sorting", + "Heap (Priority Queue)", + "Quickselect" + ], + "complexity": "Medium", + "successrate": 66, + "totalsubmissions": 1115681, + "totalaccepted": 736146, + "likes": 5350, + "dislikes": 205, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "points = [[1,3],[-2,2]], k = 1", + "expected_output": "[[-2,2]]", + "explanation": "The distance between (1, 3) and the origin is sqrt(10).\nThe distance between (-2, 2) and the origin is sqrt(8).\nSince sqrt(8) < sqrt(10), (-2, 2) is closer to the origin.\nWe only want the closest k = 1 points from the origin, so the answer is just [[-2,2]]." + }, + { + "example_num": 2, + "expected_input": "points = [[3,3],[5,-1],[-2,4]], k = 2", + "expected_output": "[[3,3],[-2,4]]", + "explanation": "The answer [[-2,4],[3,3]] would also be accepted." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720cd6", + "questionid": 523, + "title": "Largest Perimeter Triangle", + "slug": "largest-perimeter-triangle", + "description": "Given an integer array nums, return the largest perimeter of a triangle with a non-zero area, formed from three of these lengths. If it is impossible to form any triangle of a non-zero area, return 0. ", + "category": [ + "Array", + "Math", + "Greedy", + "Sorting" + ], + "complexity": "Easy", + "successrate": 56, + "totalsubmissions": 137802, + "totalaccepted": 77188, + "likes": 1065, + "dislikes": 119, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [2,1,2]", + "expected_output": "5", + "explanation": "You can form a triangle with three side lengths: 1, 2, and 2." + }, + { + "example_num": 2, + "expected_input": "nums = [1,2,1,10]", + "expected_output": "0", + "explanation": "You cannot use the side lengths 1, 1, and 2 to form a triangle.\nYou cannot use the side lengths 1, 1, and 10 to form a triangle.\nYou cannot use the side lengths 1, 2, and 10 to form a triangle.\nAs we cannot use any three side lengths to form a triangle of non-zero area, we return 0." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720cde", + "questionid": 531, + "title": "Subarrays with K Different Integers", + "slug": "subarrays-with-k-different-integers", + "description": "Given an integer array nums and an integer k, return the number of good subarrays of nums. A good array is an array where the number of different integers in that array is exactly k. A subarray is a contiguous part of an array. ", + "category": [ + "Array", + "Hash Table", + "Sliding Window", + "Counting" + ], + "complexity": "Hard", + "successrate": 53.3, + "totalsubmissions": 126886, + "totalaccepted": 67665, + "likes": 2888, + "dislikes": 40, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,2,1,2,3], k = 2", + "expected_output": "7", + "explanation": "Subarrays formed with exactly 2 different integers: [1,2], [2,1], [1,2], [2,3], [1,2,1], [2,1,2], [1,2,1,2]" + }, + { + "example_num": 2, + "expected_input": "nums = [1,2,1,3,4], k = 3", + "expected_output": "3", + "explanation": "Subarrays formed with exactly 3 different integers: [1,2,1,3], [2,1,3], [1,3,4]." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720cdf", + "questionid": 532, + "title": "Cousins in Binary Tree", + "slug": "cousins-in-binary-tree", + "description": "Given the root of a binary tree with unique values and the values of two different nodes of the tree x and y, return true if the nodes corresponding to the values x and y in the tree are cousins, or false otherwise. Two nodes of a binary tree are cousins if they have the same depth with different parents. Note that in a binary tree, the root node is at the depth 0, and children of each depth k node are at the depth k + 1. ", + "category": [ + "Tree", + "Depth-First Search", + "Breadth-First Search", + "Binary Tree" + ], + "complexity": "Easy", + "successrate": 53.8, + "totalsubmissions": 380002, + "totalaccepted": 204495, + "likes": 2682, + "dislikes": 138, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [1,2,3,4], x = 4, y = 3", + "expected_output": "false", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "root = [1,2,3,null,4,null,5], x = 5, y = 4", + "expected_output": "true", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "root = [1,2,3,null,4], x = 2, y = 3", + "expected_output": "false", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720ce1", + "questionid": 534, + "title": "Number of Squareful Arrays", + "slug": "number-of-squareful-arrays", + "description": "An array is squareful if the sum of every pair of adjacent elements is a perfect square. Given an integer array nums, return the number of permutations of nums that are squareful. Two permutations perm1 and perm2 are different if there is some index i such that perm1[i] != perm2[i]. ", + "category": [ + "Array", + "Math", + "Dynamic Programming", + "Backtracking", + "Bit Manipulation", + "Bitmask" + ], + "complexity": "Hard", + "successrate": 49.1, + "totalsubmissions": 51178, + "totalaccepted": 25134, + "likes": 657, + "dislikes": 27, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,17,8]", + "expected_output": "2", + "explanation": "[1,8,17] and [17,8,1] are the valid permutations." + }, + { + "example_num": 2, + "expected_input": "nums = [2,2,2]", + "expected_output": "1", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720ce4", + "questionid": 537, + "title": "Grid Illumination", + "slug": "grid-illumination", + "description": "There is a 2D grid of size n x n where each cell of this grid has a lamp that is initially turned off. You are given a 2D array of lamp positions lamps, where lamps[i] = [rowi, coli] indicates that the lamp at grid[rowi][coli] is turned on. Even if the same lamp is listed more than once, it is turned on. When a lamp is turned on, it illuminates its cell and all other cells in the same row, column, or diagonal. You are also given another 2D array queries, where queries[j] = [rowj, colj]. For the jth query, determine whether grid[rowj][colj] is illuminated or not. After answering the jth query, turn off the lamp at grid[rowj][colj] and its 8 adjacent lamps if they exist. A lamp is adjacent if its cell shares either a side or corner with grid[rowj][colj]. Return an array of integers ans, where ans[j] should be 1 if the cell in the jth query was illuminated, or 0 if the lamp was not. ", + "category": [ + "Array", + "Hash Table" + ], + "complexity": "Hard", + "successrate": 36.2, + "totalsubmissions": 41358, + "totalaccepted": 14957, + "likes": 390, + "dislikes": 104, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 5, lamps = [[0,0],[4,4]], queries = [[1,1],[1,0]]", + "expected_output": "[1,0]", + "explanation": "We have the initial grid with all lamps turned off. In the above picture we see the grid after turning on the lamp at grid[0][0] then turning on the lamp at grid[4][4].\nThe 0th query asks if the lamp at grid[1][1] is illuminated or not (the blue square). It is illuminated, so set ans[0] = 1. Then, we turn off all lamps in the red square.\n\"\"\nThe 1st query asks if the lamp at grid[1][0] is illuminated or not (the blue square). It is not illuminated, so set ans[1] = 0. Then, we turn off all lamps in the red rectangle.\n\"\"" + }, + { + "example_num": 2, + "expected_input": "n = 5, lamps = [[0,0],[4,4]], queries = [[1,1],[1,1]]", + "expected_output": "[1,1]", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "n = 5, lamps = [[0,0],[0,4]], queries = [[0,4],[0,1],[1,4]]", + "expected_output": "[1,1,0]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720ceb", + "questionid": 544, + "title": "Pairs of Songs With Total Durations Divisible by 60", + "slug": "pairs-of-songs-with-total-durations-divisible-by-60", + "description": "You are given a list of songs where the ith song has a duration of time[i] seconds. Return the number of pairs of songs for which their total duration in seconds is divisible by 60. Formally, we want the number of indices i, j such that i < j with (time[i] + time[j]) % 60 == 0. ", + "category": [ + "Array", + "Hash Table", + "Counting" + ], + "complexity": "Medium", + "successrate": 53.7, + "totalsubmissions": 352306, + "totalaccepted": 189080, + "likes": 3064, + "dislikes": 118, + "hints": "We only need to consider each song length modulo 60. We can count the number of songs with (length % 60) equal to r, and store that in an array of size 60.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "time = [30,20,150,100,40]", + "expected_output": "3", + "explanation": "Three pairs have a total duration divisible by 60:\n(time[0] = 30, time[2] = 150): total duration 180\n(time[1] = 20, time[3] = 100): total duration 120\n(time[1] = 20, time[4] = 40): total duration 60" + }, + { + "example_num": 2, + "expected_input": "time = [60,60,60]", + "expected_output": "3", + "explanation": "All three pairs have a total duration of 120, which is divisible by 60." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720ced", + "questionid": 546, + "title": "Numbers With Repeated Digits", + "slug": "numbers-with-repeated-digits", + "description": "Given an integer n, return the number of positive integers in the range [1, n] that have at least one repeated digit. ", + "category": [ + "Math", + "Dynamic Programming" + ], + "complexity": "Hard", + "successrate": 38.5, + "totalsubmissions": 23326, + "totalaccepted": 8983, + "likes": 393, + "dislikes": 62, + "hints": "How many numbers with no duplicate digits? How many numbers with K digits and no duplicates? How many numbers with same length as N? How many numbers with same prefix as N?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 20", + "expected_output": "1", + "explanation": "The only positive number (<= 20) with at least 1 repeated digit is 11." + }, + { + "example_num": 2, + "expected_input": "n = 100", + "expected_output": "10", + "explanation": "The positive numbers (<= 100) with atleast 1 repeated digit are 11, 22, 33, 44, 55, 66, 77, 88, 99, and 100." + }, + { + "example_num": 3, + "expected_input": "n = 1000", + "expected_output": "262", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720cf1", + "questionid": 550, + "title": "Binary Prefix Divisible By 5", + "slug": "binary-prefix-divisible-by-5", + "description": "You are given a binary array nums (0-indexed). We define xi as the number whose binary representation is the subarray nums[0..i] (from most-significant-bit to least-significant-bit). Return an array of booleans answer where answer[i] is true if xi is divisible by 5. ", + "category": [ + "Array" + ], + "complexity": "Easy", + "successrate": 47.5, + "totalsubmissions": 80946, + "totalaccepted": 38484, + "likes": 514, + "dislikes": 137, + "hints": "If X is the first i digits of the array as a binary number, then 2X + A[i] is the first i+1 digits.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [0,1,1]", + "expected_output": "[true,false,false]", + "explanation": "The input numbers in binary are 0, 01, 011; which are 0, 1, and 3 in base-10.\nOnly the first number is divisible by 5, so answer[0] is true." + }, + { + "example_num": 2, + "expected_input": "nums = [1,1,1]", + "expected_output": "[false,false,false]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720cf2", + "questionid": 551, + "title": "Next Greater Node In Linked List", + "slug": "next-greater-node-in-linked-list", + "description": "You are given the head of a linked list with n nodes. For each node in the list, find the value of the next greater node. That is, for each node, find the value of the first node that is next to it and has a strictly larger value than it. Return an integer array answer where answer[i] is the value of the next greater node of the ith node (1-indexed). If the ith node does not have a next greater node, set answer[i] = 0. ", + "category": [ + "Array", + "Linked List", + "Stack", + "Monotonic Stack" + ], + "complexity": "Medium", + "successrate": 59.7, + "totalsubmissions": 168238, + "totalaccepted": 100376, + "likes": 2114, + "dislikes": 96, + "hints": "We can use a stack that stores nodes in monotone decreasing order of value. When we see a node_j with a larger value, every node_i in the stack has next_larger(node_i) = node_j .", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "head = [2,1,5]", + "expected_output": "[5,5,0]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "head = [2,7,4,3,5]", + "expected_output": "[7,0,5,5,0]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720cf4", + "questionid": 553, + "title": "Sum of Root To Leaf Binary Numbers", + "slug": "sum-of-root-to-leaf-binary-numbers", + "description": "You are given the root of a binary tree where each node has a value 0 or 1. Each root-to-leaf path represents a binary number starting with the most significant bit. For all leaves in the tree, consider the numbers represented by the path from the root to that leaf. Return the sum of these numbers. The test cases are generated so that the answer fits in a 32-bits integer. ", + "category": [ + "Tree", + "Depth-First Search", + "Binary Tree" + ], + "complexity": "Easy", + "successrate": 73.9, + "totalsubmissions": 215956, + "totalaccepted": 159601, + "likes": 2476, + "dislikes": 149, + "hints": "Find each path, then transform that path to an integer in base 10.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [1,0,1,0,1,0,1]", + "expected_output": "22\nExplanation: (100) + (101) + (110) + (111) = 4 + 5 + 6 + 7 = 22", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "root = [0]", + "expected_output": "0", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720cf9", + "questionid": 558, + "title": "Matrix Cells in Distance Order", + "slug": "matrix-cells-in-distance-order", + "description": "You are given four integers row, cols, rCenter, and cCenter. There is a rows x cols matrix and you are on the cell with the coordinates (rCenter, cCenter). Return the coordinates of all cells in the matrix, sorted by their distance from (rCenter, cCenter) from the smallest distance to the largest distance. You may return the answer in any order that satisfies this condition. The distance between two cells (r1, c1) and (r2, c2) is |r1 - r2| + |c1 - c2|. ", + "category": [ + "Array", + "Math", + "Geometry", + "Sorting", + "Matrix" + ], + "complexity": "Easy", + "successrate": 69.1, + "totalsubmissions": 60168, + "totalaccepted": 41554, + "likes": 481, + "dislikes": 218, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "rows = 1, cols = 2, rCenter = 0, cCenter = 0", + "expected_output": "[[0,0],[0,1]]", + "explanation": "The distances from (0, 0) to other cells are: [0,1]" + }, + { + "example_num": 2, + "expected_input": "rows = 2, cols = 2, rCenter = 0, cCenter = 1", + "expected_output": "[[0,1],[0,0],[1,1],[1,0]]", + "explanation": "The distances from (0, 1) to other cells are: [0,1,1,2]\nThe answer [[0,1],[1,1],[0,0],[1,0]] would also be accepted as correct." + }, + { + "example_num": 3, + "expected_input": "rows = 2, cols = 3, rCenter = 1, cCenter = 2", + "expected_output": "[[1,2],[0,2],[1,1],[0,1],[1,0],[0,0]]", + "explanation": "The distances from (1, 2) to other cells are: [0,1,1,2,2,3]\nThere are other answers that would also be accepted as correct, such as [[1,2],[1,1],[0,2],[1,0],[0,1],[0,0]]." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720cfc", + "questionid": 561, + "title": "Coloring A Border", + "slug": "coloring-a-border", + "description": "You are given an m x n integer matrix grid, and three integers row, col, and color. Each value in the grid represents the color of the grid square at that location. Two squares belong to the same connected component if they have the same color and are next to each other in any of the 4 directions. The border of a connected component is all the squares in the connected component that are either 4-directionally adjacent to a square not in the component, or on the boundary of the grid (the first or last row or column). You should color the border of the connected component that contains the square grid[row][col] with color. Return the final grid. ", + "category": [ + "Array", + "Depth-First Search", + "Breadth-First Search", + "Matrix" + ], + "complexity": "Medium", + "successrate": 48.4, + "totalsubmissions": 45975, + "totalaccepted": 22235, + "likes": 400, + "dislikes": 597, + "hints": "Use a DFS to find every square in the component. Then for each square, color it if it has a neighbor that is outside the grid or a different color.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "grid = [[1,1],[1,2]], row = 0, col = 0, color = 3", + "expected_output": "[[3,3],[3,2]]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "grid = [[1,2,2],[2,3,2]], row = 0, col = 1, color = 3", + "expected_output": "[[1,3,3],[2,3,3]]", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "grid = [[1,1,1],[1,1,1],[1,1,1]], row = 1, col = 1, color = 2", + "expected_output": "[[2,2,2],[2,1,2],[2,2,2]]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720cfd", + "questionid": 562, + "title": "Escape a Large Maze", + "slug": "escape-a-large-maze", + "description": "There is a 1 million by 1 million grid on an XY-plane, and the coordinates of each grid square are (x, y). We start at the source = [sx, sy] square and want to reach the target = [tx, ty] square. There is also an array of blocked squares, where each blocked[i] = [xi, yi] represents a blocked square with coordinates (xi, yi). Each move, we can walk one square north, east, south, or west if the square is not in the array of blocked squares. We are also not allowed to walk outside of the grid. Return true if and only if it is possible to reach the target square from the source square through a sequence of valid moves. ", + "category": [ + "Array", + "Hash Table", + "Depth-First Search", + "Breadth-First Search" + ], + "complexity": "Hard", + "successrate": 34.4, + "totalsubmissions": 45503, + "totalaccepted": 15635, + "likes": 449, + "dislikes": 139, + "hints": "If we become stuck, there's either a loop around the source or around the target. If there is a loop around say, the source, what is the maximum number of squares it can have?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "blocked = [[0,1],[1,0]], source = [0,0], target = [0,2]", + "expected_output": "false", + "explanation": "The target square is inaccessible starting from the source square because we cannot move.\nWe cannot move north or east because those squares are blocked.\nWe cannot move south or west because we cannot go outside of the grid." + }, + { + "example_num": 2, + "expected_input": "blocked = [], source = [0,0], target = [999999,999999]", + "expected_output": "true", + "explanation": "Because there are no blocked cells, it is possible to reach the target square." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d00", + "questionid": 565, + "title": "Valid Boomerang", + "slug": "valid-boomerang", + "description": "Given an array points where points[i] = [xi, yi] represents a point on the X-Y plane, return true if these points are a boomerang. A boomerang is a set of three points that are all distinct and not in a straight line. ", + "category": [ + "Math", + "Geometry" + ], + "complexity": "Easy", + "successrate": 37.4, + "totalsubmissions": 82488, + "totalaccepted": 30881, + "likes": 223, + "dislikes": 348, + "hints": "3 points form a boomerang if and only if the triangle formed from them has non-zero area.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "points = [[1,1],[2,3],[3,2]]", + "expected_output": "true", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "points = [[1,1],[2,2],[3,3]]", + "expected_output": "false", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d02", + "questionid": 567, + "title": "Flower Planting With No Adjacent", + "slug": "flower-planting-with-no-adjacent", + "description": "You have n gardens, labeled from 1 to n, and an array paths where paths[i] = [xi, yi] describes a bidirectional path between garden xi to garden yi. In each garden, you want to plant one of 4 types of flowers. All gardens have at most 3 paths coming into or leaving it. Your task is to choose a flower type for each garden such that, for any two gardens connected by a path, they have different types of flowers. Return any such a choice as an array answer, where answer[i] is the type of flower planted in the (i+1)th garden. The flower types are denoted 1, 2, 3, or 4. It is guaranteed an answer exists. ", + "category": [ + "Depth-First Search", + "Breadth-First Search", + "Graph" + ], + "complexity": "Medium", + "successrate": 49.8, + "totalsubmissions": 109234, + "totalaccepted": 54424, + "likes": 822, + "dislikes": 650, + "hints": "Since each garden is connected to at most 3 gardens, there's always an available color for each garden. For example, if one garden is next to gardens with colors 1, 3, 4, then color #2 is available.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 3, paths = [[1,2],[2,3],[3,1]]", + "expected_output": "[1,2,3]", + "explanation": "Gardens 1 and 2 have different types.\nGardens 2 and 3 have different types.\nGardens 3 and 1 have different types.\nHence, [1,2,3] is a valid answer. Other valid answers include [1,2,4], [1,4,2], and [3,2,1]." + }, + { + "example_num": 2, + "expected_input": "n = 4, paths = [[1,2],[3,4]]", + "expected_output": "[1,2,1,2]", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "n = 4, paths = [[1,2],[2,3],[3,4],[4,1],[1,3],[2,4]]", + "expected_output": "[1,2,3,4]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d03", + "questionid": 568, + "title": "Partition Array for Maximum Sum", + "slug": "partition-array-for-maximum-sum", + "description": "Given an integer array arr, partition the array into (contiguous) subarrays of length at most k. After partitioning, each subarray has their values changed to become the maximum value of that subarray. Return the largest sum of the given array after partitioning. Test cases are generated so that the answer fits in a 32-bit integer. ", + "category": [ + "Array", + "Dynamic Programming" + ], + "complexity": "Medium", + "successrate": 70.3, + "totalsubmissions": 67101, + "totalaccepted": 47141, + "likes": 2083, + "dislikes": 196, + "hints": "Think dynamic programming: dp[i] will be the answer for array A[0], ..., A[i-1]. For j = 1 .. k that keeps everything in bounds, dp[i] is the maximum of dp[i-j] + max(A[i-1], ..., A[i-j]) * j .", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "arr = [1,15,7,9,2,5,10], k = 3", + "expected_output": "84", + "explanation": "arr becomes [15,15,15,9,10,10,10]" + }, + { + "example_num": 2, + "expected_input": "arr = [1,4,1,5,7,3,6,1,9,9,3], k = 4", + "expected_output": "83", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "arr = [1], k = 1", + "expected_output": "1", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d04", + "questionid": 569, + "title": "Remove All Adjacent Duplicates In String", + "slug": "remove-all-adjacent-duplicates-in-string", + "description": "You are given a string s consisting of lowercase English letters. A duplicate removal consists of choosing two adjacent and equal letters and removing them. We repeatedly make duplicate removals on s until we no longer can. Return the final string after all such duplicate removals have been made. It can be proven that the answer is unique. ", + "category": [ + "String", + "Stack" + ], + "complexity": "Easy", + "successrate": 71, + "totalsubmissions": 390692, + "totalaccepted": 277370, + "likes": 3093, + "dislikes": 152, + "hints": "Use a stack to process everything greedily.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "abbaca"", + "expected_output": ""ca"", + "explanation": "For example, in "abbaca" we could remove "bb" since the letters are adjacent and equal, and this is the only possible move. The result of this move is that the string is "aaca", of which only "aa" is possible, so the final string is "ca"." + }, + { + "example_num": 2, + "expected_input": "s = "azxxzy"", + "expected_output": ""ay"", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d08", + "questionid": 573, + "title": "Grumpy Bookstore Owner", + "slug": "grumpy-bookstore-owner", + "description": "There is a bookstore owner that has a store open for n minutes. Every minute, some number of customers enter the store. You are given an integer array customers of length n where customers[i] is the number of the customer that enters the store at the start of the ith minute and all those customers leave after the end of that minute. On some minutes, the bookstore owner is grumpy. You are given a binary array grumpy where grumpy[i] is 1 if the bookstore owner is grumpy during the ith minute, and is 0 otherwise. When the bookstore owner is grumpy, the customers of that minute are not satisfied, otherwise, they are satisfied. The bookstore owner knows a secret technique to keep themselves not grumpy for minutes consecutive minutes, but can only use it once. Return the maximum number of customers that can be satisfied throughout the day. ", + "category": [ + "Array", + "Sliding Window" + ], + "complexity": "Medium", + "successrate": 56.7, + "totalsubmissions": 92423, + "totalaccepted": 52409, + "likes": 1115, + "dislikes": 93, + "hints": "Say the store owner uses their power in minute 1 to X and we have some answer A. If they instead use their power from minute 2 to X+1, we only have to use data from minutes 1, 2, X and X+1 to update our answer A.", + "deleted": false, + "examples": [] + }, + { + "_id": "66f925ddfdfb8e1665720d0b", + "questionid": 576, + "title": "Greatest Common Divisor of Strings", + "slug": "greatest-common-divisor-of-strings", + "description": "For two strings s and t, we say \"t divides s\" if and only if s = t + ... + t (i.e., t is concatenated with itself one or more times). Given two strings str1 and str2, return the largest string x such that x divides both str1 and str2. ", + "category": [ + "Math", + "String" + ], + "complexity": "Easy", + "successrate": 51.5, + "totalsubmissions": 138025, + "totalaccepted": 71079, + "likes": 1267, + "dislikes": 253, + "hints": "The greatest common divisor must be a prefix of each string, so we can try all prefixes.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "str1 = "ABCABC", str2 = "ABC"", + "expected_output": ""ABC"", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "str1 = "ABABAB", str2 = "ABAB"", + "expected_output": ""AB"", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "str1 = "LEET", str2 = "CODE"", + "expected_output": """", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720cd3", + "questionid": 520, + "title": "Fibonacci Number", + "slug": "fibonacci-number", + "description": "The Fibonacci numbers, commonly denoted F(n) form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1. That is, Given n, calculate F(n). ", + "category": [ + "Math", + "Dynamic Programming", + "Recursion", + "Memoization" + ], + "complexity": "Easy", + "successrate": 68.2, + "totalsubmissions": 1075067, + "totalaccepted": 732697, + "likes": 3284, + "dislikes": 261, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 2", + "expected_output": "1", + "explanation": "F(2) = F(1) + F(0) = 1 + 0 = 1." + }, + { + "example_num": 2, + "expected_input": "n = 3", + "expected_output": "2", + "explanation": "F(3) = F(2) + F(1) = 1 + 1 = 2." + }, + { + "example_num": 3, + "expected_input": "n = 4", + "expected_output": "3", + "explanation": "F(4) = F(3) + F(2) = 2 + 1 = 3." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720cd8", + "questionid": 525, + "title": "Distribute Coins in Binary Tree", + "slug": "distribute-coins-in-binary-tree", + "description": "You are given the root of a binary tree with n nodes where each node in the tree has node.val coins. There are n coins in total throughout the whole tree. In one move, we may choose two adjacent nodes and move one coin from one node to another. A move may be from parent to child, or from child to parent. Return the minimum number of moves required to make every node have exactly one coin. ", + "category": [ + "Tree", + "Depth-First Search", + "Binary Tree" + ], + "complexity": "Medium", + "successrate": 71.5, + "totalsubmissions": 116380, + "totalaccepted": 83207, + "likes": 3561, + "dislikes": 119, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [3,0,0]", + "expected_output": "2\nExplanation: From the root of the tree, we move one coin to its left child, and one coin to its right child.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "root = [0,3,0]", + "expected_output": "3\nExplanation: From the left child of the root, we move two coins to the root [taking two moves]. Then, we move one coin from the root of the tree to the right child.", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720cd9", + "questionid": 526, + "title": "Sum of Even Numbers After Queries", + "slug": "sum-of-even-numbers-after-queries", + "description": "You are given an integer array nums and an array queries where queries[i] = [vali, indexi]. For each query i, first, apply nums[indexi] = nums[indexi] + vali, then print the sum of the even values of nums. Return an integer array answer where answer[i] is the answer to the ith query. ", + "category": [ + "Array", + "Simulation" + ], + "complexity": "Medium", + "successrate": 60.9, + "totalsubmissions": 102714, + "totalaccepted": 62602, + "likes": 668, + "dislikes": 212, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,2,3,4], queries = [[1,0],[-3,1],[-4,0],[2,3]]", + "expected_output": "[8,6,2,4]", + "explanation": "At the beginning, the array is [1,2,3,4].\nAfter adding 1 to nums[0], the array is [2,2,3,4], and the sum of even values is 2 + 2 + 4 = 8.\nAfter adding -3 to nums[1], the array is [2,-1,3,4], and the sum of even values is 2 + 4 = 6.\nAfter adding -4 to nums[0], the array is [-2,-1,3,4], and the sum of even values is -2 + 4 = 2.\nAfter adding 2 to nums[3], the array is [-2,-1,3,6], and the sum of even values is -2 + 6 = 4." + }, + { + "example_num": 2, + "expected_input": "nums = [1], queries = [[4,0]]", + "expected_output": "[0]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720cda", + "questionid": 527, + "title": "Interval List Intersections", + "slug": "interval-list-intersections", + "description": "You are given two lists of closed intervals, firstList and secondList, where firstList[i] = [starti, endi] and secondList[j] = [startj, endj]. Each list of intervals is pairwise disjoint and in sorted order. Return the intersection of these two interval lists. A closed interval [a, b] (with a <= b) denotes the set of real numbers x with a <= x <= b. The intersection of two closed intervals is a set of real numbers that are either empty or represented as a closed interval. For example, the intersection of [1, 3] and [2, 4] is [2, 3]. ", + "category": [ + "Array", + "Two Pointers" + ], + "complexity": "Medium", + "successrate": 71.1, + "totalsubmissions": 413025, + "totalaccepted": 293594, + "likes": 4101, + "dislikes": 84, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "firstList = [[0,2],[5,10],[13,23],[24,25]], secondList = [[1,5],[8,12],[15,24],[25,26]]", + "expected_output": "[[1,2],[5,5],[8,10],[15,23],[24,24],[25,25]]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "firstList = [[1,3],[5,9]], secondList = []", + "expected_output": "[]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720cdd", + "questionid": 530, + "title": "Add to Array-Form of Integer", + "slug": "add-to-array-form-of-integer", + "description": "The array-form of an integer num is an array representing its digits in left to right order. Given num, the array-form of an integer, and an integer k, return the array-form of the integer num + k. ", + "category": [ + "Array", + "Math" + ], + "complexity": "Easy", + "successrate": 45.4, + "totalsubmissions": 236136, + "totalaccepted": 107305, + "likes": 1195, + "dislikes": 144, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "num = [1,2,0,0], k = 34", + "expected_output": "[1,2,3,4]", + "explanation": "1200 + 34 = 1234" + }, + { + "example_num": 2, + "expected_input": "num = [2,7,4], k = 181", + "expected_output": "[4,5,5]", + "explanation": "274 + 181 = 455" + }, + { + "example_num": 3, + "expected_input": "num = [2,1,5], k = 806", + "expected_output": "[1,0,2,1]", + "explanation": "215 + 806 = 1021" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720ce3", + "questionid": 536, + "title": "Minimum Cost to Merge Stones", + "slug": "minimum-cost-to-merge-stones", + "description": "There are n piles of stones arranged in a row. The ith pile has stones[i] stones. A move consists of merging exactly k consecutive piles into one pile, and the cost of this move is equal to the total number of stones in these k piles. Return the minimum cost to merge all piles of stones into one pile. If it is impossible, return -1. ", + "category": [ + "Array", + "Dynamic Programming" + ], + "complexity": "Hard", + "successrate": 42, + "totalsubmissions": 65248, + "totalaccepted": 27381, + "likes": 1524, + "dislikes": 79, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "stones = [3,2,4,1], k = 2", + "expected_output": "20", + "explanation": "We start with [3, 2, 4, 1].\nWe merge [3, 2] for a cost of 5, and we are left with [5, 4, 1].\nWe merge [4, 1] for a cost of 5, and we are left with [5, 5].\nWe merge [5, 5] for a cost of 10, and we are left with [10].\nThe total cost was 20, and this is the minimum possible." + }, + { + "example_num": 2, + "expected_input": "stones = [3,2,4,1], k = 3", + "expected_output": "-1", + "explanation": "After any merge operation, there are 2 piles left, and we can't merge anymore. So the task is impossible." + }, + { + "example_num": 3, + "expected_input": "stones = [3,5,1,2,6], k = 3", + "expected_output": "25", + "explanation": "We start with [3, 5, 1, 2, 6].\nWe merge [5, 1, 2] for a cost of 8, and we are left with [3, 8, 6].\nWe merge [3, 8, 6] for a cost of 17, and we are left with [17].\nThe total cost was 25, and this is the minimum possible." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720ce5", + "questionid": 538, + "title": "Find Common Characters", + "slug": "find-common-characters", + "description": "Given a string array words, return an array of all characters that show up in all strings within the words (including duplicates). You may return the answer in any order. ", + "category": [ + "Array", + "Hash Table", + "String" + ], + "complexity": "Easy", + "successrate": 68.4, + "totalsubmissions": 207326, + "totalaccepted": 141846, + "likes": 2273, + "dislikes": 184, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "words = [\"bella\",\"label\",\"roller\"]", + "expected_output": "[\"e\",\"l\",\"l\"]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "words = [\"cool\",\"lock\",\"cook\"]", + "expected_output": "[\"c\",\"o\"]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720ce6", + "questionid": 539, + "title": "Max Consecutive Ones III", + "slug": "max-consecutive-ones-iii", + "description": "Given a binary array nums and an integer k, return the maximum number of consecutive 1's in the array if you can flip at most k 0's. ", + "category": [ + "Array", + "Binary Search", + "Sliding Window", + "Prefix Sum" + ], + "complexity": "Medium", + "successrate": 62.9, + "totalsubmissions": 320003, + "totalaccepted": 201213, + "likes": 4230, + "dislikes": 55, + "hints": "One thing's for sure, we will only flip a zero if it extends an existing window of 1s. Otherwise, there's no point in doing it, right? Think Sliding Window! Since we know this problem can be solved using the sliding window construct, we might as well focus in that direction for hints. Basically, in a given window, we can never have > K zeros, right? We don't have a fixed size window in this case. The window size can grow and shrink depending upon the number of zeros we have (we don't actually have to flip the zeros here!). The way to shrink or expand a window would be based on the number of zeros that can still be flipped and so on.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,1,1,0,0,0,1,1,1,1,0], k = 2", + "expected_output": "6", + "explanation": "[1,1,1,0,0,1,1,1,1,1,1]\nBolded numbers were flipped from 0 to 1. The longest subarray is underlined." + }, + { + "example_num": 2, + "expected_input": "nums = [0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1], k = 3", + "expected_output": "10", + "explanation": "[0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1]\nBolded numbers were flipped from 0 to 1. The longest subarray is underlined." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720cea", + "questionid": 543, + "title": "Complement of Base 10 Integer", + "slug": "complement-of-base-10-integer", + "description": "The complement of an integer is the integer you get when you flip all the 0's to 1's and all the 1's to 0's in its binary representation. Given an integer n, return its complement. ", + "category": [ + "Bit Manipulation" + ], + "complexity": "Easy", + "successrate": 62.3, + "totalsubmissions": 200901, + "totalaccepted": 125125, + "likes": 1314, + "dislikes": 70, + "hints": "A binary number plus its complement will equal 111....111 in binary. Also, N = 0 is a corner case.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 5", + "expected_output": "2", + "explanation": "5 is "101" in binary, with complement "010" in binary, which is 2 in base-10." + }, + { + "example_num": 2, + "expected_input": "n = 7", + "expected_output": "0", + "explanation": "7 is "111" in binary, with complement "000" in binary, which is 0 in base-10." + }, + { + "example_num": 3, + "expected_input": "n = 10", + "expected_output": "5", + "explanation": "10 is "1010" in binary, with complement "0101" in binary, which is 5 in base-10." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720cee", + "questionid": 547, + "title": "Partition Array Into Three Parts With Equal Sum", + "slug": "partition-array-into-three-parts-with-equal-sum", + "description": "Given an array of integers arr, return true if we can partition the array into three non-empty parts with equal sums. Formally, we can partition the array if we can find indexes i + 1 < j with (arr[0] + arr[1] + ... + arr[i] == arr[i + 1] + arr[i + 2] + ... + arr[j - 1] == arr[j] + arr[j + 1] + ... + arr[arr.length - 1]) ", + "category": [ + "Array", + "Greedy" + ], + "complexity": "Easy", + "successrate": 44.5, + "totalsubmissions": 141004, + "totalaccepted": 62772, + "likes": 1093, + "dislikes": 117, + "hints": "If we have three parts with the same sum, what is the sum of each?\r\nIf you can find the first part, can you find the second part?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "arr = [0,2,1,-6,6,-7,9,1,2,0,1]", + "expected_output": "true\nExplanation: 0 + 2 + 1 = -6 + 6 - 7 + 9 + 1 = 2 + 0 + 1", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "arr = [0,2,1,-6,6,7,9,-1,2,0,1]", + "expected_output": "false", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "arr = [3,3,6,5,-2,2,5,1,-9,4]", + "expected_output": "true\nExplanation: 3 + 3 = 6 = 5 - 2 + 2 + 5 + 1 - 9 + 4", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720cf5", + "questionid": 554, + "title": "Camelcase Matching", + "slug": "camelcase-matching", + "description": "Given an array of strings queries and a string pattern, return a boolean array answer where answer[i] is true if queries[i] matches pattern, and false otherwise. A query word queries[i] matches pattern if you can insert lowercase English letters pattern so that it equals the query. You may insert each character at any position and you may not insert any characters. ", + "category": [ + "Two Pointers", + "String", + "Trie", + "String Matching" + ], + "complexity": "Medium", + "successrate": 59.1, + "totalsubmissions": 52591, + "totalaccepted": 31099, + "likes": 541, + "dislikes": 220, + "hints": "Given a single pattern and word, how can we solve it? One way to do it is using a DP (pos1, pos2) where pos1 is a pointer to the word and pos2 to the pattern and returns true if we can match the pattern with the given word. We have two scenarios: The first one is when `word[pos1] == pattern[pos2]`, then the transition will be just DP(pos1 + 1, pos2 + 1). The second scenario is when `word[pos1]` is lowercase then we can add this character to the pattern so that the transition is just DP(pos1 + 1, pos2)\r\nThe case base is `if (pos1 == n && pos2 == m) return true;` Where n and m are the sizes of the strings word and pattern respectively.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "queries = ["FooBar","FooBarTest","FootBall","FrameBuffer","ForceFeedBack"], pattern = "FB"", + "expected_output": "[true,false,true,true,false]", + "explanation": ""FooBar" can be generated like this "F" + "oo" + "B" + "ar".\n"FootBall" can be generated like this "F" + "oot" + "B" + "all".\n"FrameBuffer" can be generated like this "F" + "rame" + "B" + "uffer"." + }, + { + "example_num": 2, + "expected_input": "queries = ["FooBar","FooBarTest","FootBall","FrameBuffer","ForceFeedBack"], pattern = "FoBa"", + "expected_output": "[true,false,true,false,false]", + "explanation": ""FooBar" can be generated like this "Fo" + "o" + "Ba" + "r".\n"FootBall" can be generated like this "Fo" + "ot" + "Ba" + "ll"." + }, + { + "example_num": 3, + "expected_input": "queries = ["FooBar","FooBarTest","FootBall","FrameBuffer","ForceFeedBack"], pattern = "FoBaT"", + "expected_output": "[false,true,false,false,false]", + "explanation": ""FooBarTest" can be generated like this "Fo" + "o" + "Ba" + "r" + "T" + "est"." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720cf8", + "questionid": 557, + "title": "Recover a Tree From Preorder Traversal", + "slug": "recover-a-tree-from-preorder-traversal", + "description": "We run a preorder depth-first search (DFS) on the root of a binary tree. At each node in this traversal, we output D dashes (where D is the depth of this node), then we output the value of this node.  If the depth of a node is D, the depth of its immediate child is D + 1.  The depth of the root node is 0. If a node has only one child, that child is guaranteed to be the left child. Given the output traversal of this traversal, recover the tree and return its root. ", + "category": [ + "String", + "Tree", + "Depth-First Search", + "Binary Tree" + ], + "complexity": "Hard", + "successrate": 72.4, + "totalsubmissions": 47225, + "totalaccepted": 34187, + "likes": 1013, + "dislikes": 30, + "hints": "Do an iterative depth first search, parsing dashes from the string to inform you how to link the nodes together.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "traversal = "1-2--3--4-5--6--7"", + "expected_output": "[1,2,5,3,4,6,7]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "traversal = "1-2--3---4-5--6---7"", + "expected_output": "[1,2,5,3,null,6,null,4,null,7]", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "traversal = "1-401--349---90--88"", + "expected_output": "[1,401,null,349,88,90]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720cfa", + "questionid": 559, + "title": "Two City Scheduling", + "slug": "two-city-scheduling", + "description": "A company is planning to interview 2n people. Given the array costs where costs[i] = [aCosti, bCosti], the cost of flying the ith person to city a is aCosti, and the cost of flying the ith person to city b is bCosti. Return the minimum cost to fly every person to a city such that exactly n people arrive in each city. ", + "category": [ + "Array", + "Greedy", + "Sorting" + ], + "complexity": "Medium", + "successrate": 63.6, + "totalsubmissions": 277601, + "totalaccepted": 176436, + "likes": 3594, + "dislikes": 273, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "costs = [[10,20],[30,200],[400,50],[30,20]]", + "expected_output": "110\nExplanation: \nThe first person goes to city A for a cost of 10.\nThe second person goes to city A for a cost of 30.\nThe third person goes to city B for a cost of 50.\nThe fourth person goes to city B for a cost of 20.\n\nThe total minimum cost is 10 + 30 + 50 + 20 = 110 to have half the people interviewing in each city.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "costs = [[259,770],[448,54],[926,667],[184,139],[840,118],[577,469]]", + "expected_output": "1859", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "costs = [[515,563],[451,713],[537,709],[343,819],[855,779],[457,60],[650,359],[631,42]]", + "expected_output": "3086", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720cfe", + "questionid": 563, + "title": "Minimum Score Triangulation of Polygon", + "slug": "minimum-score-triangulation-of-polygon", + "description": "You have a convex n-sided polygon where each vertex has an integer value. You are given an integer array values where values[i] is the value of the ith vertex (i.e., clockwise order). You will triangulate the polygon into n - 2 triangles. For each triangle, the value of that triangle is the product of the values of its vertices, and the total score of the triangulation is the sum of these values over all n - 2 triangles in the triangulation. Return the smallest possible total score that you can achieve with some triangulation of the polygon. ", + "category": [ + "Array", + "Dynamic Programming" + ], + "complexity": "Medium", + "successrate": 52.5, + "totalsubmissions": 42068, + "totalaccepted": 22074, + "likes": 991, + "dislikes": 113, + "hints": "Without loss of generality, there is a triangle that uses adjacent vertices A[0] and A[N-1] (where N = A.length). Depending on your choice K of it, this breaks down the triangulation into two subproblems A[1:K] and A[K+1:N-1].", + "deleted": false, + "examples": [] + }, + { + "_id": "66f925ddfdfb8e1665720d01", + "questionid": 566, + "title": "Maximum Level Sum of a Binary Tree", + "slug": "maximum-level-sum-of-a-binary-tree", + "description": "Given the root of a binary tree, the level of its root is 1, the level of its children is 2, and so on. Return the smallest level x such that the sum of all the values of nodes at level x is maximal. ", + "category": [ + "Tree", + "Depth-First Search", + "Breadth-First Search", + "Binary Tree" + ], + "complexity": "Medium", + "successrate": 66.6, + "totalsubmissions": 152803, + "totalaccepted": 101752, + "likes": 1375, + "dislikes": 56, + "hints": "Calculate the sum for each level then find the level with the maximum sum. How can you traverse the tree ? How can you sum up the values for every level ? Use DFS or BFS to traverse the tree keeping the level of each node, and sum up those values with a map or a frequency array.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [1,7,0,7,-8,null,null]", + "expected_output": "2\nExplanation: \nLevel 1 sum = 1.\nLevel 2 sum = 7 + 0 = 7.\nLevel 3 sum = 7 + -8 = -1.\nSo we return the level with the maximum sum which is level 2.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "root = [989,null,10250,98693,-89388,null,null,null,-32127]", + "expected_output": "2", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d09", + "questionid": 574, + "title": "Previous Permutation With One Swap", + "slug": "previous-permutation-with-one-swap", + "description": "Given an array of positive integers arr (not necessarily distinct), return the lexicographically largest permutation that is smaller than arr, that can be made with exactly one swap (A swap exchanges the positions of two numbers arr[i] and arr[j]). If it cannot be done, then return the same array. ", + "category": [ + "Array", + "Greedy" + ], + "complexity": "Medium", + "successrate": 51.8, + "totalsubmissions": 58931, + "totalaccepted": 30533, + "likes": 223, + "dislikes": 23, + "hints": "You need to swap two values, one larger than the other. Where is the larger one located?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "arr = [3,2,1]", + "expected_output": "[3,1,2]", + "explanation": "Swapping 2 and 1." + }, + { + "example_num": 2, + "expected_input": "arr = [1,1,5]", + "expected_output": "[1,1,5]", + "explanation": "This is already the smallest permutation." + }, + { + "example_num": 3, + "expected_input": "arr = [1,9,4,6,7]", + "expected_output": "[1,7,4,6,9]", + "explanation": "Swapping 9 and 7." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720ccc", + "questionid": 513, + "title": "Delete Columns to Make Sorted III", + "slug": "delete-columns-to-make-sorted-iii", + "description": "You are given an array of n strings strs, all of the same length. We may choose any deletion indices, and we delete all the characters in those indices for each string. For example, if we have strs = [\"abcdef\",\"uvwxyz\"] and deletion indices {0, 2, 3}, then the final array after deletions is [\"bef\", \"vyz\"]. Suppose we chose a set of deletion indices answer such that after deletions, the final array has every string (row) in lexicographic order. (i.e., (strs[0][0] <= strs[0][1] <= ... <= strs[0][strs[0].length - 1]), and (strs[1][0] <= strs[1][1] <= ... <= strs[1][strs[1].length - 1]), and so on). Return the minimum possible value of answer.length. ", + "category": [ + "Array", + "String", + "Dynamic Programming" + ], + "complexity": "Hard", + "successrate": 56.5, + "totalsubmissions": 18026, + "totalaccepted": 10191, + "likes": 421, + "dislikes": 11, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "strs = ["babca","bbazb"]", + "expected_output": "3", + "explanation": "After deleting columns 0, 1, and 4, the final array is strs = ["bc", "az"].\nBoth these rows are individually in lexicographic order (ie. strs[0][0] <= strs[0][1] and strs[1][0] <= strs[1][1]).\nNote that strs[0] > strs[1] - the array strs is not necessarily in lexicographic order." + }, + { + "example_num": 2, + "expected_input": "strs = ["edcba"]", + "expected_output": "4", + "explanation": "If we delete less than 4 columns, the only row will not be lexicographically sorted." + }, + { + "example_num": 3, + "expected_input": "strs = ["ghi","def","abc"]", + "expected_output": "0", + "explanation": "All rows are already lexicographically sorted." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720cd7", + "questionid": 524, + "title": "Squares of a Sorted Array", + "slug": "squares-of-a-sorted-array", + "description": "Given an integer array nums sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order. ", + "category": [ + "Array", + "Two Pointers", + "Sorting" + ], + "complexity": "Easy", + "successrate": 71.6, + "totalsubmissions": 1324165, + "totalaccepted": 948265, + "likes": 5114, + "dislikes": 150, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [-4,-1,0,3,10]", + "expected_output": "[0,1,9,16,100]", + "explanation": "After squaring, the array becomes [16,1,0,9,100].\nAfter sorting, it becomes [0,1,9,16,100]." + }, + { + "example_num": 2, + "expected_input": "nums = [-7,-3,2,3,11]", + "expected_output": "[4,9,9,49,121]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720cdb", + "questionid": 528, + "title": "Vertical Order Traversal of a Binary Tree", + "slug": "vertical-order-traversal-of-a-binary-tree", + "description": "Given the root of a binary tree, calculate the vertical order traversal of the binary tree. For each node at position (row, col), its left and right children will be at positions (row + 1, col - 1) and (row + 1, col + 1) respectively. The root of the tree is at (0, 0). The vertical order traversal of a binary tree is a list of top-to-bottom orderings for each column index starting from the leftmost column and ending on the rightmost column. There may be multiple nodes in the same row and same column. In such a case, sort these nodes by their values. Return the vertical order traversal of the binary tree. ", + "category": [ + "Hash Table", + "Tree", + "Depth-First Search", + "Breadth-First Search", + "Binary Tree" + ], + "complexity": "Hard", + "successrate": 41.4, + "totalsubmissions": 520150, + "totalaccepted": 215521, + "likes": 3104, + "dislikes": 3293, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [3,9,20,null,null,15,7]", + "expected_output": "[[9],[3,15],[20],[7]]", + "explanation": "Column -1: Only node 9 is in this column.\nColumn 0: Nodes 3 and 15 are in this column in that order from top to bottom.\nColumn 1: Only node 20 is in this column.\nColumn 2: Only node 7 is in this column." + }, + { + "example_num": 2, + "expected_input": "root = [1,2,3,4,5,6,7]", + "expected_output": "[[4],[2],[1,5,6],[3],[7]]", + "explanation": "Column -2: Only node 4 is in this column.\nColumn -1: Only node 2 is in this column.\nColumn 0: Nodes 1, 5, and 6 are in this column.\n 1 is at the top, so it comes first.\n 5 and 6 are at the same position (2, 0), so we order them by their value, 5 before 6.\nColumn 1: Only node 3 is in this column.\nColumn 2: Only node 7 is in this column." + }, + { + "example_num": 3, + "expected_input": "root = [1,2,3,4,6,5,7]", + "expected_output": "[[4],[2],[1,5,6],[3],[7]]", + "explanation": "This case is the exact same as example 2, but with nodes 5 and 6 swapped.\nNote that the solution remains the same since 5 and 6 are in the same location and should be ordered by their values." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720ce2", + "questionid": 535, + "title": "Available Captures for Rook", + "slug": "available-captures-for-rook", + "description": "On an 8 x 8 chessboard, there is exactly one white rook 'R' and some number of white bishops 'B', black pawns 'p', and empty squares '.'. When the rook moves, it chooses one of four cardinal directions (north, east, south, or west), then moves in that direction until it chooses to stop, reaches the edge of the board, captures a black pawn, or is blocked by a white bishop. A rook is considered attacking a pawn if the rook can capture the pawn on the rook's turn. The number of available captures for the white rook is the number of pawns that the rook is attacking. Return the number of available captures for the white rook. ", + "category": [ + "Array", + "Matrix", + "Simulation" + ], + "complexity": "Easy", + "successrate": 67.5, + "totalsubmissions": 73332, + "totalaccepted": 49531, + "likes": 443, + "dislikes": 560, + "hints": "", + "deleted": false, + "examples": [] + }, + { + "_id": "66f925ddfdfb8e1665720cf0", + "questionid": 549, + "title": "Convert to Base -2", + "slug": "convert-to-base-2", + "description": "Given an integer n, return a binary string representing its representation in base -2. Note that the returned string should not have leading zeros unless the string is \"0\". ", + "category": [ + "Math" + ], + "complexity": "Medium", + "successrate": 60.2, + "totalsubmissions": 30310, + "totalaccepted": 18251, + "likes": 346, + "dislikes": 225, + "hints": "Figure out whether you need the ones digit placed or not, then shift by two.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 2", + "expected_output": ""110"\nExplantion: (-2)2 + (-2)1 = 2", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "n = 3", + "expected_output": ""111"\nExplantion: (-2)2 + (-2)1 + (-2)0 = 3", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "n = 4", + "expected_output": ""100"\nExplantion: (-2)2 = 4", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d06", + "questionid": 571, + "title": "Last Substring in Lexicographical Order", + "slug": "last-substring-in-lexicographical-order", + "description": "Given a string s, return the last substring of s in lexicographical order. ", + "category": [ + "Two Pointers", + "String" + ], + "complexity": "Hard", + "successrate": 35.6, + "totalsubmissions": 82473, + "totalaccepted": 29361, + "likes": 435, + "dislikes": 406, + "hints": "Assume that the answer is a sub-string from index i to j. If you add the character at index j+1 you get a better answer. The answer is always a suffix of the given string. Since the limits are high, we need an efficient data structure. Use suffix array.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "abab"", + "expected_output": ""bab"", + "explanation": "The substrings are ["a", "ab", "aba", "abab", "b", "ba", "bab"]. The lexicographically maximum substring is "bab"." + }, + { + "example_num": 2, + "expected_input": "s = "leetcode"", + "expected_output": ""tcode"", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720cce", + "questionid": 515, + "title": "Minimum Area Rectangle II", + "slug": "minimum-area-rectangle-ii", + "description": "You are given an array of points in the X-Y plane points where points[i] = [xi, yi]. Return the minimum area of any rectangle formed from these points, with sides not necessarily parallel to the X and Y axes. If there is not any such rectangle, return 0. Answers within 10-5 of the actual answer will be accepted. ", + "category": [ + "Array", + "Math", + "Geometry" + ], + "complexity": "Medium", + "successrate": 54.4, + "totalsubmissions": 41787, + "totalaccepted": 22753, + "likes": 302, + "dislikes": 400, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "points = [[1,2],[2,1],[1,0],[0,1]]", + "expected_output": "2.00000", + "explanation": "The minimum area rectangle occurs at [1,2],[2,1],[1,0],[0,1], with an area of 2." + }, + { + "example_num": 2, + "expected_input": "points = [[0,1],[2,1],[1,1],[1,0],[2,0]]", + "expected_output": "1.00000", + "explanation": "The minimum area rectangle occurs at [1,0],[1,1],[2,1],[2,0], with an area of 1." + }, + { + "example_num": 3, + "expected_input": "points = [[0,3],[1,2],[3,1],[1,3],[2,1]]", + "expected_output": "0", + "explanation": "There is no possible rectangle to form from these points." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720ccf", + "questionid": 516, + "title": "Univalued Binary Tree", + "slug": "univalued-binary-tree", + "description": "A binary tree is uni-valued if every node in the tree has the same value. Given the root of a binary tree, return true if the given tree is uni-valued, or false otherwise. ", + "category": [ + "Tree", + "Depth-First Search", + "Breadth-First Search", + "Binary Tree" + ], + "complexity": "Easy", + "successrate": 68.9, + "totalsubmissions": 227655, + "totalaccepted": 156880, + "likes": 1259, + "dislikes": 56, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [1,1,1,1,1,null,1]", + "expected_output": "true", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "root = [2,2,2,5,2]", + "expected_output": "false", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720cd0", + "questionid": 517, + "title": "Numbers With Same Consecutive Differences", + "slug": "numbers-with-same-consecutive-differences", + "description": "Return all non-negative integers of length n such that the absolute difference between every two consecutive digits is k. Note that every number in the answer must not have leading zeros. For example, 01 has one leading zero and is invalid. You may return the answer in any order. ", + "category": [ + "Backtracking", + "Breadth-First Search" + ], + "complexity": "Medium", + "successrate": 47.2, + "totalsubmissions": 105324, + "totalaccepted": 49756, + "likes": 860, + "dislikes": 131, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 3, k = 7", + "expected_output": "[181,292,707,818,929]", + "explanation": "Note that 070 is not a valid number, because it has leading zeroes." + }, + { + "example_num": 2, + "expected_input": "n = 2, k = 1", + "expected_output": "[10,12,21,23,32,34,43,45,54,56,65,67,76,78,87,89,98]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720cd2", + "questionid": 519, + "title": "Powerful Integers", + "slug": "powerful-integers", + "description": "Given three integers x, y, and bound, return a list of all the powerful integers that have a value less than or equal to bound. An integer is powerful if it can be represented as xi + yj for some integers i >= 0 and j >= 0. You may return the answer in any order. In your answer, each value should occur at most once. ", + "category": [ + "Hash Table", + "Math" + ], + "complexity": "Medium", + "successrate": 43.6, + "totalsubmissions": 105922, + "totalaccepted": 46133, + "likes": 242, + "dislikes": 62, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "x = 2, y = 3, bound = 10", + "expected_output": "[2,3,4,5,7,9,10]", + "explanation": "2 = 20 + 30\n3 = 21 + 30\n4 = 20 + 31\n5 = 21 + 31\n7 = 22 + 31\n9 = 23 + 30\n10 = 20 + 32" + }, + { + "example_num": 2, + "expected_input": "x = 3, y = 5, bound = 15", + "expected_output": "[2,4,6,8,10,14]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720cd5", + "questionid": 522, + "title": "Subarray Sums Divisible by K", + "slug": "subarray-sums-divisible-by-k", + "description": "Given an integer array nums and an integer k, return the number of non-empty subarrays that have a sum divisible by k. A subarray is a contiguous part of an array. ", + "category": [ + "Array", + "Hash Table", + "Prefix Sum" + ], + "complexity": "Medium", + "successrate": 53.2, + "totalsubmissions": 174162, + "totalaccepted": 92620, + "likes": 2709, + "dislikes": 133, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [4,5,0,-2,-3,1], k = 5", + "expected_output": "7", + "explanation": "There are 7 subarrays with a sum divisible by k = 5:\n[4, 5, 0, -2, -3, 1], [5], [5, 0], [5, 0, -2, -3], [0], [0, -2, -3], [-2, -3]" + }, + { + "example_num": 2, + "expected_input": "nums = [5], k = 9", + "expected_output": "0", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720cdc", + "questionid": 529, + "title": "Smallest String Starting From Leaf", + "slug": "smallest-string-starting-from-leaf", + "description": "You are given the root of a binary tree where each node has a value in the range [0, 25] representing the letters 'a' to 'z'. Return the lexicographically smallest string that starts at a leaf of this tree and ends at the root. As a reminder, any shorter prefix of a string is lexicographically smaller. A leaf of a node is a node that has no children. ", + "category": [ + "String", + "Tree", + "Depth-First Search", + "Binary Tree" + ], + "complexity": "Medium", + "successrate": 48.6, + "totalsubmissions": 107393, + "totalaccepted": 52244, + "likes": 1046, + "dislikes": 168, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [0,1,2,3,4,3,4]", + "expected_output": ""dba"", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "root = [25,1,3,1,3,0,2]", + "expected_output": ""adz"", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "root = [2,2,1,null,1,0,null,0]", + "expected_output": ""abc"", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720ce0", + "questionid": 533, + "title": "Minimum Number of K Consecutive Bit Flips", + "slug": "minimum-number-of-k-consecutive-bit-flips", + "description": "You are given a binary array nums and an integer k. A k-bit flip is choosing a subarray of length k from nums and simultaneously changing every 0 in the subarray to 1, and every 1 in the subarray to 0. Return the minimum number of k-bit flips required so that there is no 0 in the array. If it is not possible, return -1. A subarray is a contiguous part of an array. ", + "category": [ + "Array", + "Bit Manipulation", + "Sliding Window", + "Prefix Sum" + ], + "complexity": "Hard", + "successrate": 50.7, + "totalsubmissions": 49867, + "totalaccepted": 25291, + "likes": 792, + "dislikes": 49, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [0,1,0], k = 1", + "expected_output": "2", + "explanation": "Flip nums[0], then flip nums[2]." + }, + { + "example_num": 2, + "expected_input": "nums = [1,1,0], k = 2", + "expected_output": "-1", + "explanation": "No matter how we flip subarrays of size 2, we cannot make the array become [1,1,1]." + }, + { + "example_num": 3, + "expected_input": "nums = [0,0,0,1,0,1,1,0], k = 3", + "expected_output": "3", + "explanation": "Flip nums[0],nums[1],nums[2]: nums becomes [1,1,1,1,0,1,1,0]\nFlip nums[4],nums[5],nums[6]: nums becomes [1,1,1,1,1,0,0,0]\nFlip nums[5],nums[6],nums[7]: nums becomes [1,1,1,1,1,1,1,1]" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720ce7", + "questionid": 540, + "title": "Clumsy Factorial", + "slug": "clumsy-factorial", + "description": "The factorial of a positive integer n is the product of all positive integers less than or equal to n. We make a clumsy factorial using the integers in decreasing order by swapping out the multiply operations for a fixed rotation of operations with multiply '*', divide '/', add '+', and subtract '-' in this order. However, these operations are still applied using the usual order of operations of arithmetic. We do all multiplication and division steps before any addition or subtraction steps, and multiplication and division steps are processed left to right. Additionally, the division that we use is floor division such that 10 * 9 / 8 = 90 / 8 = 11. Given an integer n, return the clumsy factorial of n. ", + "category": [ + "Math", + "Stack", + "Simulation" + ], + "complexity": "Medium", + "successrate": 54.7, + "totalsubmissions": 36299, + "totalaccepted": 19854, + "likes": 186, + "dislikes": 228, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 4", + "expected_output": "7", + "explanation": "7 = 4 * 3 / 2 + 1" + }, + { + "example_num": 2, + "expected_input": "n = 10", + "expected_output": "12", + "explanation": "12 = 10 * 9 / 8 + 7 - 6 * 5 / 4 + 3 - 2 * 1" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720ce8", + "questionid": 541, + "title": "Minimum Domino Rotations For Equal Row", + "slug": "minimum-domino-rotations-for-equal-row", + "description": "In a row of dominoes, tops[i] and bottoms[i] represent the top and bottom halves of the ith domino. (A domino is a tile with two numbers from 1 to 6 - one on each half of the tile.) We may rotate the ith domino, so that tops[i] and bottoms[i] swap values. Return the minimum number of rotations so that all the values in tops are the same, or all the values in bottoms are the same. If it cannot be done, return -1. ", + "category": [ + "Array", + "Greedy" + ], + "complexity": "Medium", + "successrate": 52.6, + "totalsubmissions": 337683, + "totalaccepted": 177735, + "likes": 2423, + "dislikes": 239, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "tops = [2,1,2,4,2,2], bottoms = [5,2,6,2,3,2]", + "expected_output": "2", + "explanation": "The first figure represents the dominoes as given by tops and bottoms: before we do any rotations.\nIf we rotate the second and fourth dominoes, we can make every value in the top row equal to 2, as indicated by the second figure." + }, + { + "example_num": 2, + "expected_input": "tops = [3,5,1,2,3], bottoms = [3,6,3,3,4]", + "expected_output": "-1", + "explanation": "In this case, it is not possible to rotate the dominoes to make one row of values equal." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720ce9", + "questionid": 542, + "title": "Construct Binary Search Tree from Preorder Traversal", + "slug": "construct-binary-search-tree-from-preorder-traversal", + "description": "Given an array of integers preorder, which represents the preorder traversal of a BST (i.e., binary search tree), construct the tree and return its root. It is guaranteed that there is always possible to find a binary search tree with the given requirements for the given test cases. A binary search tree is a binary tree where for every node, any descendant of Node.left has a value strictly less than Node.val, and any descendant of Node.right has a value strictly greater than Node.val. A preorder traversal of a binary tree displays the value of the node first, then traverses Node.left, then traverses Node.right. ", + "category": [ + "Array", + "Stack", + "Tree", + "Binary Search Tree", + "Monotonic Stack", + "Binary Tree" + ], + "complexity": "Medium", + "successrate": 80.2, + "totalsubmissions": 287043, + "totalaccepted": 230198, + "likes": 3543, + "dislikes": 60, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "preorder = [8,5,1,7,10,12]", + "expected_output": "[8,5,10,1,7,null,12]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "preorder = [1,3]", + "expected_output": "[1,null,3]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720cec", + "questionid": 545, + "title": "Capacity To Ship Packages Within D Days", + "slug": "capacity-to-ship-packages-within-d-days", + "description": "A conveyor belt has packages that must be shipped from one port to another within days days. The ith package on the conveyor belt has a weight of weights[i]. Each day, we load the ship with packages on the conveyor belt (in the order given by weights). We may not load more weight than the maximum weight capacity of the ship. Return the least weight capacity of the ship that will result in all the packages on the conveyor belt being shipped within days days. ", + "category": [ + "Array", + "Binary Search", + "Greedy" + ], + "complexity": "Medium", + "successrate": 63.5, + "totalsubmissions": 225076, + "totalaccepted": 142938, + "likes": 4119, + "dislikes": 94, + "hints": "Binary search on the answer. We need a function possible(capacity) which returns true if and only if we can do the task in D days.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "weights = [1,2,3,4,5,6,7,8,9,10], days = 5", + "expected_output": "15", + "explanation": "A ship capacity of 15 is the minimum to ship all the packages in 5 days like this:\n1st day: 1, 2, 3, 4, 5\n2nd day: 6, 7\n3rd day: 8\n4th day: 9\n5th day: 10\n\nNote that the cargo must be shipped in the order given, so using a ship of capacity 14 and splitting the packages into parts like (2, 3, 4, 5), (1, 6, 7), (8), (9), (10) is not allowed." + }, + { + "example_num": 2, + "expected_input": "weights = [3,2,2,4,1,4], days = 3", + "expected_output": "6", + "explanation": "A ship capacity of 6 is the minimum to ship all the packages in 3 days like this:\n1st day: 3, 2\n2nd day: 2, 4\n3rd day: 1, 4" + }, + { + "example_num": 3, + "expected_input": "weights = [1,2,3,1,1], days = 4", + "expected_output": "3", + "explanation": "1st day: 1\n2nd day: 2\n3rd day: 3\n4th day: 1, 1" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720cef", + "questionid": 548, + "title": "Binary String With Substrings Representing 1 To N", + "slug": "binary-string-with-substrings-representing-1-to-n", + "description": "Given a binary string s and a positive integer n, return true if the binary representation of all the integers in the range [1, n] are substrings of s, or false otherwise. A substring is a contiguous sequence of characters within a string. ", + "category": [ + "String" + ], + "complexity": "Medium", + "successrate": 57.9, + "totalsubmissions": 49096, + "totalaccepted": 28428, + "likes": 247, + "dislikes": 453, + "hints": "We only need to check substrings of length at most 30, because 10^9 has 30 bits.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = \"0110\", n = 3", + "expected_output": "true", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "s = \"0110\", n = 4", + "expected_output": "false", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720cf3", + "questionid": 552, + "title": "Number of Enclaves", + "slug": "number-of-enclaves", + "description": "You are given an m x n binary matrix grid, where 0 represents a sea cell and 1 represents a land cell. A move consists of walking from one land cell to another adjacent (4-directionally) land cell or walking off the boundary of the grid. Return the number of land cells in grid for which we cannot walk off the boundary of the grid in any number of moves. ", + "category": [ + "Array", + "Depth-First Search", + "Breadth-First Search", + "Union Find", + "Matrix" + ], + "complexity": "Medium", + "successrate": 62.6, + "totalsubmissions": 82170, + "totalaccepted": 51438, + "likes": 1172, + "dislikes": 32, + "hints": "Can you model this problem as a graph problem? Create n * m + 1 nodes where n * m nodes represents each cell of the map and one extra node to represent the exterior of the map. In the map add edges between neighbors on land cells. And add edges between the exterior and land nodes which are in the boundary.\r\nReturn as answer the number of nodes that are not reachable from the exterior node.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "grid = [[0,0,0,0],[1,0,1,0],[0,1,1,0],[0,0,0,0]]", + "expected_output": "3", + "explanation": "There are three 1s that are enclosed by 0s, and one 1 that is not enclosed because its on the boundary." + }, + { + "example_num": 2, + "expected_input": "grid = [[0,1,1,0],[0,0,1,0],[0,0,1,0],[0,0,0,0]]", + "expected_output": "0", + "explanation": "All 1s are either on the boundary or can reach the boundary." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720cf6", + "questionid": 555, + "title": "Video Stitching", + "slug": "video-stitching", + "description": "You are given a series of video clips from a sporting event that lasted time seconds. These video clips can be overlapping with each other and have varying lengths. Each video clip is described by an array clips where clips[i] = [starti, endi] indicates that the ith clip started at starti and ended at endi. We can cut these clips into segments freely. Return the minimum number of clips needed so that we can cut the clips into segments that cover the entire sporting event [0, time]. If the task is impossible, return -1. ", + "category": [ + "Array", + "Dynamic Programming", + "Greedy" + ], + "complexity": "Medium", + "successrate": 50, + "totalsubmissions": 92645, + "totalaccepted": 46356, + "likes": 1179, + "dislikes": 47, + "hints": "What if we sort the intervals? Considering the sorted intervals, how can we solve the problem with dynamic programming? Let's consider a DP(pos, limit) where pos represents the position of the current interval we are gonna take the decision and limit is the current covered area from [0 - limit]. This DP returns the minimum number of taken intervals or infinite if it's not possible to cover the [0 - T] section.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "clips = [[0,2],[4,6],[8,10],[1,9],[1,5],[5,9]], time = 10", + "expected_output": "3", + "explanation": "We take the clips [0,2], [8,10], [1,9]; a total of 3 clips.\nThen, we can reconstruct the sporting event as follows:\nWe cut [1,9] into segments [1,2] + [2,8] + [8,9].\nNow we have segments [0,2] + [2,8] + [8,10] which cover the sporting event [0, 10]." + }, + { + "example_num": 2, + "expected_input": "clips = [[0,1],[1,2]], time = 5", + "expected_output": "-1", + "explanation": "We cannot cover [0,5] with only [0,1] and [1,2]." + }, + { + "example_num": 3, + "expected_input": "clips = [[0,1],[6,8],[0,2],[5,6],[0,4],[0,3],[6,7],[1,3],[4,7],[1,4],[2,5],[2,6],[3,4],[4,5],[5,7],[6,9]], time = 9", + "expected_output": "3", + "explanation": "We can take clips [0,4], [4,7], and [6,9]." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720cf7", + "questionid": 556, + "title": "Longest Arithmetic Subsequence", + "slug": "longest-arithmetic-subsequence", + "description": "Given an array nums of integers, return the length of the longest arithmetic subsequence in nums. Recall that a subsequence of an array nums is a list nums[i1], nums[i2], ..., nums[ik] with 0 <= i1 < i2 < ... < ik <= nums.length - 1, and that a sequence seq is arithmetic if seq[i+1] - seq[i] are all the same value (for 0 <= i < seq.length - 1). ", + "category": [ + "Array", + "Hash Table", + "Binary Search", + "Dynamic Programming" + ], + "complexity": "Medium", + "successrate": 48.2, + "totalsubmissions": 175733, + "totalaccepted": 84715, + "likes": 2049, + "dislikes": 97, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [3,6,9,12]", + "expected_output": "4\nExplanation: The whole array is an arithmetic sequence with steps of length = 3.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "nums = [9,4,7,2,10]", + "expected_output": "3\nExplanation: The longest arithmetic subsequence is [4,7,10].", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "nums = [20,1,15,3,10,5,8]", + "expected_output": "4\nExplanation: The longest arithmetic subsequence is [20,15,10,5].", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720cfb", + "questionid": 560, + "title": "Maximum Sum of Two Non-Overlapping Subarrays", + "slug": "maximum-sum-of-two-non-overlapping-subarrays", + "description": "Given an integer array nums and two integers firstLen and secondLen, return the maximum sum of elements in two non-overlapping subarrays with lengths firstLen and secondLen. The array with length firstLen could occur before or after the array with length secondLen, but they have to be non-overlapping. A subarray is a contiguous part of an array. ", + "category": [ + "Array", + "Dynamic Programming", + "Sliding Window" + ], + "complexity": "Medium", + "successrate": 59.4, + "totalsubmissions": 82510, + "totalaccepted": 49020, + "likes": 1660, + "dislikes": 70, + "hints": "We can use prefix sums to calculate any subarray sum quickly.\r\nFor each L length subarray, find the best possible M length subarray that occurs before and after it.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [0,6,5,2,2,5,1,9,4], firstLen = 1, secondLen = 2", + "expected_output": "20", + "explanation": "One choice of subarrays is [9] with length 1, and [6,5] with length 2." + }, + { + "example_num": 2, + "expected_input": "nums = [3,8,1,3,2,1,8,9,0], firstLen = 3, secondLen = 2", + "expected_output": "29", + "explanation": "One choice of subarrays is [3,8,1] with length 3, and [8,9] with length 2." + }, + { + "example_num": 3, + "expected_input": "nums = [2,1,5,6,0,9,5,0,3,8], firstLen = 4, secondLen = 3", + "expected_output": "31", + "explanation": "One choice of subarrays is [5,6,0,9] with length 4, and [0,3,8] with length 3." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720cff", + "questionid": 564, + "title": "Find Words That Can Be Formed by Characters", + "slug": "find-words-that-can-be-formed-by-characters", + "description": "You are given an array of strings words and a string chars. A string is good if it can be formed by characters from chars (each character can only be used once). Return the sum of lengths of all good strings in words. ", + "category": [ + "Array", + "Hash Table", + "String" + ], + "complexity": "Easy", + "successrate": 67.7, + "totalsubmissions": 165666, + "totalaccepted": 112147, + "likes": 959, + "dislikes": 120, + "hints": "Solve the problem for each string in words independently. Now try to think in frequency of letters. Count how many times each character occurs in string chars. To form a string using characters from chars, the frequency of each character in chars must be greater than or equal the frequency of that character in the string to be formed.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "words = ["cat","bt","hat","tree"], chars = "atach"", + "expected_output": "6", + "explanation": "The strings that can be formed are "cat" and "hat" so the answer is 3 + 3 = 6." + }, + { + "example_num": 2, + "expected_input": "words = ["hello","world","leetcode"], chars = "welldonehoneyr"", + "expected_output": "10", + "explanation": "The strings that can be formed are "hello" and "world" so the answer is 5 + 5 = 10." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d05", + "questionid": 570, + "title": "Longest String Chain", + "slug": "longest-string-chain", + "description": "You are given an array of words where each word consists of lowercase English letters. wordA is a predecessor of wordB if and only if we can insert exactly one letter anywhere in wordA without changing the order of the other characters to make it equal to wordB. A word chain is a sequence of words [word1, word2, ..., wordk] with k >= 1, where word1 is a predecessor of word2, word2 is a predecessor of word3, and so on. A single word is trivially a word chain with k == 1. Return the length of the longest possible word chain with words chosen from the given list of words. ", + "category": [ + "Array", + "Hash Table", + "Two Pointers", + "String", + "Dynamic Programming" + ], + "complexity": "Medium", + "successrate": 57.8, + "totalsubmissions": 338994, + "totalaccepted": 195915, + "likes": 3279, + "dislikes": 161, + "hints": "Instead of adding a character, try deleting a character to form a chain in reverse. For each word in order of length, for each word2 which is word with one character removed, length[word2] = max(length[word2], length[word] + 1).", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "words = ["a","b","ba","bca","bda","bdca"]", + "expected_output": "4\nExplanation: One of the longest word chains is ["a","ba","bda","bdca"].", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "words = ["xbc","pcxbcf","xb","cxbc","pcxbc"]", + "expected_output": "5", + "explanation": "All the words can be put in a word chain ["xb", "xbc", "cxbc", "pcxbc", "pcxbcf"]." + }, + { + "example_num": 3, + "expected_input": "words = ["abcd","dbqca"]", + "expected_output": "1", + "explanation": "The trivial word chain ["abcd"] is one of the longest word chains.\n["abcd","dbqca"] is not a valid word chain because the ordering of the letters is changed." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d07", + "questionid": 572, + "title": "Height Checker", + "slug": "height-checker", + "description": "A school is trying to take an annual photo of all the students. The students are asked to stand in a single file line in non-decreasing order by height. Let this ordering be represented by the integer array expected where expected[i] is the expected height of the ith student in line. You are given an integer array heights representing the current order that the students are standing in. Each heights[i] is the height of the ith student in line (0-indexed). Return the number of indices where heights[i] != expected[i]. ", + "category": [ + "Array", + "Sorting", + "Counting Sort" + ], + "complexity": "Easy", + "successrate": 74.3, + "totalsubmissions": 262388, + "totalaccepted": 194845, + "likes": 428, + "dislikes": 47, + "hints": "Build the correct order of heights by sorting another array, then compare the two arrays.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "heights = [1,1,4,2,1,3]", + "expected_output": "3", + "explanation": "heights: [1,1,4,2,1,3]\nexpected: [1,1,1,2,3,4]\nIndices 2, 4, and 5 do not match." + }, + { + "example_num": 2, + "expected_input": "heights = [5,1,2,3,4]", + "expected_output": "5", + "explanation": "heights: [5,1,2,3,4]\nexpected: [1,2,3,4,5]\nAll indices do not match." + }, + { + "example_num": 3, + "expected_input": "heights = [1,2,3,4,5]", + "expected_output": "0", + "explanation": "heights: [1,2,3,4,5]\nexpected: [1,2,3,4,5]\nAll indices match." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d0a", + "questionid": 575, + "title": "Distant Barcodes", + "slug": "distant-barcodes", + "description": "In a warehouse, there is a row of barcodes, where the ith barcode is barcodes[i]. Rearrange the barcodes so that no two adjacent barcodes are equal. You may return any answer, and it is guaranteed an answer exists. ", + "category": [ + "Array", + "Hash Table", + "Greedy", + "Sorting", + "Heap (Priority Queue)", + "Counting" + ], + "complexity": "Medium", + "successrate": 45.2, + "totalsubmissions": 65587, + "totalaccepted": 29644, + "likes": 828, + "dislikes": 36, + "hints": "We want to always choose the most common or second most common element to write next. What data structure allows us to query this effectively?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "barcodes = [1,1,1,2,2,2]", + "expected_output": "[2,1,2,1,2,1]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "barcodes = [1,1,1,1,2,2,3,3]", + "expected_output": "[1,3,1,3,1,2,1,2]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d0f", + "questionid": 580, + "title": "Smallest Subsequence of Distinct Characters", + "slug": "smallest-subsequence-of-distinct-characters", + "description": "Given a string s, return the lexicographically smallest subsequence of s that contains all the distinct characters of s exactly once. ", + "category": [ + "String", + "Stack", + "Greedy", + "Monotonic Stack" + ], + "complexity": "Medium", + "successrate": 56.8, + "totalsubmissions": 66954, + "totalaccepted": 38059, + "likes": 1618, + "dislikes": 142, + "hints": "Greedily try to add one missing character. How to check if adding some character will not cause problems ? Use bit-masks to check whether you will be able to complete the sub-sequence if you add the character at some index i.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "bcabc"", + "expected_output": ""abc"", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "s = "cbacdcbc"", + "expected_output": ""acdb"", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d11", + "questionid": 582, + "title": "Duplicate Zeros", + "slug": "duplicate-zeros", + "description": "Given a fixed-length integer array arr, duplicate each occurrence of zero, shifting the remaining elements to the right. Note that elements beyond the length of the original array are not written. Do the above modifications to the input array in place and do not return anything. ", + "category": [ + "Array", + "Two Pointers" + ], + "complexity": "Easy", + "successrate": 51.1, + "totalsubmissions": 509601, + "totalaccepted": 260589, + "likes": 1624, + "dislikes": 522, + "hints": "This is a great introductory problem for understanding and working with the concept of in-place operations. The problem statement clearly states that we are to modify the array in-place. That does not mean we cannot use another array. We just don't have to return anything. A better way to solve this would be without using additional space. The only reason the problem statement allows you to make modifications in place is that it hints at avoiding any additional memory. The main problem with not using additional memory is that we might override elements due to the zero duplication requirement of the problem statement. How do we get around that? If we had enough space available, we would be able to accommodate all the elements properly. The new length would be the original length of the array plus the number of zeros. Can we use this information somehow to solve the problem?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "arr = [1,0,2,3,0,4,5,0]", + "expected_output": "[1,0,0,2,3,0,0,4]", + "explanation": "After calling your function, the input array is modified to: [1,0,0,2,3,0,0,4]" + }, + { + "example_num": 2, + "expected_input": "arr = [1,2,3]", + "expected_output": "[1,2,3]", + "explanation": "After calling your function, the input array is modified to: [1,2,3]" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d14", + "questionid": 585, + "title": "Path In Zigzag Labelled Binary Tree", + "slug": "path-in-zigzag-labelled-binary-tree", + "description": "In an infinite binary tree where every node has two children, the nodes are labelled in row order. In the odd numbered rows (ie., the first, third, fifth,...), the labelling is left to right, while in the even numbered rows (second, fourth, sixth,...), the labelling is right to left. Given the label of a node in this tree, return the labels in the path from the root of the tree to the node with that label. ", + "category": [ + "Math", + "Tree", + "Binary Tree" + ], + "complexity": "Medium", + "successrate": 74.5, + "totalsubmissions": 43751, + "totalaccepted": 32604, + "likes": 953, + "dislikes": 261, + "hints": "Based on the label of the current node, find what the label must be for the parent of that node.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "label = 14", + "expected_output": "[1,3,4,14]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "label = 26", + "expected_output": "[1,2,6,10,26]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d16", + "questionid": 587, + "title": "Defanging an IP Address", + "slug": "defanging-an-ip-address", + "description": "Given a valid (IPv4) IP address, return a defanged version of that IP address. A defanged IP address replaces every period \".\" with \"[.]\". ", + "category": [ + "String" + ], + "complexity": "Easy", + "successrate": 89, + "totalsubmissions": 450803, + "totalaccepted": 401039, + "likes": 1072, + "dislikes": 1457, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "address = \"1.1.1.1\"", + "expected_output": "\"1[.]1[.]1[.]1\"", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "address = \"255.100.50.0\"", + "expected_output": "\"255[.]100[.]50[.]0\"", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d1d", + "questionid": 594, + "title": "Element Appearing More Than 25% In Sorted Array", + "slug": "element-appearing-more-than-25-in-sorted-array", + "description": "Given an integer array sorted in non-decreasing order, there is exactly one integer in the array that occurs more than 25% of the time, return that integer. ", + "category": [ + "Array" + ], + "complexity": "Easy", + "successrate": 59.5, + "totalsubmissions": 103670, + "totalaccepted": 61720, + "likes": 636, + "dislikes": 36, + "hints": "Divide the array in four parts [1 - 25%] [25 - 50 %] [50 - 75 %] [75% - 100%] The answer should be in one of the ends of the intervals. In order to check which is element is the answer we can count the frequency with binarySearch.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "arr = [1,2,2,6,6,6,6,7,10]", + "expected_output": "6", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "arr = [1,1]", + "expected_output": "1", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d22", + "questionid": 599, + "title": "Sum of Mutated Array Closest to Target", + "slug": "sum-of-mutated-array-closest-to-target", + "description": "Given an integer array arr and a target value target, return the integer value such that when we change all the integers larger than value in the given array to be equal to value, the sum of the array gets as close as possible (in absolute difference) to target. In case of a tie, return the minimum such integer. Notice that the answer is not neccesarilly a number from arr. ", + "category": [ + "Array", + "Binary Search", + "Sorting" + ], + "complexity": "Medium", + "successrate": 42.5, + "totalsubmissions": 57122, + "totalaccepted": 24305, + "likes": 736, + "dislikes": 89, + "hints": "If you draw a graph with the value on one axis and the absolute difference between the target and the array sum, what will you get? That graph is uni-modal. Use ternary search on that graph to find the best value.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "arr = [4,9,3], target = 10", + "expected_output": "3", + "explanation": "When using 3 arr converts to [3, 3, 3] which sums 9 and that's the optimal answer." + }, + { + "example_num": 2, + "expected_input": "arr = [2,3,5], target = 10", + "expected_output": "5", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "arr = [60864,25176,27249,21296,20204], target = 56803", + "expected_output": "11361", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d23", + "questionid": 600, + "title": "Largest 1-Bordered Square", + "slug": "largest-1-bordered-square", + "description": "Given a 2D grid of 0s and 1s, return the number of elements in the largest square subgrid that has all 1s on its border, or 0 if such a subgrid doesn't exist in the grid. ", + "category": [ + "Array", + "Dynamic Programming", + "Matrix" + ], + "complexity": "Medium", + "successrate": 49.6, + "totalsubmissions": 36636, + "totalaccepted": 18158, + "likes": 492, + "dislikes": 82, + "hints": "For each square, know how many ones are up, left, down, and right of this square. You can find it in O(N^2) using dynamic programming. Now for each square ( O(N^3) ), we can evaluate whether that square is 1-bordered in O(1).", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "grid = [[1,1,1],[1,0,1],[1,1,1]]", + "expected_output": "9", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "grid = [[1,1,0,0]]", + "expected_output": "1", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d26", + "questionid": 603, + "title": "Sum of Nodes with Even-Valued Grandparent", + "slug": "sum-of-nodes-with-even-valued-grandparent", + "description": "Given the root of a binary tree, return the sum of values of nodes with an even-valued grandparent. If there are no nodes with an even-valued grandparent, return 0. A grandparent of a node is the parent of its parent if it exists. ", + "category": [ + "Tree", + "Depth-First Search", + "Breadth-First Search", + "Binary Tree" + ], + "complexity": "Medium", + "successrate": 85.2, + "totalsubmissions": 115315, + "totalaccepted": 98213, + "likes": 1697, + "dislikes": 56, + "hints": "Traverse the tree keeping the parent and the grandparent. If the grandparent of the current node is even-valued, add the value of this node to the answer.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [6,7,8,2,7,1,3,9,null,1,4,null,null,null,5]", + "expected_output": "18", + "explanation": "The red nodes are the nodes with even-value grandparent while the blue nodes are the even-value grandparents." + }, + { + "example_num": 2, + "expected_input": "root = [1]", + "expected_output": "0", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d28", + "questionid": 605, + "title": "Binary Tree Coloring Game", + "slug": "binary-tree-coloring-game", + "description": "Two players play a turn based game on a binary tree. We are given the root of this binary tree, and the number of nodes n in the tree. n is odd, and each node has a distinct value from 1 to n. Initially, the first player names a value x with 1 <= x <= n, and the second player names a value y with 1 <= y <= n and y != x. The first player colors the node with value x red, and the second player colors the node with value y blue. Then, the players take turns starting with the first player. In each turn, that player chooses a node of their color (red if player 1, blue if player 2) and colors an uncolored neighbor of the chosen node (either the left child, right child, or parent of the chosen node.) If (and only if) a player cannot choose such a node in this way, they must pass their turn. If both players pass their turn, the game ends, and the winner is the player that colored more nodes. You are the second player. If it is possible to choose such a y to ensure you win the game, return true. If it is not possible, return false. ", + "category": [ + "Tree", + "Depth-First Search", + "Binary Tree" + ], + "complexity": "Medium", + "successrate": 51.2, + "totalsubmissions": 67331, + "totalaccepted": 34450, + "likes": 940, + "dislikes": 172, + "hints": "The best move y must be immediately adjacent to x, since it locks out that subtree. Can you count each of (up to) 3 different subtrees neighboring x?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [1,2,3,4,5,6,7,8,9,10,11], n = 11, x = 3", + "expected_output": "true\nExplanation: The second player can choose the node with value 2.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "root = [1,2,3], n = 3, x = 1", + "expected_output": "false", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d2e", + "questionid": 611, + "title": "Swap For Longest Repeated Character Substring", + "slug": "swap-for-longest-repeated-character-substring", + "description": "You are given a string text. You can swap two of the characters in the text. Return the length of the longest substring with repeated characters. ", + "category": [ + "String", + "Sliding Window" + ], + "complexity": "Medium", + "successrate": 46.3, + "totalsubmissions": 48792, + "totalaccepted": 22568, + "likes": 694, + "dislikes": 63, + "hints": "There are two cases: a block of characters, or two blocks of characters between one different character. \r\n By keeping a run-length encoded version of the string, we can easily check these cases.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "text = "ababa"", + "expected_output": "3", + "explanation": "We can swap the first 'b' with the last 'a', or the last 'b' with the first 'a'. Then, the longest repeated character substring is "aaa" with length 3." + }, + { + "example_num": 2, + "expected_input": "text = "aaabaaa"", + "expected_output": "6", + "explanation": "Swap 'b' with the last 'a' (or the first 'a'), and we get longest repeated character substring "aaaaaa" with length 6." + }, + { + "example_num": 3, + "expected_input": "text = "aaaaa"", + "expected_output": "5", + "explanation": "No need to swap, longest repeated character substring is "aaaaa" with length is 5." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d30", + "questionid": 613, + "title": "Maximum Number of Words You Can Type", + "slug": "maximum-number-of-words-you-can-type", + "description": "There is a malfunctioning keyboard where some letter keys do not work. All other keys on the keyboard work properly. Given a string text of words separated by a single space (no leading or trailing spaces) and a string brokenLetters of all distinct letter keys that are broken, return the number of words in text you can fully type using this keyboard. ", + "category": [ + "Hash Table", + "String" + ], + "complexity": "Easy", + "successrate": 71.4, + "totalsubmissions": 39791, + "totalaccepted": 28416, + "likes": 273, + "dislikes": 13, + "hints": "Check each word separately if it can be typed. A word can be typed if all its letters are not broken.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "text = "hello world", brokenLetters = "ad"", + "expected_output": "1", + "explanation": "We cannot type "world" because the 'd' key is broken." + }, + { + "example_num": 2, + "expected_input": "text = "leet code", brokenLetters = "lt"", + "expected_output": "1", + "explanation": "We cannot type "leet" because the 'l' and 't' keys are broken." + }, + { + "example_num": 3, + "expected_input": "text = "leet code", brokenLetters = "e"", + "expected_output": "0", + "explanation": "We cannot type either word because the 'e' key is broken." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d33", + "questionid": 616, + "title": "Number of Days Between Two Dates", + "slug": "number-of-days-between-two-dates", + "description": "Write a program to count the number of days between two dates. The two dates are given as strings, their format is YYYY-MM-DD as shown in the examples. ", + "category": [ + "Math", + "String" + ], + "complexity": "Easy", + "successrate": 46.7, + "totalsubmissions": 61154, + "totalaccepted": 28582, + "likes": 184, + "dislikes": 802, + "hints": "Create a function f(date) that counts the number of days from 1900-01-01 to date. How can we calculate the answer ? The answer is just |f(date1) - f(date2)|. How to construct f(date) ? For each year from 1900 to year - 1 sum up 365 or 366 in case of leap years. Then sum up for each month the number of days, consider the case when the current year is leap, finally sum up the days.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "date1 = \"2019-06-29\", date2 = \"2019-06-30\"", + "expected_output": "1", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "date1 = \"2020-01-15\", date2 = \"2019-12-31\"", + "expected_output": "15", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d34", + "questionid": 617, + "title": "Validate Binary Tree Nodes", + "slug": "validate-binary-tree-nodes", + "description": "You have n binary tree nodes numbered from 0 to n - 1 where node i has two children leftChild[i] and rightChild[i], return true if and only if all the given nodes form exactly one valid binary tree. If node i has no left child then leftChild[i] will equal -1, similarly for the right child. Note that the nodes have no values and that we only use the node numbers in this problem. ", + "category": [ + "Tree", + "Depth-First Search", + "Breadth-First Search", + "Union Find", + "Graph", + "Binary Tree" + ], + "complexity": "Medium", + "successrate": 41.5, + "totalsubmissions": 82677, + "totalaccepted": 34281, + "likes": 742, + "dislikes": 247, + "hints": "Find the parent of each node. A valid tree must have nodes with only one parent and exactly one node with no parent.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 4, leftChild = [1,-1,3,-1], rightChild = [2,-1,-1,-1]", + "expected_output": "true", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "n = 4, leftChild = [1,-1,3,-1], rightChild = [2,3,-1,-1]", + "expected_output": "false", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "n = 2, leftChild = [1,0], rightChild = [-1,-1]", + "expected_output": "false", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d35", + "questionid": 618, + "title": "Closest Divisors", + "slug": "closest-divisors", + "description": "Given an integer num, find the closest two integers in absolute difference whose product equals num + 1 or num + 2. Return the two integers in any order. ", + "category": [ + "Math" + ], + "complexity": "Medium", + "successrate": 59.1, + "totalsubmissions": 26132, + "totalaccepted": 15456, + "likes": 186, + "dislikes": 81, + "hints": "Find the divisors of n+1 and n+2. To find the divisors of a number, you only need to iterate to the square root of that number.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "num = 8", + "expected_output": "[3,3]", + "explanation": "For num + 1 = 9, the closest divisors are 3 & 3, for num + 2 = 10, the closest divisors are 2 & 5, hence 3 & 3 is chosen." + }, + { + "example_num": 2, + "expected_input": "num = 123", + "expected_output": "[5,25]", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "num = 999", + "expected_output": "[40,25]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d36", + "questionid": 619, + "title": "Largest Multiple of Three", + "slug": "largest-multiple-of-three", + "description": "Given an array of digits digits, return the largest multiple of three that can be formed by concatenating some of the given digits in any order. If there is no answer return an empty string. Since the answer may not fit in an integer data type, return the answer as a string. Note that the returning answer must not contain unnecessary leading zeros. ", + "category": [ + "Array", + "Dynamic Programming", + "Greedy" + ], + "complexity": "Hard", + "successrate": 34.2, + "totalsubmissions": 39968, + "totalaccepted": 13666, + "likes": 390, + "dislikes": 55, + "hints": "A number is a multiple of three if and only if its sum of digits is a multiple of three. Use dynamic programming. To find the maximum number, try to maximize the number of digits of the number. Sort the digits in descending order to find the maximum number.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "digits = [8,1,9]", + "expected_output": ""981"", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "digits = [8,6,7,1,0]", + "expected_output": ""8760"", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "digits = [1]", + "expected_output": """", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d40", + "questionid": 629, + "title": "Reverse Substrings Between Each Pair of Parentheses", + "slug": "reverse-substrings-between-each-pair-of-parentheses", + "description": "You are given a string s that consists of lower case English letters and brackets. Reverse the strings in each pair of matching parentheses, starting from the innermost one. Your result should not contain any brackets. ", + "category": [ + "String", + "Stack" + ], + "complexity": "Medium", + "successrate": 65.7, + "totalsubmissions": 72801, + "totalaccepted": 47800, + "likes": 1269, + "dislikes": 34, + "hints": "Find all brackets in the string. Does the order of the reverse matter ? The order does not matter.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "(abcd)"", + "expected_output": ""dcba"", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "s = "(u(love)i)"", + "expected_output": ""iloveu"", + "explanation": "The substring "love" is reversed first, then the whole string is reversed." + }, + { + "example_num": 3, + "expected_input": "s = "(ed(et(oc))el)"", + "expected_output": ""leetcode"", + "explanation": "First, we reverse the substring "oc", then "etco", and finally, the whole string." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d42", + "questionid": 631, + "title": "Critical Connections in a Network", + "slug": "critical-connections-in-a-network", + "description": "There are n servers numbered from 0 to n - 1 connected by undirected server-to-server connections forming a network where connections[i] = [ai, bi] represents a connection between servers ai and bi. Any server can reach other servers directly or indirectly through the network. A critical connection is a connection that, if removed, will make some servers unable to reach some other server. Return all critical connections in the network in any order. ", + "category": [ + "Depth-First Search", + "Graph", + "Biconnected Component" + ], + "complexity": "Hard", + "successrate": 52, + "totalsubmissions": 278178, + "totalaccepted": 144789, + "likes": 3465, + "dislikes": 140, + "hints": "Use Tarjan's algorithm.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 4, connections = [[0,1],[1,2],[2,0],[1,3]]", + "expected_output": "[[1,3]]", + "explanation": "[[3,1]] is also accepted." + }, + { + "example_num": 2, + "expected_input": "n = 2, connections = [[0,1]]", + "expected_output": "[[0,1]]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d44", + "questionid": 633, + "title": "Number of Visible People in a Queue", + "slug": "number-of-visible-people-in-a-queue", + "description": "There are n people standing in a queue, and they numbered from 0 to n - 1 in left to right order. You are given an array heights of distinct integers where heights[i] represents the height of the ith person. A person can see another person to their right in the queue if everybody in between is shorter than both of them. More formally, the ith person can see the jth person if i < j and min(heights[i], heights[j]) > max(heights[i+1], heights[i+2], ..., heights[j-1]). Return an array answer of length n where answer[i] is the number of people the ith person can see to their right in the queue. ", + "category": [ + "Array", + "Stack", + "Monotonic Stack" + ], + "complexity": "Hard", + "successrate": 70.2, + "totalsubmissions": 25244, + "totalaccepted": 17721, + "likes": 742, + "dislikes": 14, + "hints": "How to solve this problem in quadratic complexity ? For every subarray start at index i, keep finding new maximum values until a value larger than arr[i] is found. Since the limits are high, you need a linear solution. Use a stack to keep the values of the array sorted as you iterate the array from the end to the start. Keep popping from the stack the elements in sorted order until a value larger than arr[i] is found, these are the ones that person i can see.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "heights = [10,6,8,5,11,9]", + "expected_output": "[3,1,2,1,1,0]", + "explanation": "Person 0 can see person 1, 2, and 4.\nPerson 1 can see person 2.\nPerson 2 can see person 3 and 4.\nPerson 3 can see person 4.\nPerson 4 can see person 5.\nPerson 5 can see no one since nobody is to the right of them." + }, + { + "example_num": 2, + "expected_input": "heights = [5,1,2,3,10]", + "expected_output": "[4,1,1,1,0]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d48", + "questionid": 637, + "title": "Largest Magic Square", + "slug": "largest-magic-square", + "description": "A k x k magic square is a k x k grid filled with integers such that every row sum, every column sum, and both diagonal sums are all equal. The integers in the magic square do not have to be distinct. Every 1 x 1 grid is trivially a magic square. Given an m x n integer grid, return the size (i.e., the side length k) of the largest magic square that can be found within this grid. ", + "category": [ + "Array", + "Matrix", + "Prefix Sum" + ], + "complexity": "Medium", + "successrate": 51.2, + "totalsubmissions": 14499, + "totalaccepted": 7426, + "likes": 186, + "dislikes": 199, + "hints": "Check all squares in the matrix and find the largest one.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "grid = [[7,1,4,5,6],[2,5,1,6,4],[1,5,4,3,2],[1,2,7,3,4]]", + "expected_output": "3", + "explanation": "The largest magic square has a size of 3.\nEvery row sum, column sum, and diagonal sum of this magic square is equal to 12.\n- Row sums: 5+1+6 = 5+4+3 = 2+7+3 = 12\n- Column sums: 5+5+2 = 1+4+7 = 6+3+3 = 12\n- Diagonal sums: 5+4+3 = 6+4+2 = 12" + }, + { + "example_num": 2, + "expected_input": "grid = [[5,1,3,1],[9,3,3,1],[1,3,3,8]]", + "expected_output": "2", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d49", + "questionid": 638, + "title": "Count Ways to Build Rooms in an Ant Colony", + "slug": "count-ways-to-build-rooms-in-an-ant-colony", + "description": "You are an ant tasked with adding n new rooms numbered 0 to n-1 to your colony. You are given the expansion plan as a 0-indexed integer array of length n, prevRoom, where prevRoom[i] indicates that you must build room prevRoom[i] before building room i, and these two rooms must be connected directly. Room 0 is already built, so prevRoom[0] = -1. The expansion plan is given such that once all the rooms are built, every room will be reachable from room 0. You can only build one room at a time, and you can travel freely between rooms you have already built only if they are connected. You can choose to build any room as long as its previous room is already built. Return the number of different orders you can build all the rooms in. Since the answer may be large, return it modulo 109 + 7. ", + "category": [ + "Math", + "Dynamic Programming", + "Tree", + "Graph", + "Topological Sort", + "Combinatorics" + ], + "complexity": "Hard", + "successrate": 48.2, + "totalsubmissions": 7427, + "totalaccepted": 3579, + "likes": 247, + "dislikes": 34, + "hints": "Use dynamic programming. Let dp[i] be the number of ways to solve the problem for the subtree of node i. Imagine you are trying to fill an array with the order of traversal, dp[i] equals the multiplications of the number of ways to distribute the subtrees of the children of i on the array using combinatorics, multiplied bu their dp values.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "prevRoom = [-1,0,1]", + "expected_output": "1", + "explanation": " There is only one way to build the additional rooms: 0 → 1 → 2" + }, + { + "example_num": 2, + "expected_input": "prevRoom = [-1,0,0,1,2]", + "expected_output": "6\r\nExplanation:\r\nThe 6 ways are:\r\n0 → 1 → 3 → 2 → 4\r\n0 → 2 → 4 → 1 → 3\r\n0 → 1 → 2 → 3 → 4\r\n0 → 1 → 2 → 4 → 3\r\n0 → 2 → 1 → 3 → 4\r\n0 → 2 → 1 → 4 → 3", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d0d", + "questionid": 578, + "title": "Occurrences After Bigram", + "slug": "occurrences-after-bigram", + "description": "Given two strings first and second, consider occurrences in some text of the form \"first second third\", where second comes immediately after first, and third comes immediately after second. Return an array of all the words third for each occurrence of \"first second third\". ", + "category": [ + "String" + ], + "complexity": "Easy", + "successrate": 64.2, + "totalsubmissions": 79598, + "totalaccepted": 51126, + "likes": 319, + "dislikes": 289, + "hints": "Split the string into words, then look at adjacent triples of words.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "text = \"alice is a good girl she is a good student\", first = \"a\", second = \"good\"", + "expected_output": "[\"girl\",\"student\"]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "text = \"we will we will rock you\", first = \"we\", second = \"will\"", + "expected_output": "[\"we\",\"rock\"]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d12", + "questionid": 583, + "title": "Shortest Common Supersequence ", + "slug": "shortest-common-supersequence", + "description": "Given two strings str1 and str2, return the shortest string that has both str1 and str2 as subsequences. If there are multiple valid strings, return any of them. A string s is a subsequence of string t if deleting some number of characters from t (possibly 0) results in the string s. ", + "category": [ + "String", + "Dynamic Programming" + ], + "complexity": "Hard", + "successrate": 55.9, + "totalsubmissions": 78404, + "totalaccepted": 43824, + "likes": 2133, + "dislikes": 41, + "hints": "We can find the length of the longest common subsequence between str1[i:] and str2[j:] (for all (i, j)) by using dynamic programming. We can use this information to recover the longest common supersequence.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "str1 = "abac", str2 = "cab"", + "expected_output": ""cabac"", + "explanation": "str1 = "abac" is a subsequence of "cabac" because we can delete the first "c".\nstr2 = "cab" is a subsequence of "cabac" because we can delete the last "ac".\nThe answer provided is the shortest such string that satisfies these properties." + }, + { + "example_num": 2, + "expected_input": "str1 = "aaaaaaaa", str2 = "aaaaaaaa"", + "expected_output": ""aaaaaaaa"", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d17", + "questionid": 588, + "title": "Corporate Flight Bookings", + "slug": "corporate-flight-bookings", + "description": "There are n flights that are labeled from 1 to n. You are given an array of flight bookings bookings, where bookings[i] = [firsti, lasti, seatsi] represents a booking for flights firsti through lasti (inclusive) with seatsi seats reserved for each flight in the range. Return an array answer of length n, where answer[i] is the total number of seats reserved for flight i. ", + "category": [ + "Array", + "Prefix Sum" + ], + "complexity": "Medium", + "successrate": 58.5, + "totalsubmissions": 65368, + "totalaccepted": 38231, + "likes": 1002, + "dislikes": 141, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "bookings = [[1,2,10],[2,3,20],[2,5,25]], n = 5", + "expected_output": "[10,55,45,25,25]", + "explanation": "Flight labels: 1 2 3 4 5\nBooking 1 reserved: 10 10\nBooking 2 reserved: 20 20\nBooking 3 reserved: 25 25 25 25\nTotal seats: 10 55 45 25 25\nHence, answer = [10,55,45,25,25]" + }, + { + "example_num": 2, + "expected_input": "bookings = [[1,2,10],[2,2,15]], n = 2", + "expected_output": "[10,25]", + "explanation": "Flight labels: 1 2\nBooking 1 reserved: 10 10\nBooking 2 reserved: 15\nTotal seats: 10 25\nHence, answer = [10,25]" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d19", + "questionid": 590, + "title": "Mean of Array After Removing Some Elements", + "slug": "mean-of-array-after-removing-some-elements", + "description": "Given an integer array arr, return the mean of the remaining integers after removing the smallest 5% and the largest 5% of the elements. Answers within 10-5 of the actual answer will be considered accepted. ", + "category": [ + "Array", + "Sorting" + ], + "complexity": "Easy", + "successrate": 64.6, + "totalsubmissions": 49041, + "totalaccepted": 31657, + "likes": 265, + "dislikes": 76, + "hints": "Sort the given array. Remove the first and last 5% of the sorted array.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "arr = [1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3]", + "expected_output": "2.00000", + "explanation": "After erasing the minimum and the maximum values of this array, all elements are equal to 2, so the mean is 2." + }, + { + "example_num": 2, + "expected_input": "arr = [6,2,7,5,1,2,0,3,10,2,5,0,5,5,0,8,7,6,8,0]", + "expected_output": "4.00000", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "arr = [6,0,7,0,7,5,7,8,3,4,0,7,8,1,6,8,1,1,2,4,8,1,9,5,4,3,8,5,10,8,6,6,1,0,6,10,8,2,3,4]", + "expected_output": "4.77778", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d1a", + "questionid": 591, + "title": "Sequential Digits", + "slug": "sequential-digits", + "description": "An integer has sequential digits if and only if each digit in the number is one more than the previous digit. Return a sorted list of all the integers in the range [low, high] inclusive that have sequential digits. ", + "category": [ + "Enumeration" + ], + "complexity": "Medium", + "successrate": 60.9, + "totalsubmissions": 124148, + "totalaccepted": 75563, + "likes": 1588, + "dislikes": 98, + "hints": "Generate all numbers with sequential digits and check if they are in the given range. Fix the starting digit then do a recursion that tries to append all valid digits.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "low = 100, high = 300", + "expected_output": "[123,234]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "low = 1000, high = 13000", + "expected_output": "[1234,2345,3456,4567,5678,6789,12345]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d1c", + "questionid": 593, + "title": "Longest Well-Performing Interval", + "slug": "longest-well-performing-interval", + "description": "We are given hours, a list of the number of hours worked per day for a given employee. A day is considered to be a tiring day if and only if the number of hours worked is (strictly) greater than 8. A well-performing interval is an interval of days for which the number of tiring days is strictly larger than the number of non-tiring days. Return the length of the longest well-performing interval. ", + "category": [ + "Array", + "Hash Table", + "Stack", + "Monotonic Stack", + "Prefix Sum" + ], + "complexity": "Medium", + "successrate": 34.2, + "totalsubmissions": 62835, + "totalaccepted": 21507, + "likes": 944, + "dislikes": 95, + "hints": "Make a new array A of +1/-1s corresponding to if hours[i] is > 8 or not. The goal is to find the longest subarray with positive sum. Using prefix sums (PrefixSum[i+1] = A[0] + A[1] + ... + A[i]), you need to find for each j, the smallest i < j with PrefixSum[i] + 1 == PrefixSum[j].", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "hours = [9,9,6,0,6,6,9]", + "expected_output": "3\nExplanation: The longest well-performing interval is [9,9,6].", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "hours = [6,6,6]", + "expected_output": "0", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d1f", + "questionid": 596, + "title": "Minimum Falling Path Sum II", + "slug": "minimum-falling-path-sum-ii", + "description": "Given an n x n integer matrix grid, return the minimum sum of a falling path with non-zero shifts. A falling path with non-zero shifts is a choice of exactly one element from each row of grid such that no two elements chosen in adjacent rows are in the same column. ", + "category": [ + "Array", + "Dynamic Programming", + "Matrix" + ], + "complexity": "Hard", + "successrate": 61.2, + "totalsubmissions": 44781, + "totalaccepted": 27426, + "likes": 761, + "dislikes": 65, + "hints": "Use dynamic programming. Let dp[i][j] be the answer for the first i rows such that column j is chosen from row i. Use the concept of cumulative array to optimize the complexity of the solution.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "grid = [[1,2,3],[4,5,6],[7,8,9]]", + "expected_output": "13", + "explanation": "The possible falling paths are:\n[1,5,9], [1,5,7], [1,6,7], [1,6,8],\n[2,4,8], [2,4,9], [2,6,7], [2,6,8],\n[3,4,8], [3,4,9], [3,5,7], [3,5,9]\nThe falling path with the smallest sum is [1,5,7], so the answer is 13." + }, + { + "example_num": 2, + "expected_input": "grid = [[7]]", + "expected_output": "7", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d2a", + "questionid": 607, + "title": "Break a Palindrome", + "slug": "break-a-palindrome", + "description": "Given a palindromic string of lowercase English letters palindrome, replace exactly one character with any lowercase English letter so that the resulting string is not a palindrome and that it is the lexicographically smallest one possible. Return the resulting string. If there is no way to replace a character to make it not a palindrome, return an empty string. A string a is lexicographically smaller than a string b (of the same length) if in the first position where a and b differ, a has a character strictly smaller than the corresponding character in b. For example, \"abcc\" is lexicographically smaller than \"abcd\" because the first position they differ is at the fourth character, and 'c' is smaller than 'd'. ", + "category": [ + "String", + "Greedy" + ], + "complexity": "Medium", + "successrate": 52.3, + "totalsubmissions": 129419, + "totalaccepted": 67722, + "likes": 730, + "dislikes": 433, + "hints": "How to detect if there is impossible to perform the replacement? Only when the length = 1. Change the first non 'a' character to 'a'. What if the string has only 'a'? Change the last character to 'b'.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "palindrome = "abccba"", + "expected_output": ""aaccba"", + "explanation": "There are many ways to make "abccba" not a palindrome, such as "zbccba", "aaccba", and "abacba".\nOf all the ways, "aaccba" is the lexicographically smallest." + }, + { + "example_num": 2, + "expected_input": "palindrome = "a"", + "expected_output": """", + "explanation": "There is no way to replace a single character to make "a" not a palindrome, so return an empty string." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d2c", + "questionid": 609, + "title": "Reverse Subarray To Maximize Array Value", + "slug": "reverse-subarray-to-maximize-array-value", + "description": "You are given an integer array nums. The value of this array is defined as the sum of |nums[i] - nums[i + 1]| for all 0 <= i < nums.length - 1. You are allowed to select any subarray of the given array and reverse it. You can perform this operation only once. Find maximum possible value of the final array. ", + "category": [ + "Array", + "Math", + "Greedy" + ], + "complexity": "Hard", + "successrate": 38.9, + "totalsubmissions": 9846, + "totalaccepted": 3833, + "likes": 330, + "dislikes": 34, + "hints": "What's the score after reversing a sub-array [L, R] ? It's the score without reversing it + abs(a[R] - a[L-1]) + abs(a[L] - a[R+1]) - abs(a[L] - a[L-1]) - abs(a[R] - a[R+1]) How to maximize that formula given that abs(x - y) = max(x - y, y - x) ? This can be written as max(max(a[R] - a[L - 1], a[L - 1] - a[R]) + max(a[R + 1] - a[L], a[L] - a[R + 1]) - value(L) - value(R + 1)) over all L < R where value(i) = abs(a[i] - a[i-1]) This can be divided into 4 cases.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [2,3,1,5,4]", + "expected_output": "10\nExplanation: By reversing the subarray [3,1,5] the array becomes [2,5,1,3,4] whose value is 10.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "nums = [2,4,9,24,2,1,10]", + "expected_output": "68", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d2f", + "questionid": 612, + "title": "Number of Dice Rolls With Target Sum", + "slug": "number-of-dice-rolls-with-target-sum", + "description": "You have n dice and each die has k faces numbered from 1 to k. Given three integers n, k, and target, return the number of possible ways (out of the kn total ways) to roll the dice so the sum of the face-up numbers equals target. Since the answer may be too large, return it modulo 109 + 7. ", + "category": [ + "Dynamic Programming" + ], + "complexity": "Medium", + "successrate": 47.7, + "totalsubmissions": 212292, + "totalaccepted": 101295, + "likes": 1942, + "dislikes": 85, + "hints": "Use dynamic programming. The states are how many dice are remaining, and what sum total you have rolled so far.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 1, k = 6, target = 3", + "expected_output": "1", + "explanation": "You throw one die with 6 faces.\nThere is only one way to get a sum of 3." + }, + { + "example_num": 2, + "expected_input": "n = 2, k = 6, target = 7", + "expected_output": "6", + "explanation": "You throw two dice, each with 6 faces.\nThere are 6 ways to get a sum of 7: 1+6, 2+5, 3+4, 4+3, 5+2, 6+1." + }, + { + "example_num": 3, + "expected_input": "n = 30, k = 30, target = 500", + "expected_output": "222616187", + "explanation": "The answer must be returned modulo 109 + 7." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d3a", + "questionid": 623, + "title": "Constrained Subsequence Sum", + "slug": "constrained-subsequence-sum", + "description": "Given an integer array nums and an integer k, return the maximum sum of a non-empty subsequence of that array such that for every two consecutive integers in the subsequence, nums[i] and nums[j], where i < j, the condition j - i <= k is satisfied. A subsequence of an array is obtained by deleting some number of elements (can be zero) from the array, leaving the remaining elements in their original order. ", + "category": [ + "Array", + "Dynamic Programming", + "Queue", + "Sliding Window", + "Heap (Priority Queue)", + "Monotonic Queue" + ], + "complexity": "Hard", + "successrate": 46.6, + "totalsubmissions": 38558, + "totalaccepted": 17955, + "likes": 770, + "dislikes": 31, + "hints": "Use dynamic programming. Let dp[i] be the solution for the prefix of the array that ends at index i, if the element at index i is in the subsequence. dp[i] = nums[i] + max(0, dp[i-k], dp[i-k+1], ..., dp[i-1]) Use a heap with the sliding window technique to optimize the dp.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [10,2,-10,5,20], k = 2", + "expected_output": "37\nExplanation: The subsequence is [10, 2, 5, 20].", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "nums = [-1,-2,-3], k = 1", + "expected_output": "-1\nExplanation: The subsequence must be non-empty, so we choose the largest number.", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "nums = [10,-2,-10,-5,20], k = 2", + "expected_output": "23\nExplanation: The subsequence is [10, -2, -5, 20].", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d3c", + "questionid": 625, + "title": "Maximum Subarray Sum with One Deletion", + "slug": "maximum-subarray-sum-with-one-deletion", + "description": "Given an array of integers, return the maximum sum for a non-empty subarray (contiguous elements) with at most one element deletion. In other words, you want to choose a subarray and optionally delete one element from it so that there is still at least one element left and the sum of the remaining elements is maximum possible. Note that the subarray needs to be non-empty after deleting one element. ", + "category": [ + "Array", + "Dynamic Programming" + ], + "complexity": "Medium", + "successrate": 40.6, + "totalsubmissions": 77540, + "totalaccepted": 31492, + "likes": 1222, + "dislikes": 42, + "hints": "How to solve this problem if no deletions are allowed ? Try deleting each element and find the maximum subarray sum to both sides of that element. To do that efficiently, use the idea of Kadane's algorithm.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "arr = [1,-2,0,3]", + "expected_output": "4\nExplanation: Because we can choose [1, -2, 0, 3] and drop -2, thus the subarray [1, 0, 3] becomes the maximum value.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "arr = [1,-2,-2,3]", + "expected_output": "3\nExplanation: We just choose [3] and it's the maximum sum.", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "arr = [-1,-1,-1,-1]", + "expected_output": "-1", + "explanation": " The final subarray needs to be non-empty. You can't choose [-1] and delete -1 from it, then get an empty subarray to make the sum equals to 0." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d3d", + "questionid": 626, + "title": "Day of the Week", + "slug": "day-of-the-week", + "description": "Given a date, return the corresponding day of the week for that date. The input is given as three integers representing the day, month and year respectively. Return the answer as one of the following values {\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\"}. ", + "category": [ + "Math" + ], + "complexity": "Easy", + "successrate": 58.4, + "totalsubmissions": 73088, + "totalaccepted": 42700, + "likes": 229, + "dislikes": 1875, + "hints": "Sum up the number of days for the years before the given year. Handle the case of a leap year. Find the number of days for each month of the given year.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "day = 31, month = 8, year = 2019", + "expected_output": ""Saturday"", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "day = 18, month = 7, year = 1999", + "expected_output": ""Sunday"", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "day = 15, month = 8, year = 1993", + "expected_output": ""Sunday"", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d47", + "questionid": 636, + "title": "Smallest String With Swaps", + "slug": "smallest-string-with-swaps", + "description": "You are given a string s, and an array of pairs of indices in the string pairs where pairs[i] = [a, b] indicates 2 indices(0-indexed) of the string. You can swap the characters at any pair of indices in the given pairs any number of times. Return the lexicographically smallest string that s can be changed to after using the swaps. ", + "category": [ + "Hash Table", + "String", + "Depth-First Search", + "Breadth-First Search", + "Union Find" + ], + "complexity": "Medium", + "successrate": 52.7, + "totalsubmissions": 87654, + "totalaccepted": 46225, + "likes": 1506, + "dislikes": 51, + "hints": "Think of it as a graph problem. Consider the pairs as connected nodes in the graph, what can you do with a connected component of indices ? We can sort each connected component alone to get the lexicographically minimum string.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "dcab", pairs = [[0,3],[1,2]]", + "expected_output": ""bacd"\nExplaination: \nSwap s[0] and s[3], s = "bcad"\nSwap s[1] and s[2], s = "bacd"", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "s = "dcab", pairs = [[0,3],[1,2],[0,2]]", + "expected_output": ""abcd"\nExplaination: \nSwap s[0] and s[3], s = "bcad"\nSwap s[0] and s[2], s = "acbd"\nSwap s[1] and s[2], s = "abcd"", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "s = "cba", pairs = [[0,1],[1,2]]", + "expected_output": ""abc"\nExplaination: \nSwap s[0] and s[1], s = "bca"\nSwap s[1] and s[2], s = "bac"\nSwap s[0] and s[1], s = "abc"", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d4b", + "questionid": 640, + "title": "Remove All Adjacent Duplicates in String II", + "slug": "remove-all-adjacent-duplicates-in-string-ii", + "description": "You are given a string s and an integer k, a k duplicate removal consists of choosing k adjacent and equal letters from s and removing them, causing the left and the right side of the deleted substring to concatenate together. We repeatedly make k duplicate removals on s until we no longer can. Return the final string after all such duplicate removals have been made. It is guaranteed that the answer is unique. ", + "category": [ + "String", + "Stack" + ], + "complexity": "Medium", + "successrate": 56, + "totalsubmissions": 279451, + "totalaccepted": 156418, + "likes": 2575, + "dislikes": 49, + "hints": "Use a stack to store the characters, when there are k same characters, delete them. To make it more efficient, use a pair to store the value and the count of each character.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "abcd", k = 2", + "expected_output": ""abcd"\nExplanation: There's nothing to delete.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "s = "deeedbbcccbdaa", k = 3", + "expected_output": ""aa"\nExplanation: \nFirst delete "eee" and "ccc", get "ddbbbdaa"\nThen delete "bbb", get "dddaa"\nFinally delete "ddd", get "aa"", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "s = "pbbcggttciiippooaais", k = 2", + "expected_output": ""ps"", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d0c", + "questionid": 577, + "title": "Flip Columns For Maximum Number of Equal Rows", + "slug": "flip-columns-for-maximum-number-of-equal-rows", + "description": "You are given an m x n binary matrix matrix. You can choose any number of columns in the matrix and flip every cell in that column (i.e., Change the value of the cell from 0 to 1 or vice versa). Return the maximum number of rows that have all values equal after some number of flips. ", + "category": [ + "Array", + "Hash Table", + "Matrix" + ], + "complexity": "Medium", + "successrate": 63.1, + "totalsubmissions": 26409, + "totalaccepted": 16653, + "likes": 523, + "dislikes": 36, + "hints": "Flipping a subset of columns is like doing a bitwise XOR of some number K onto each row. We want rows X with X ^ K = all 0s or all 1s. This is the same as X = X^K ^K = (all 0s or all 1s) ^ K, so we want to count rows that have opposite bits set. For example, if K = 1, then we count rows X = (00000...001, or 1111....110).", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "matrix = [[0,1],[1,1]]", + "expected_output": "1", + "explanation": "After flipping no values, 1 row has all values equal." + }, + { + "example_num": 2, + "expected_input": "matrix = [[0,1],[1,0]]", + "expected_output": "2", + "explanation": "After flipping values in the first column, both rows have equal values." + }, + { + "example_num": 3, + "expected_input": "matrix = [[0,0,0],[0,0,1],[1,1,0]]", + "expected_output": "2", + "explanation": "After flipping values in the first two columns, the last two rows have equal values." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d0e", + "questionid": 579, + "title": "Insufficient Nodes in Root to Leaf Paths", + "slug": "insufficient-nodes-in-root-to-leaf-paths", + "description": "Given the root of a binary tree and an integer limit, delete all insufficient nodes in the tree simultaneously, and return the root of the resulting binary tree. A node is insufficient if every root to leaf path intersecting this node has a sum strictly less than limit. A leaf is a node with no children. ", + "category": [ + "Tree", + "Depth-First Search", + "Binary Tree" + ], + "complexity": "Medium", + "successrate": 51.9, + "totalsubmissions": 48380, + "totalaccepted": 25100, + "likes": 407, + "dislikes": 547, + "hints": "Consider a DFS traversal of the tree. You can keep track of the current path sum from root to this node, and you can also use DFS to return the minimum value of any path from this node to the leaf. This will tell you if this node is insufficient.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [1,2,3,4,-99,-99,7,8,9,-99,-99,12,13,-99,14], limit = 1", + "expected_output": "[1,2,3,4,null,null,7,8,9,null,14]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "root = [5,4,8,11,null,17,4,7,1,null,null,5,3], limit = 22", + "expected_output": "[5,4,8,11,null,17,4,7,null,null,null,5]", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "root = [1,2,-3,-5,null,4,null], limit = -1", + "expected_output": "[1,null,-3,4]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d10", + "questionid": 581, + "title": "Letter Tile Possibilities", + "slug": "letter-tile-possibilities", + "description": "You have n  tiles, where each tile has one letter tiles[i] printed on it. Return the number of possible non-empty sequences of letters you can make using the letters printed on those tiles. ", + "category": [ + "String", + "Backtracking" + ], + "complexity": "Medium", + "successrate": 76.2, + "totalsubmissions": 87888, + "totalaccepted": 66986, + "likes": 1609, + "dislikes": 46, + "hints": "Try to build the string with a backtracking DFS by considering what you can put in every position.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "tiles = "AAB"", + "expected_output": "8\nExplanation: The possible sequences are "A", "B", "AA", "AB", "BA", "AAB", "ABA", "BAA".", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "tiles = "AAABBC"", + "expected_output": "188", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "tiles = "V"", + "expected_output": "1", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d1b", + "questionid": 592, + "title": "Relative Sort Array", + "slug": "relative-sort-array", + "description": "Given two arrays arr1 and arr2, the elements of arr2 are distinct, and all elements in arr2 are also in arr1. Sort the elements of arr1 such that the relative ordering of items in arr1 are the same as in arr2. Elements that do not appear in arr2 should be placed at the end of arr1 in ascending order. ", + "category": [ + "Array", + "Hash Table", + "Sorting", + "Counting Sort" + ], + "complexity": "Easy", + "successrate": 68.2, + "totalsubmissions": 180859, + "totalaccepted": 123303, + "likes": 1635, + "dislikes": 98, + "hints": "Using a hashmap, we can map the values of arr2 to their position in arr2. After, we can use a custom sorting function.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "arr1 = [2,3,1,3,2,4,6,7,9,2,19], arr2 = [2,1,4,3,9,6]", + "expected_output": "[2,2,2,1,4,3,3,9,6,7,19]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "arr1 = [28,6,22,8,44,17], arr2 = [22,28,8,6]", + "expected_output": "[22,28,8,6,17,44]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d1e", + "questionid": 595, + "title": "Remove Covered Intervals", + "slug": "remove-covered-intervals", + "description": "Given an array intervals where intervals[i] = [li, ri] represent the interval [li, ri), remove all intervals that are covered by another interval in the list. The interval [a, b) is covered by the interval [c, d) if and only if c <= a and b <= d. Return the number of remaining intervals. ", + "category": [ + "Array", + "Sorting" + ], + "complexity": "Medium", + "successrate": 57.4, + "totalsubmissions": 166495, + "totalaccepted": 95595, + "likes": 1851, + "dislikes": 44, + "hints": "How to check if an interval is covered by another? Compare each interval to all others and check if it is covered by any interval.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "intervals = [[1,4],[3,6],[2,8]]", + "expected_output": "2", + "explanation": "Interval [3,6] is covered by [2,8], therefore it is removed." + }, + { + "example_num": 2, + "expected_input": "intervals = [[1,4],[2,3]]", + "expected_output": "1", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d20", + "questionid": 597, + "title": "Number of Equivalent Domino Pairs", + "slug": "number-of-equivalent-domino-pairs", + "description": "Given a list of dominoes, dominoes[i] = [a, b] is equivalent to dominoes[j] = [c, d] if and only if either (a == c and b == d), or (a == d and b == c) - that is, one domino can be rotated to be equal to another domino. Return the number of pairs (i, j) for which 0 <= i < j < dominoes.length, and dominoes[i] is equivalent to dominoes[j]. ", + "category": [ + "Array", + "Hash Table", + "Counting" + ], + "complexity": "Easy", + "successrate": 46.3, + "totalsubmissions": 100715, + "totalaccepted": 46607, + "likes": 476, + "dislikes": 230, + "hints": "For each domino j, find the number of dominoes you've already seen (dominoes i with i < j) that are equivalent. You can keep track of what you've seen using a hashmap.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "dominoes = [[1,2],[2,1],[3,4],[5,6]]", + "expected_output": "1", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "dominoes = [[1,2],[1,2],[1,1],[1,2],[2,2]]", + "expected_output": "3", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d21", + "questionid": 598, + "title": "Replace Elements with Greatest Element on Right Side", + "slug": "replace-elements-with-greatest-element-on-right-side", + "description": "Given an array arr, replace every element in that array with the greatest element among the elements to its right, and replace the last element with -1. After doing so, return the array. ", + "category": [ + "Array" + ], + "complexity": "Easy", + "successrate": 74.5, + "totalsubmissions": 270455, + "totalaccepted": 201365, + "likes": 1208, + "dislikes": 164, + "hints": "Loop through the array starting from the end. Keep the maximum value seen so far.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "arr = [17,18,5,4,6,1]", + "expected_output": "[18,6,6,6,1,-1]", + "explanation": "- index 0 --> the greatest element to the right of index 0 is index 1 (18).\n- index 1 --> the greatest element to the right of index 1 is index 4 (6).\n- index 2 --> the greatest element to the right of index 2 is index 4 (6).\n- index 3 --> the greatest element to the right of index 3 is index 4 (6).\n- index 4 --> the greatest element to the right of index 4 is index 5 (1).\n- index 5 --> there are no elements to the right of index 5, so we put -1." + }, + { + "example_num": 2, + "expected_input": "arr = [400]", + "expected_output": "[-1]", + "explanation": "There are no elements to the right of index 0." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d24", + "questionid": 601, + "title": "Stone Game II", + "slug": "stone-game-ii", + "description": "Alice and Bob continue their games with piles of stones.  There are a number of piles arranged in a row, and each pile has a positive integer number of stones piles[i].  The objective of the game is to end with the most stones. Alice and Bob take turns, with Alice starting first.  Initially, M = 1. On each player's turn, that player can take all the stones in the first X remaining piles, where 1 <= X <= 2M.  Then, we set M = max(M, X). The game continues until all the stones have been taken. Assuming Alice and Bob play optimally, return the maximum number of stones Alice can get. ", + "category": [ + "Array", + "Math", + "Dynamic Programming", + "Game Theory" + ], + "complexity": "Medium", + "successrate": 64.9, + "totalsubmissions": 59817, + "totalaccepted": 38833, + "likes": 1293, + "dislikes": 251, + "hints": "Use dynamic programming: the states are (i, m) for the answer of piles[i:] and that given m.", + "deleted": false, + "examples": [] + }, + { + "_id": "66f925ddfdfb8e1665720d25", + "questionid": 602, + "title": "Decompress Run-Length Encoded List", + "slug": "decompress-run-length-encoded-list", + "description": "We are given a list nums of integers representing a list compressed with run-length encoding. Consider each adjacent pair of elements [freq, val] = [nums[2*i], nums[2*i+1]] (with i >= 0).  For each such pair, there are freq elements with value val concatenated in a sublist. Concatenate all the sublists from left to right to generate the decompressed list. Return the decompressed list. ", + "category": [ + "Array" + ], + "complexity": "Easy", + "successrate": 85.9, + "totalsubmissions": 206085, + "totalaccepted": 176994, + "likes": 730, + "dislikes": 1063, + "hints": "Decompress the given array by repeating nums[2*i+1] a number of times equal to nums[2*i].", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,2,3,4]", + "expected_output": "[2,4,4,4]", + "explanation": "The first pair [1,2] means we have freq = 1 and val = 2 so we generate the array [2].\nThe second pair [3,4] means we have freq = 3 and val = 4 so we generate [4,4,4].\nAt the end the concatenation [2] + [4,4,4] is [2,4,4,4]." + }, + { + "example_num": 2, + "expected_input": "nums = [1,1,2,3]", + "expected_output": "[1,3,3]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d29", + "questionid": 606, + "title": "Longest Common Subsequence", + "slug": "longest-common-subsequence", + "description": "Given two strings text1 and text2, return the length of their longest common subsequence. If there is no common subsequence, return 0. A subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters. A common subsequence of two strings is a subsequence that is common to both strings. ", + "category": [ + "String", + "Dynamic Programming" + ], + "complexity": "Medium", + "successrate": 58.9, + "totalsubmissions": 666769, + "totalaccepted": 392632, + "likes": 6213, + "dislikes": 70, + "hints": "Try dynamic programming. \r\nDP[i][j] represents the longest common subsequence of text1[0 ... i] & text2[0 ... j]. DP[i][j] = DP[i - 1][j - 1] + 1 , if text1[i] == text2[j]\r\nDP[i][j] = max(DP[i - 1][j], DP[i][j - 1]) , otherwise", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "text1 = "abcde", text2 = "ace"", + "expected_output": "3", + "explanation": "The longest common subsequence is "ace" and its length is 3." + }, + { + "example_num": 2, + "expected_input": "text1 = "abc", text2 = "abc"", + "expected_output": "3", + "explanation": "The longest common subsequence is "abc" and its length is 3." + }, + { + "example_num": 3, + "expected_input": "text1 = "abc", text2 = "def"", + "expected_output": "0", + "explanation": "There is no such common subsequence, so the result is 0." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d38", + "questionid": 621, + "title": "Four Divisors", + "slug": "four-divisors", + "description": "Given an integer array nums, return the sum of divisors of the integers in that array that have exactly four divisors. If there is no such integer in the array, return 0. ", + "category": [ + "Array", + "Math" + ], + "complexity": "Medium", + "successrate": 40.8, + "totalsubmissions": 49183, + "totalaccepted": 20060, + "likes": 201, + "dislikes": 146, + "hints": "Find the divisors of each element in the array. You only need to loop to the square root of a number to find its divisors.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [21,4,7]", + "expected_output": "32", + "explanation": "21 has 4 divisors: 1, 3, 7, 21\n4 has 3 divisors: 1, 2, 4\n7 has 2 divisors: 1, 7\nThe answer is the sum of divisors of 21 only." + }, + { + "example_num": 2, + "expected_input": "nums = [21,21]", + "expected_output": "64", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "nums = [1,2,3,4,5]", + "expected_output": "0", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d3e", + "questionid": 627, + "title": "Make Array Strictly Increasing", + "slug": "make-array-strictly-increasing", + "description": "Given two integer arrays arr1 and arr2, return the minimum number of operations (possibly zero) needed to make arr1 strictly increasing. In one operation, you can choose two indices 0 <= i < arr1.length and 0 <= j < arr2.length and do the assignment arr1[i] = arr2[j]. If there is no way to make arr1 strictly increasing, return -1. ", + "category": [ + "Array", + "Binary Search", + "Dynamic Programming" + ], + "complexity": "Hard", + "successrate": 44.4, + "totalsubmissions": 25430, + "totalaccepted": 11302, + "likes": 595, + "dislikes": 16, + "hints": "Use dynamic programming. The state would be the index in arr1 and the index of the previous element in arr2 after sorting it and removing duplicates.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "arr1 = [1,5,3,6,7], arr2 = [1,3,2,4]", + "expected_output": "1", + "explanation": "Replace 5 with 2, then arr1 = [1, 2, 3, 6, 7]." + }, + { + "example_num": 2, + "expected_input": "arr1 = [1,5,3,6,7], arr2 = [4,3,1]", + "expected_output": "2", + "explanation": "Replace 5 with 3 and then replace 3 with 4. arr1 = [1, 3, 4, 6, 7]." + }, + { + "example_num": 3, + "expected_input": "arr1 = [1,5,3,6,7], arr2 = [1,6,3,3]", + "expected_output": "-1", + "explanation": "You can't make arr1 strictly increasing." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d45", + "questionid": 634, + "title": "Minimum Absolute Difference", + "slug": "minimum-absolute-difference", + "description": "Given an array of distinct integers arr, find all pairs of elements with the minimum absolute difference of any two elements. Return a list of pairs in ascending order(with respect to pairs), each pair [a, b] follows ", + "category": [ + "Array", + "Sorting" + ], + "complexity": "Easy", + "successrate": 69.8, + "totalsubmissions": 170198, + "totalaccepted": 118863, + "likes": 1465, + "dislikes": 58, + "hints": "Find the minimum absolute difference between two elements in the array. The minimum absolute difference must be a difference between two consecutive elements in the sorted array.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "arr = [4,2,1,3]", + "expected_output": "[[1,2],[2,3],[3,4]]\nExplanation: The minimum absolute difference is 1. List all pairs with difference equal to 1 in ascending order.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "arr = [1,3,6,10,15]", + "expected_output": "[[1,3]]", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "arr = [3,8,-10,23,19,-4,-14,27]", + "expected_output": "[[-14,-10],[19,23],[23,27]]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d13", + "questionid": 584, + "title": "Car Pooling", + "slug": "car-pooling", + "description": "There is a car with capacity empty seats. The vehicle only drives east (i.e., it cannot turn around and drive west). You are given the integer capacity and an array trips where trips[i] = [numPassengersi, fromi, toi] indicates that the ith trip has numPassengersi passengers and the locations to pick them up and drop them off are fromi and toi respectively. The locations are given as the number of kilometers due east from the car's initial location. Return true if it is possible to pick up and drop off all passengers for all the given trips, or false otherwise. ", + "category": [ + "Array", + "Sorting", + "Heap (Priority Queue)", + "Simulation", + "Prefix Sum" + ], + "complexity": "Medium", + "successrate": 58.3, + "totalsubmissions": 257410, + "totalaccepted": 149966, + "likes": 3080, + "dislikes": 66, + "hints": "Sort the pickup and dropoff events by location, then process them in order.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "trips = [[2,1,5],[3,3,7]], capacity = 4", + "expected_output": "false", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "trips = [[2,1,5],[3,3,7]], capacity = 5", + "expected_output": "true", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d15", + "questionid": 586, + "title": "Filling Bookcase Shelves", + "slug": "filling-bookcase-shelves", + "description": "You are given an array books where books[i] = [thicknessi, heighti] indicates the thickness and height of the ith book. You are also given an integer shelfWidth. We want to place these books in order onto bookcase shelves that have a total width shelfWidth. We choose some of the books to place on this shelf such that the sum of their thickness is less than or equal to shelfWidth, then build another level of the shelf of the bookcase so that the total height of the bookcase has increased by the maximum height of the books we just put down. We repeat this process until there are no more books to place. Note that at each step of the above process, the order of the books we place is the same order as the given sequence of books. Return the minimum possible height that the total bookshelf can be after placing shelves in this manner. ", + "category": [ + "Array", + "Dynamic Programming" + ], + "complexity": "Medium", + "successrate": 58.2, + "totalsubmissions": 55901, + "totalaccepted": 32512, + "likes": 1234, + "dislikes": 75, + "hints": "Use dynamic programming: dp(i) will be the answer to the problem for books[i:].", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "books = [[1,1],[2,3],[2,3],[1,1],[1,1],[1,1],[1,2]], shelfWidth = 4", + "expected_output": "6", + "explanation": "The sum of the heights of the 3 shelves is 1 + 3 + 2 = 6.\nNotice that book number 2 does not have to be on the first shelf." + }, + { + "example_num": 2, + "expected_input": "books = [[1,3],[2,4],[3,2]], shelfWidth = 6", + "expected_output": "4", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d18", + "questionid": 589, + "title": "Delete Nodes And Return Forest", + "slug": "delete-nodes-and-return-forest", + "description": "Given the root of a binary tree, each node in the tree has a distinct value. After deleting all nodes with a value in to_delete, we are left with a forest (a disjoint union of trees). Return the roots of the trees in the remaining forest. You may return the result in any order. ", + "category": [ + "Tree", + "Depth-First Search", + "Binary Tree" + ], + "complexity": "Medium", + "successrate": 69.3, + "totalsubmissions": 224073, + "totalaccepted": 155220, + "likes": 2775, + "dislikes": 80, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [1,2,3,4,5,6,7], to_delete = [3,5]", + "expected_output": "[[1,2,null,4],[6],[7]]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "root = [1,2,4,null,3], to_delete = [3]", + "expected_output": "[[1,2,4]]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d27", + "questionid": 604, + "title": "Distinct Echo Substrings", + "slug": "distinct-echo-substrings", + "description": "Return the number of distinct non-empty substrings of text that can be written as the concatenation of some string with itself (i.e. it can be written as a + a where a is some string). ", + "category": [ + "String", + "Dynamic Programming", + "Trie", + "Sliding Window", + "Rolling Hash", + "Hash Function" + ], + "complexity": "Hard", + "successrate": 49.9, + "totalsubmissions": 22844, + "totalaccepted": 11399, + "likes": 181, + "dislikes": 169, + "hints": "Given a substring of the text, how to check if it can be written as the concatenation of a string with itself ? We can do that in linear time, a faster way is to use hashing. Try all substrings and use hashing to check them.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "text = "abcabcabc"", + "expected_output": "3\nExplanation: The 3 substrings are "abcabc", "bcabca" and "cabcab".", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "text = "leetcodeleetcode"", + "expected_output": "2\nExplanation: The 2 substrings are "ee" and "leetcodeleetcode".", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d2b", + "questionid": 608, + "title": "Sort the Matrix Diagonally", + "slug": "sort-the-matrix-diagonally", + "description": "A matrix diagonal is a diagonal line of cells starting from some cell in either the topmost row or leftmost column and going in the bottom-right direction until reaching the matrix's end. For example, the matrix diagonal starting from mat[2][0], where mat is a 6 x 3 matrix, includes cells mat[2][0], mat[3][1], and mat[4][2]. Given an m x n matrix mat of integers, sort each matrix diagonal in ascending order and return the resulting matrix. ", + "category": [ + "Array", + "Sorting", + "Matrix" + ], + "complexity": "Medium", + "successrate": 81.3, + "totalsubmissions": 101810, + "totalaccepted": 82802, + "likes": 1599, + "dislikes": 176, + "hints": "Use a data structure to store all values of each diagonal. How to index the data structure with the id of the diagonal? All cells in the same diagonal (i,j) have the same difference so we can get the diagonal of a cell using the difference i-j.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "mat = [[3,3,1,1],[2,2,1,2],[1,1,1,2]]", + "expected_output": "[[1,1,1,1],[1,2,2,2],[1,2,3,3]]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "mat = [[11,25,66,1,69,7],[23,55,17,45,15,52],[75,31,36,44,58,8],[22,27,33,25,68,4],[84,28,14,11,5,50]]", + "expected_output": "[[5,17,4,1,52,7],[11,11,25,45,8,69],[14,23,25,44,58,15],[22,27,31,36,50,66],[84,28,75,33,55,68]]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d2d", + "questionid": 610, + "title": "Day of the Year", + "slug": "day-of-the-year", + "description": "Given a string date representing a Gregorian calendar date formatted as YYYY-MM-DD, return the day number of the year. ", + "category": [ + "Math", + "String" + ], + "complexity": "Easy", + "successrate": 50.9, + "totalsubmissions": 64176, + "totalaccepted": 32690, + "likes": 240, + "dislikes": 303, + "hints": "Have a integer array of how many days there are per month. February gets one extra day if its a leap year. Then, we can manually count the ordinal as day + (number of days in months before this one).", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "date = "2019-01-09"", + "expected_output": "9", + "explanation": "Given date is the 9th day of the year in 2019." + }, + { + "example_num": 2, + "expected_input": "date = "2019-02-10"", + "expected_output": "41", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d31", + "questionid": 614, + "title": "Remove Zero Sum Consecutive Nodes from Linked List", + "slug": "remove-zero-sum-consecutive-nodes-from-linked-list", + "description": "Given the head of a linked list, we repeatedly delete consecutive sequences of nodes that sum to 0 until there are no such sequences. After doing so, return the head of the final linked list.  You may return any such answer. (Note that in the examples below, all sequences are serializations of ListNode objects.)", + "category": [ + "Hash Table", + "Linked List" + ], + "complexity": "Medium", + "successrate": 42.6, + "totalsubmissions": 82720, + "totalaccepted": 35212, + "likes": 1389, + "dislikes": 71, + "hints": "Convert the linked list into an array. While you can find a non-empty subarray with sum = 0, erase it. Convert the array into a linked list.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "head = [1,2,-3,3,1]", + "expected_output": "[3,1]\nNote: The answer [1,2,1] would also be accepted.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "head = [1,2,3,-3,4]", + "expected_output": "[1,2,4]", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "head = [1,2,3,-3,-2]", + "expected_output": "[1]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d32", + "questionid": 615, + "title": "Compare Strings by Frequency of the Smallest Character", + "slug": "compare-strings-by-frequency-of-the-smallest-character", + "description": "Let the function f(s) be the frequency of the lexicographically smallest character in a non-empty string s. For example, if s = \"dcce\" then f(s) = 2 because the lexicographically smallest character is 'c', which has a frequency of 2. You are given an array of strings words and another array of query strings queries. For each query queries[i], count the number of words in words such that f(queries[i]) < f(W) for each W in words. Return an integer array answer, where each answer[i] is the answer to the ith query. ", + "category": [ + "Array", + "Hash Table", + "String", + "Binary Search", + "Sorting" + ], + "complexity": "Medium", + "successrate": 61.1, + "totalsubmissions": 106244, + "totalaccepted": 64885, + "likes": 492, + "dislikes": 888, + "hints": "For each string from words calculate the leading count and store it in an array, then sort the integer array. For each string from queries calculate the leading count \"p\" and in base of the sorted array calculated on the step 1 do a binary search to count the number of items greater than \"p\".", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "queries = ["cbd"], words = ["zaaaz"]", + "expected_output": "[1]", + "explanation": "On the first query we have f("cbd") = 1, f("zaaaz") = 3 so f("cbd") < f("zaaaz")." + }, + { + "example_num": 2, + "expected_input": "queries = ["bbb","cc"], words = ["a","aa","aaa","aaaa"]", + "expected_output": "[1,2]", + "explanation": "On the first query only f("bbb") < f("aaaa"). On the second query both f("aaa") and f("aaaa") are both > f("cc")." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d37", + "questionid": 620, + "title": "Prime Arrangements", + "slug": "prime-arrangements", + "description": "Return the number of permutations of 1 to n so that prime numbers are at prime indices (1-indexed.) (Recall that an integer is prime if and only if it is greater than 1, and cannot be written as a product of two positive integers both smaller than it.) Since the answer may be large, return the answer modulo 10^9 + 7. ", + "category": [ + "Math" + ], + "complexity": "Easy", + "successrate": 52.8, + "totalsubmissions": 37583, + "totalaccepted": 19850, + "likes": 243, + "dislikes": 352, + "hints": "Solve the problem for prime numbers and composite numbers separately. Multiply the number of permutations of prime numbers over prime indices with the number of permutations of composite numbers over composite indices. The number of permutations equals the factorial.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 5", + "expected_output": "12", + "explanation": "For example [1,2,5,4,3] is a valid permutation, but [5,2,3,4,1] is not because the prime number 5 is at index 1." + }, + { + "example_num": 2, + "expected_input": "n = 100", + "expected_output": "682289015", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d39", + "questionid": 622, + "title": "Balance a Binary Search Tree", + "slug": "balance-a-binary-search-tree", + "description": "Given the root of a binary search tree, return a balanced binary search tree with the same node values. If there is more than one answer, return any of them. A binary search tree is balanced if the depth of the two subtrees of every node never differs by more than 1. ", + "category": [ + "Divide and Conquer", + "Greedy", + "Tree", + "Depth-First Search", + "Binary Search Tree", + "Binary Tree" + ], + "complexity": "Medium", + "successrate": 80.3, + "totalsubmissions": 111866, + "totalaccepted": 89848, + "likes": 1762, + "dislikes": 56, + "hints": "Convert the tree to a sorted array using an in-order traversal. Construct a new balanced tree from the sorted array recursively.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [1,null,2,null,3,null,4,null,null]", + "expected_output": "[2,1,3,null,null,null,4]\nExplanation: This is not the only correct answer, [3,1,4,null,2] is also correct.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "root = [2,1,3]", + "expected_output": "[2,1,3]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d3b", + "questionid": 624, + "title": "Distance Between Bus Stops", + "slug": "distance-between-bus-stops", + "description": "A bus has n stops numbered from 0 to n - 1 that form a circle. We know the distance between all pairs of neighboring stops where distance[i] is the distance between the stops number i and (i + 1) % n. The bus goes along both directions i.e. clockwise and counterclockwise. Return the shortest distance between the given start and destination stops. ", + "category": [ + "Array" + ], + "complexity": "Easy", + "successrate": 54, + "totalsubmissions": 76073, + "totalaccepted": 41117, + "likes": 512, + "dislikes": 58, + "hints": "Find the distance between the two stops if the bus moved in clockwise or counterclockwise directions.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "distance = [1,2,3,4], start = 0, destination = 1", + "expected_output": "1", + "explanation": "Distance between 0 and 1 is 1 or 9, minimum is 1." + }, + { + "example_num": 2, + "expected_input": "distance = [1,2,3,4], start = 0, destination = 2", + "expected_output": "3", + "explanation": "Distance between 0 and 2 is 3 or 7, minimum is 3." + }, + { + "example_num": 3, + "expected_input": "distance = [1,2,3,4], start = 0, destination = 3", + "expected_output": "4", + "explanation": "Distance between 0 and 3 is 6 or 4, minimum is 4." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d3f", + "questionid": 628, + "title": "Maximum Number of Balloons", + "slug": "maximum-number-of-balloons", + "description": "Given a string text, you want to use the characters of text to form as many instances of the word \"balloon\" as possible. You can use each character in text at most once. Return the maximum number of instances that can be formed. ", + "category": [ + "Hash Table", + "String", + "Counting" + ], + "complexity": "Easy", + "successrate": 62.5, + "totalsubmissions": 175531, + "totalaccepted": 109751, + "likes": 1002, + "dislikes": 68, + "hints": "Count the frequency of letters in the given string. Find the letter than can make the minimum number of instances of the word \"balloon\".", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "text = "nlaebolko"", + "expected_output": "1", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "text = "loonbalxballpoon"", + "expected_output": "2", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "text = "leetcode"", + "expected_output": "0", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d41", + "questionid": 630, + "title": "K-Concatenation Maximum Sum", + "slug": "k-concatenation-maximum-sum", + "description": "Given an integer array arr and an integer k, modify the array by repeating it k times. For example, if arr = [1, 2] and k = 3 then the modified array will be [1, 2, 1, 2, 1, 2]. Return the maximum sub-array sum in the modified array. Note that the length of the sub-array can be 0 and its sum in that case is 0. As the answer can be very large, return the answer modulo 109 + 7. ", + "category": [ + "Array", + "Dynamic Programming" + ], + "complexity": "Medium", + "successrate": 24.1, + "totalsubmissions": 99886, + "totalaccepted": 24098, + "likes": 891, + "dislikes": 86, + "hints": "How to solve the problem for k=1 ? Use Kadane's algorithm for k=1. What are the possible cases for the answer ? The answer is the maximum between, the answer for k=1, the sum of the whole array multiplied by k, or the maximum suffix sum plus the maximum prefix sum plus (k-2) multiplied by the whole array sum for k > 1.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "arr = [1,2], k = 3", + "expected_output": "9", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "arr = [1,-2,1], k = 5", + "expected_output": "2", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "arr = [-1,-2], k = 7", + "expected_output": "0", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d43", + "questionid": 632, + "title": "Delete Characters to Make Fancy String", + "slug": "delete-characters-to-make-fancy-string", + "description": "A fancy string is a string where no three consecutive characters are equal. Given a string s, delete the minimum possible number of characters from s to make it fancy. Return the final string after the deletion. It can be shown that the answer will always be unique. ", + "category": [ + "String" + ], + "complexity": "Easy", + "successrate": 56.8, + "totalsubmissions": 32711, + "totalaccepted": 18591, + "likes": 215, + "dislikes": 10, + "hints": "What's the optimal way to delete characters if three or more consecutive characters are equal? If three or more consecutive characters are equal, keep two of them and delete the rest.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "leeetcode"", + "expected_output": ""leetcode"", + "explanation": "Remove an 'e' from the first group of 'e's to create "leetcode".\nNo three consecutive characters are equal, so return "leetcode"." + }, + { + "example_num": 2, + "expected_input": "s = "aaabaaaa"", + "expected_output": ""aabaa"", + "explanation": "Remove an 'a' from the first group of 'a's to create "aabaaaa".\nRemove two 'a's from the second group of 'a's to create "aabaa".\nNo three consecutive characters are equal, so return "aabaa"." + }, + { + "example_num": 3, + "expected_input": "s = "aab"", + "expected_output": ""aab"", + "explanation": "No three consecutive characters are equal, so return "aab"." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d46", + "questionid": 635, + "title": "Ugly Number III", + "slug": "ugly-number-iii", + "description": "An ugly number is a positive integer that is divisible by a, b, or c. Given four integers n, a, b, and c, return the nth ugly number. ", + "category": [ + "Math", + "Binary Search", + "Number Theory" + ], + "complexity": "Medium", + "successrate": 27.7, + "totalsubmissions": 69539, + "totalaccepted": 19251, + "likes": 750, + "dislikes": 394, + "hints": "Write a function f(k) to determine how many ugly numbers smaller than k. As f(k) is non-decreasing, try binary search. Find all ugly numbers in [1, LCM(a, b, c)] (LCM is Least Common Multiple). Use inclusion-exclusion principle to expand the result.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 3, a = 2, b = 3, c = 5", + "expected_output": "4", + "explanation": "The ugly numbers are 2, 3, 4, 5, 6, 8, 9, 10... The 3rd is 4." + }, + { + "example_num": 2, + "expected_input": "n = 4, a = 2, b = 3, c = 4", + "expected_output": "6", + "explanation": "The ugly numbers are 2, 3, 4, 6, 8, 9, 10, 12... The 4th is 6." + }, + { + "example_num": 3, + "expected_input": "n = 5, a = 2, b = 11, c = 13", + "expected_output": "10", + "explanation": "The ugly numbers are 2, 4, 6, 8, 10, 11, 12, 13... The 5th is 10." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d4a", + "questionid": 639, + "title": "Unique Number of Occurrences", + "slug": "unique-number-of-occurrences", + "description": "Given an array of integers arr, return true if the number of occurrences of each value in the array is unique, or false otherwise. ", + "category": [ + "Array", + "Hash Table" + ], + "complexity": "Easy", + "successrate": 72, + "totalsubmissions": 170248, + "totalaccepted": 122558, + "likes": 1402, + "dislikes": 33, + "hints": "Find the number of occurrences of each element in the array using a hash map. Iterate through the hash map and check if there is a repeated value.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "arr = [1,2,2,1,1,3]", + "expected_output": "true", + "explanation": " The value 1 has 3 occurrences, 2 has 2 and 3 has 1. No two values have the same number of occurrences." + }, + { + "example_num": 2, + "expected_input": "arr = [1,2]", + "expected_output": "false", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "arr = [-3,0,1,-3,1,1,1,-3,10,0]", + "expected_output": "true", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d4f", + "questionid": 644, + "title": "Sum of Floored Pairs", + "slug": "sum-of-floored-pairs", + "description": "Given an integer array nums, return the sum of floor(nums[i] / nums[j]) for all pairs of indices 0 <= i, j < nums.length in the array. Since the answer may be too large, return it modulo 109 + 7. The floor() function returns the integer part of the division. ", + "category": [ + "Array", + "Math", + "Binary Search", + "Prefix Sum" + ], + "complexity": "Hard", + "successrate": 27.9, + "totalsubmissions": 20976, + "totalaccepted": 5862, + "likes": 287, + "dislikes": 24, + "hints": "Find the frequency (number of occurrences) of all elements in the array. For each element, iterate through its multiples and multiply frequencies to find the answer.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [2,5,9]", + "expected_output": "10", + "explanation": "floor(2 / 5) = floor(2 / 9) = floor(5 / 9) = 0\nfloor(2 / 2) = floor(5 / 5) = floor(9 / 9) = 1\nfloor(5 / 2) = 2\nfloor(9 / 2) = 4\nfloor(9 / 5) = 1\nWe calculate the floor of the division for every pair of indices in the array then sum them up." + }, + { + "example_num": 2, + "expected_input": "nums = [7,7,7,7,7,7,7]", + "expected_output": "49", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d5a", + "questionid": 655, + "title": "Maximum Length of a Concatenated String with Unique Characters", + "slug": "maximum-length-of-a-concatenated-string-with-unique-characters", + "description": "You are given an array of strings arr. A string s is formed by the concatenation of a subsequence of arr that has unique characters. Return the maximum possible length of s. A subsequence is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements. ", + "category": [ + "Array", + "String", + "Backtracking", + "Bit Manipulation" + ], + "complexity": "Medium", + "successrate": 50.5, + "totalsubmissions": 208173, + "totalaccepted": 105219, + "likes": 1721, + "dislikes": 155, + "hints": "You can try all combinations and keep mask of characters you have. You can use DP.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "arr = ["un","iq","ue"]", + "expected_output": "4", + "explanation": "All the valid concatenations are:\n- ""\n- "un"\n- "iq"\n- "ue"\n- "uniq" ("un" + "iq")\n- "ique" ("iq" + "ue")\nMaximum length is 4." + }, + { + "example_num": 2, + "expected_input": "arr = ["cha","r","act","ers"]", + "expected_output": "6", + "explanation": "Possible longest valid concatenations are "chaers" ("cha" + "ers") and "acters" ("act" + "ers")." + }, + { + "example_num": 3, + "expected_input": "arr = ["abcdefghijklmnopqrstuvwxyz"]", + "expected_output": "26", + "explanation": "The only string in arr has all 26 characters." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d5c", + "questionid": 657, + "title": "Tuple with Same Product", + "slug": "tuple-with-same-product", + "description": "Given an array nums of distinct positive integers, return the number of tuples (a, b, c, d) such that a * b = c * d where a, b, c, and d are elements of nums, and a != b != c != d. ", + "category": [ + "Array", + "Hash Table" + ], + "complexity": "Medium", + "successrate": 60.5, + "totalsubmissions": 30445, + "totalaccepted": 18406, + "likes": 406, + "dislikes": 19, + "hints": "Note that all of the integers are distinct. This means that each time a product is formed it must be formed by two unique integers. Count the frequency of each product of 2 distinct numbers. Then calculate the permutations formed.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [2,3,4,6]", + "expected_output": "8", + "explanation": "There are 8 valid tuples:\n(2,6,3,4) , (2,6,4,3) , (6,2,3,4) , (6,2,4,3)\n(3,4,2,6) , (4,3,2,6) , (3,4,6,2) , (4,3,6,2)" + }, + { + "example_num": 2, + "expected_input": "nums = [1,2,4,5,10]", + "expected_output": "16", + "explanation": "There are 16 valid tuples:\n(1,10,2,5) , (1,10,5,2) , (10,1,2,5) , (10,1,5,2)\n(2,5,1,10) , (2,5,10,1) , (5,2,1,10) , (5,2,10,1)\n(2,10,4,5) , (2,10,5,4) , (10,2,4,5) , (10,2,5,4)\n(4,5,2,10) , (4,5,10,2) , (5,4,2,10) , (5,4,10,2)" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d5e", + "questionid": 659, + "title": "Count Number of Nice Subarrays", + "slug": "count-number-of-nice-subarrays", + "description": "Given an array of integers nums and an integer k. A continuous subarray is called nice if there are k odd numbers on it. Return the number of nice sub-arrays. ", + "category": [ + "Array", + "Hash Table", + "Math", + "Sliding Window" + ], + "complexity": "Medium", + "successrate": 58.5, + "totalsubmissions": 89894, + "totalaccepted": 52568, + "likes": 1659, + "dislikes": 42, + "hints": "After replacing each even by zero and every odd by one can we use prefix sum to find answer ? Can we use two pointers to count number of sub-arrays ? Can we store indices of odd numbers and for each k indices count number of sub-arrays contains them ?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,1,2,1,1], k = 3", + "expected_output": "2", + "explanation": "The only sub-arrays with 3 odd numbers are [1,1,2,1] and [1,2,1,1]." + }, + { + "example_num": 2, + "expected_input": "nums = [2,4,6], k = 1", + "expected_output": "0", + "explanation": "There are no odd numbers in the array." + }, + { + "example_num": 3, + "expected_input": "nums = [2,2,2,1,2,2,1,2,2,2], k = 2", + "expected_output": "16", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d5f", + "questionid": 660, + "title": "Check If It Is a Good Array", + "slug": "check-if-it-is-a-good-array", + "description": "Given an array nums of positive integers. Your task is to select some subset of nums, multiply each element by an integer and add all these numbers. The array is said to be good if you can obtain a sum of 1 from the array by any possible subset and multiplicand. Return True if the array is good otherwise return False. ", + "category": [ + "Array", + "Math", + "Number Theory" + ], + "complexity": "Hard", + "successrate": 57.9, + "totalsubmissions": 22606, + "totalaccepted": 13097, + "likes": 251, + "dislikes": 274, + "hints": "Eq. ax+by=1 has solution x, y if gcd(a,b) = 1. Can you generalize the formula?. Check Bézout's lemma.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [12,5,7,23]", + "expected_output": "true", + "explanation": "Pick numbers 5 and 7.\n5*3 + 7*(-2) = 1" + }, + { + "example_num": 2, + "expected_input": "nums = [29,6,10]", + "expected_output": "true", + "explanation": "Pick numbers 29, 6 and 10.\n29*1 + 6*(-3) + 10*(-1) = 1" + }, + { + "example_num": 3, + "expected_input": "nums = [3,6]", + "expected_output": "false", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d61", + "questionid": 662, + "title": "Number of Closed Islands", + "slug": "number-of-closed-islands", + "description": "Given a 2D grid consists of 0s (land) and 1s (water).  An island is a maximal 4-directionally connected group of 0s and a closed island is an island totally (all left, top, right, bottom) surrounded by 1s. Return the number of closed islands. ", + "category": [ + "Array", + "Depth-First Search", + "Breadth-First Search", + "Union Find", + "Matrix" + ], + "complexity": "Medium", + "successrate": 63.3, + "totalsubmissions": 133520, + "totalaccepted": 84486, + "likes": 1755, + "dislikes": 39, + "hints": "Exclude connected group of 0s on the corners because they are not closed island. Return number of connected component of 0s on the grid.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "grid = [[1,1,1,1,1,1,1,0],[1,0,0,0,0,1,1,0],[1,0,1,0,1,1,1,0],[1,0,0,0,0,1,0,1],[1,1,1,1,1,1,1,0]]", + "expected_output": "2", + "explanation": "Islands in gray are closed because they are completely surrounded by water (group of 1s)." + }, + { + "example_num": 2, + "expected_input": "grid = [[0,0,1,0,0],[0,1,0,1,0],[0,1,1,1,0]]", + "expected_output": "1", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "grid = [[1,1,1,1,1,1,1],\n  [1,0,0,0,0,0,1],\n  [1,0,1,1,1,0,1],\n  [1,0,1,0,1,0,1],\n  [1,0,1,1,1,0,1],\n  [1,0,0,0,0,0,1],\n [1,1,1,1,1,1,1]]", + "expected_output": "2", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d68", + "questionid": 669, + "title": "Count Square Submatrices with All Ones", + "slug": "count-square-submatrices-with-all-ones", + "description": "Given a m * n matrix of ones and zeros, return how many square submatrices have all ones. ", + "category": [ + "Array", + "Dynamic Programming", + "Matrix" + ], + "complexity": "Medium", + "successrate": 74.2, + "totalsubmissions": 215047, + "totalaccepted": 159523, + "likes": 3221, + "dislikes": 53, + "hints": "Create an additive table that counts the sum of elements of submatrix with the superior corner at (0,0). Loop over all subsquares in O(n^3) and check if the sum make the whole array to be ones, if it checks then add 1 to the answer.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "matrix =\n[\n  [0,1,1,1],\n  [1,1,1,1],\n  [0,1,1,1]\n]", + "expected_output": "15", + "explanation": "There are 10 squares of side 1.\nThere are 4 squares of side 2.\nThere is 1 square of side 3.\nTotal number of squares = 10 + 4 + 1 = 15." + }, + { + "example_num": 2, + "expected_input": "matrix = \n[\n [1,0,1],\n [1,1,0],\n [1,1,0]\n]", + "expected_output": "7", + "explanation": "There are 6 squares of side 1. \nThere is 1 square of side 2. \nTotal number of squares = 6 + 1 = 7." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d69", + "questionid": 670, + "title": "Group the People Given the Group Size They Belong To", + "slug": "group-the-people-given-the-group-size-they-belong-to", + "description": "There are n people that are split into some unknown number of groups. Each person is labeled with a unique ID from 0 to n - 1. You are given an integer array groupSizes, where groupSizes[i] is the size of the group that person i is in. For example, if groupSizes[1] = 3, then person 1 must be in a group of size 3. Return a list of groups such that each person i is in a group of size groupSizes[i]. Each person should appear in exactly one group, and every person must be in a group. If there are multiple answers, return any of them. It is guaranteed that there will be at least one valid solution for the given input. ", + "category": [ + "Array", + "Hash Table" + ], + "complexity": "Medium", + "successrate": 85.3, + "totalsubmissions": 91779, + "totalaccepted": 78252, + "likes": 995, + "dislikes": 461, + "hints": "Put people's IDs with same groupSize into buckets, then split each bucket into groups. Greedy fill until you need a new group.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "groupSizes = [3,3,3,3,3,1,3]", + "expected_output": "[[5],[0,1,2],[3,4,6]]\nExplanation: \nThe first group is [5]. The size is 1, and groupSizes[5] = 1.\nThe second group is [0,1,2]. The size is 3, and groupSizes[0] = groupSizes[1] = groupSizes[2] = 3.\nThe third group is [3,4,6]. The size is 3, and groupSizes[3] = groupSizes[4] = groupSizes[6] = 3.\nOther possible solutions are [[2,1,6],[5],[0,4,3]] and [[5],[0,6,2],[4,3,1]].", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "groupSizes = [2,1,3,3,3,2]", + "expected_output": "[[1],[0,5],[2,3,4]]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d6b", + "questionid": 672, + "title": "Convert Binary Number in a Linked List to Integer", + "slug": "convert-binary-number-in-a-linked-list-to-integer", + "description": "Given head which is a reference node to a singly-linked list. The value of each node in the linked list is either 0 or 1. The linked list holds the binary representation of a number. Return the decimal value of the number in the linked list. ", + "category": [ + "Linked List", + "Math" + ], + "complexity": "Easy", + "successrate": 82.7, + "totalsubmissions": 340360, + "totalaccepted": 281429, + "likes": 2462, + "dislikes": 123, + "hints": "Traverse the linked list and store all values in a string or array. convert the values obtained to decimal value. You can solve the problem in O(1) memory using bits operation. use shift left operation ( << ) and or operation ( | ) to get the decimal value in one operation.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "head = [1,0,1]", + "expected_output": "5", + "explanation": "(101) in base 2 = (5) in base 10" + }, + { + "example_num": 2, + "expected_input": "head = [0]", + "expected_output": "0", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d6c", + "questionid": 673, + "title": "Maximum Side Length of a Square with Sum Less than or Equal to Threshold", + "slug": "maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold", + "description": "Given a m x n matrix mat and an integer threshold, return the maximum side-length of a square with a sum less than or equal to threshold or return 0 if there is no such square. ", + "category": [ + "Array", + "Binary Search", + "Matrix", + "Prefix Sum" + ], + "complexity": "Medium", + "successrate": 52.2, + "totalsubmissions": 45286, + "totalaccepted": 23625, + "likes": 766, + "dislikes": 59, + "hints": "Store prefix sum of all grids in another 2D array. Try all possible solutions and if you cannot find one return -1. If x is a valid answer then any y < x is also valid answer. Use binary search to find answer.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "mat = [[1,1,3,2,4,3,2],[1,1,3,2,4,3,2],[1,1,3,2,4,3,2]], threshold = 4", + "expected_output": "2", + "explanation": "The maximum side length of square with sum less than 4 is 2 as shown." + }, + { + "example_num": 2, + "expected_input": "mat = [[2,2,2,2,2],[2,2,2,2,2],[2,2,2,2,2],[2,2,2,2,2],[2,2,2,2,2]], threshold = 1", + "expected_output": "0", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d70", + "questionid": 677, + "title": "Find N Unique Integers Sum up to Zero", + "slug": "find-n-unique-integers-sum-up-to-zero", + "description": "Given an integer n, return any array containing n unique integers such that they add up to 0. ", + "category": [ + "Array", + "Math" + ], + "complexity": "Easy", + "successrate": 76.9, + "totalsubmissions": 175888, + "totalaccepted": 135316, + "likes": 1047, + "dislikes": 456, + "hints": "Return an array where the values are symmetric. (+x , -x). If n is odd, append value 0 in your returned array.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 5", + "expected_output": "[-7,-1,1,3,4]", + "explanation": "These arrays also are accepted [-5,-1,1,2,3] , [-3,-1,2,-2,4]." + }, + { + "example_num": 2, + "expected_input": "n = 3", + "expected_output": "[-1,0,1]", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "n = 1", + "expected_output": "[0]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d72", + "questionid": 679, + "title": "Jump Game III", + "slug": "jump-game-iii", + "description": "Given an array of non-negative integers arr, you are initially positioned at start index of the array. When you are at index i, you can jump to i + arr[i] or i - arr[i], check if you can reach to any index with value 0. Notice that you can not jump outside of the array at any time. ", + "category": [ + "Array", + "Depth-First Search", + "Breadth-First Search" + ], + "complexity": "Medium", + "successrate": 62.8, + "totalsubmissions": 225811, + "totalaccepted": 141718, + "likes": 2638, + "dislikes": 63, + "hints": "Think of BFS to solve the problem. When you reach a position with a value = 0 then return true.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "arr = [4,2,3,0,3,1,2], start = 5", + "expected_output": "true", + "explanation": "All possible ways to reach at index 3 with value 0 are: \nindex 5 -> index 4 -> index 1 -> index 3 \nindex 5 -> index 6 -> index 4 -> index 1 -> index 3" + }, + { + "example_num": 2, + "expected_input": "arr = [4,2,3,0,3,1,2], start = 0", + "expected_output": "true \nExplanation: \nOne possible way to reach at index 3 with value 0 is: \nindex 0 -> index 4 -> index 1 -> index 3", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "arr = [3,0,2,1,2], start = 2", + "expected_output": "false\nExplanation: There is no way to reach at index 1 with value 0.", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d74", + "questionid": 681, + "title": "XOR Queries of a Subarray", + "slug": "xor-queries-of-a-subarray", + "description": "You are given an array arr of positive integers. You are also given the array queries where queries[i] = [lefti, righti]. For each query i compute the XOR of elements from lefti to righti (that is, arr[lefti] XOR arr[lefti + 1] XOR ... XOR arr[righti] ). Return an array answer where answer[i] is the answer to the ith query. ", + "category": [ + "Array", + "Bit Manipulation", + "Prefix Sum" + ], + "complexity": "Medium", + "successrate": 71.2, + "totalsubmissions": 50087, + "totalaccepted": 35676, + "likes": 895, + "dislikes": 30, + "hints": "What is the result of x ^ y ^ x ? Compute the prefix sum for XOR. Process the queries with the prefix sum values.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "arr = [1,3,4,8], queries = [[0,1],[1,2],[0,3],[3,3]]", + "expected_output": "[2,7,14,8]", + "explanation": "The binary representation of the elements in the array are:\n1 = 0001 \n3 = 0011 \n4 = 0100 \n8 = 1000 \nThe XOR values for queries are:\n[0,1] = 1 xor 3 = 2 \n[1,2] = 3 xor 4 = 7 \n[0,3] = 1 xor 3 xor 4 xor 8 = 14 \n[3,3] = 8" + }, + { + "example_num": 2, + "expected_input": "arr = [4,8,2,10], queries = [[2,3],[1,3],[0,0],[0,3]]", + "expected_output": "[8,0,4,4]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d77", + "questionid": 684, + "title": "Minimum Flips to Make a OR b Equal to c", + "slug": "minimum-flips-to-make-a-or-b-equal-to-c", + "description": "Given 3 positives numbers a, b and c. Return the minimum flips required in some bits of a and b to make ( a OR b == c ). (bitwise OR operation).\r\nFlip operation consists of change any single bit 1 to 0 or change the bit 0 to 1 in their binary representation. ", + "category": [ + "Bit Manipulation" + ], + "complexity": "Medium", + "successrate": 65.3, + "totalsubmissions": 36445, + "totalaccepted": 23792, + "likes": 428, + "dislikes": 37, + "hints": "Check the bits one by one whether they need to be flipped.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "a = 2, b = 6, c = 5", + "expected_output": "3\r\nExplanation: After flips a = 1 , b = 4 , c = 5 such that (a OR b == c)", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "a = 4, b = 2, c = 7", + "expected_output": "1", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "a = 1, b = 2, c = 3", + "expected_output": "0", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d79", + "questionid": 686, + "title": "Minimum Distance to Type a Word Using Two Fingers", + "slug": "minimum-distance-to-type-a-word-using-two-fingers", + "description": "You have a keyboard layout as shown above in the X-Y plane, where each English uppercase letter is located at some coordinate. Given the string word, return the minimum total distance to type such string using only two fingers. The distance between coordinates (x1, y1) and (x2, y2) is |x1 - x2| + |y1 - y2|. Note that the initial positions of your two fingers are considered free so do not count towards your total distance, also your two fingers do not have to start at the first letter or the first two letters. ", + "category": [ + "String", + "Dynamic Programming" + ], + "complexity": "Hard", + "successrate": 60.3, + "totalsubmissions": 39380, + "totalaccepted": 23752, + "likes": 755, + "dislikes": 30, + "hints": "Use dynamic programming. dp[i][j][k]: smallest movements when you have one finger on i-th char and the other one on j-th char already having written k first characters from word.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "word = "CAKE"", + "expected_output": "3", + "explanation": "Using two fingers, one optimal way to type "CAKE" is: \nFinger 1 on letter 'C' -> cost = 0 \nFinger 1 on letter 'A' -> cost = Distance from letter 'C' to letter 'A' = 2 \nFinger 2 on letter 'K' -> cost = 0 \nFinger 2 on letter 'E' -> cost = Distance from letter 'K' to letter 'E' = 1 \nTotal distance = 3" + }, + { + "example_num": 2, + "expected_input": "word = "HAPPY"", + "expected_output": "6", + "explanation": "Using two fingers, one optimal way to type "HAPPY" is:\nFinger 1 on letter 'H' -> cost = 0\nFinger 1 on letter 'A' -> cost = Distance from letter 'H' to letter 'A' = 2\nFinger 2 on letter 'P' -> cost = 0\nFinger 2 on letter 'P' -> cost = Distance from letter 'P' to letter 'P' = 0\nFinger 1 on letter 'Y' -> cost = Distance from letter 'A' to letter 'Y' = 4\nTotal distance = 6" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d7b", + "questionid": 688, + "title": "Number of Sub-arrays of Size K and Average Greater than or Equal to Threshold", + "slug": "number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold", + "description": "Given an array of integers arr and two integers k and threshold, return the number of sub-arrays of size k and average greater than or equal to threshold. ", + "category": [ + "Array", + "Sliding Window" + ], + "complexity": "Medium", + "successrate": 67.8, + "totalsubmissions": 47808, + "totalaccepted": 32427, + "likes": 581, + "dislikes": 57, + "hints": "Start with a window of size K and test its average against the threshold. Keep moving the window by one element maintaining its size k until you cover the whole array. count number of windows that satisfy that its average is greater than the threshold.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "arr = [2,2,2,2,5,5,5,8], k = 3, threshold = 4", + "expected_output": "3", + "explanation": "Sub-arrays [2,5,5],[5,5,5] and [5,5,8] have averages 4, 5 and 6 respectively. All other sub-arrays of size 3 have averages less than 4 (the threshold)." + }, + { + "example_num": 2, + "expected_input": "arr = [11,13,17,23,29,31,7,5,2,3], k = 3, threshold = 5", + "expected_output": "6", + "explanation": "The first 6 sub-arrays of size 3 have averages greater than 5. Note that averages are not integers." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d7c", + "questionid": 689, + "title": "Angle Between Hands of a Clock", + "slug": "angle-between-hands-of-a-clock", + "description": "Given two numbers, hour and minutes, return the smaller angle (in degrees) formed between the hour and the minute hand. Answers within 10-5 of the actual value will be accepted as correct. ", + "category": [ + "Math" + ], + "complexity": "Medium", + "successrate": 63.2, + "totalsubmissions": 140671, + "totalaccepted": 88882, + "likes": 914, + "dislikes": 191, + "hints": "The tricky part is determining how the minute hand affects the position of the hour hand. Calculate the angles separately then find the difference.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "hour = 12, minutes = 30", + "expected_output": "165", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "hour = 3, minutes = 30", + "expected_output": "75", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "hour = 3, minutes = 15", + "expected_output": "7.5", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d7e", + "questionid": 691, + "title": "Print Words Vertically", + "slug": "print-words-vertically", + "description": "Given a string s. Return all the words vertically in the same order in which they appear in s.\r\nWords are returned as a list of strings, complete with spaces when is necessary. (Trailing spaces are not allowed).\r\nEach word would be put on only one column and that in one column there will be only one word. ", + "category": [ + "Array", + "String", + "Simulation" + ], + "complexity": "Medium", + "successrate": 59.6, + "totalsubmissions": 43408, + "totalaccepted": 25873, + "likes": 431, + "dislikes": 87, + "hints": "Use the maximum length of words to determine the length of the returned answer. However, don't forget to remove trailing spaces.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "HOW ARE YOU"", + "expected_output": "["HAY","ORO","WEU"]\r\nExplanation: Each word is printed vertically. \r\n "HAY"\r\n "ORO"\r\n "WEU"", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "s = "TO BE OR NOT TO BE"", + "expected_output": "["TBONTB","OEROOE"," T"]\r\nExplanation: Trailing spaces is not allowed. \r\n"TBONTB"\r\n"OEROOE"\r\n" T"", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "s = "CONTEST IS COMING"", + "expected_output": "["CIC","OSO","N M","T I","E N","S G","T"]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d86", + "questionid": 699, + "title": "Number of Substrings Containing All Three Characters", + "slug": "number-of-substrings-containing-all-three-characters", + "description": "Given a string s consisting only of characters a, b and c. Return the number of substrings containing at least one occurrence of all these characters a, b and c. ", + "category": [ + "Hash Table", + "String", + "Sliding Window" + ], + "complexity": "Medium", + "successrate": 62.1, + "totalsubmissions": 57647, + "totalaccepted": 35808, + "likes": 1378, + "dislikes": 25, + "hints": "For each position we simply need to find the first occurrence of a/b/c on or after this position. So we can pre-compute three link-list of indices of each a, b, and c.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "abcabc"", + "expected_output": "10", + "explanation": "The substrings containing at least one occurrence of the characters ab and c are "abc", "abca", "abcab", "abcabc", "bca", "bcab", "bcabc", "cab", "cabc" and "abc" (again). " + }, + { + "example_num": 2, + "expected_input": "s = "aaacb"", + "expected_output": "3", + "explanation": "The substrings containing at least one occurrence of the characters ab and c are "aaacb", "aacb" and "acb". " + }, + { + "example_num": 3, + "expected_input": "s = "abc"", + "expected_output": "1", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d53", + "questionid": 648, + "title": "Split a String in Balanced Strings", + "slug": "split-a-string-in-balanced-strings", + "description": "Balanced strings are those that have an equal quantity of 'L' and 'R' characters. Given a balanced string s, split it in the maximum amount of balanced strings. Return the maximum amount of split balanced strings. ", + "category": [ + "String", + "Greedy", + "Counting" + ], + "complexity": "Easy", + "successrate": 84.7, + "totalsubmissions": 231115, + "totalaccepted": 195643, + "likes": 1680, + "dislikes": 747, + "hints": "Loop from left to right maintaining a balance variable when it gets an L increase it by one otherwise decrease it by one. Whenever the balance variable reaches zero then we increase the answer by one.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "RLRRLLRLRL"", + "expected_output": "4", + "explanation": "s can be split into "RL", "RRLL", "RL", "RL", each substring contains same number of 'L' and 'R'." + }, + { + "example_num": 2, + "expected_input": "s = "RLRRRLLRLL"", + "expected_output": "2", + "explanation": "s can be split into "RL", "RRRLLRLL", each substring contains same number of 'L' and 'R'.\nNote that s cannot be split into "RL", "RR", "RL", "LR", "LL", because the 2nd and 5th substrings are not balanced." + }, + { + "example_num": 3, + "expected_input": "s = "LLLLRRRR"", + "expected_output": "1", + "explanation": "s can be split into "LLLLRRRR"." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d55", + "questionid": 650, + "title": "Dice Roll Simulation", + "slug": "dice-roll-simulation", + "description": "A die simulator generates a random number from 1 to 6 for each roll. You introduced a constraint to the generator such that it cannot roll the number i more than rollMax[i] (1-indexed) consecutive times. Given an array of integers rollMax and an integer n, return the number of distinct sequences that can be obtained with exact n rolls. Since the answer may be too large, return it modulo 109 + 7. Two sequences are considered different if at least one element differs from each other. ", + "category": [ + "Array", + "Dynamic Programming" + ], + "complexity": "Hard", + "successrate": 47.8, + "totalsubmissions": 45213, + "totalaccepted": 21615, + "likes": 680, + "dislikes": 175, + "hints": "Think on Dynamic Programming. DP(pos, last) which means we are at the position pos having as last the last character seen.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 2, rollMax = [1,1,2,2,2,3]", + "expected_output": "34", + "explanation": "There will be 2 rolls of die, if there are no constraints on the die, there are 6 * 6 = 36 possible combinations. In this case, looking at rollMax array, the numbers 1 and 2 appear at most once consecutively, therefore sequences (1,1) and (2,2) cannot occur, so the final answer is 36-2 = 34." + }, + { + "example_num": 2, + "expected_input": "n = 2, rollMax = [1,1,1,1,1,1]", + "expected_output": "30", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "n = 3, rollMax = [1,1,1,2,2,3]", + "expected_output": "181", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d56", + "questionid": 651, + "title": "Maximum Equal Frequency", + "slug": "maximum-equal-frequency", + "description": "Given an array nums of positive integers, return the longest possible length of an array prefix of nums, such that it is possible to remove exactly one element from this prefix so that every number that has appeared in it will have the same number of occurrences. If after removing one element there are no remaining elements, it's still considered that every appeared number has the same number of ocurrences (0). ", + "category": [ + "Array", + "Hash Table" + ], + "complexity": "Hard", + "successrate": 36.6, + "totalsubmissions": 28983, + "totalaccepted": 10611, + "likes": 359, + "dislikes": 41, + "hints": "Keep track of the min and max frequencies. The number to be eliminated must have a frequency of 1, same as the others or the same +1.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [2,2,1,1,5,3,3,5]", + "expected_output": "7", + "explanation": "For the subarray [2,2,1,1,5,3,3] of length 7, if we remove nums[4] = 5, we will get [2,2,1,1,3,3], so that each number will appear exactly twice." + }, + { + "example_num": 2, + "expected_input": "nums = [1,1,1,2,2,2,3,3,3,4,4,4,5]", + "expected_output": "13", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d58", + "questionid": 653, + "title": "Maximum Profit in Job Scheduling", + "slug": "maximum-profit-in-job-scheduling", + "description": "We have n jobs, where every job is scheduled to be done from startTime[i] to endTime[i], obtaining a profit of profit[i]. You're given the startTime, endTime and profit arrays, return the maximum profit you can take such that there are no two jobs in the subset with overlapping time range. If you choose a job that ends at time X you will be able to start another job that starts at time X. ", + "category": [ + "Array", + "Binary Search", + "Dynamic Programming", + "Sorting" + ], + "complexity": "Hard", + "successrate": 50.9, + "totalsubmissions": 216641, + "totalaccepted": 110214, + "likes": 3106, + "dislikes": 34, + "hints": "Think on DP. Sort the elements by starting time, then define the dp[i] as the maximum profit taking elements from the suffix starting at i. Use binarySearch (lower_bound/upper_bound on C++) to get the next index for the DP transition.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "startTime = [1,2,3,3], endTime = [3,4,5,6], profit = [50,10,40,70]", + "expected_output": "120", + "explanation": "The subset chosen is the first and fourth job. \nTime range [1-3]+[3-6] , we get profit of 120 = 50 + 70." + }, + { + "example_num": 2, + "expected_input": "startTime = [1,2,3,4,6], endTime = [3,5,10,6,9], profit = [20,20,100,70,60]", + "expected_output": "150", + "explanation": "The subset chosen is the first, fourth and fifth job. \nProfit obtained 150 = 20 + 70 + 60." + }, + { + "example_num": 3, + "expected_input": "startTime = [1,1,1], endTime = [2,3,4], profit = [5,6,4]", + "expected_output": "6", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d60", + "questionid": 661, + "title": "Find Palindrome With Fixed Length", + "slug": "find-palindrome-with-fixed-length", + "description": "Given an integer array queries and a positive integer intLength, return an array answer where answer[i] is either the queries[i]th smallest positive palindrome of length intLength or -1 if no such palindrome exists. A palindrome is a number that reads the same backwards and forwards. Palindromes cannot have leading zeros. ", + "category": [ + "Array", + "Math" + ], + "complexity": "Medium", + "successrate": 34.3, + "totalsubmissions": 28626, + "totalaccepted": 9810, + "likes": 298, + "dislikes": 165, + "hints": "For any value of queries[i] and intLength, how can you check if there exists at least queries[i] palindromes of length intLength? Since a palindrome reads the same forwards and backwards, consider how you can efficiently find the first half (ceil(intLength/2) digits) of the palindrome.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "queries = [1,2,3,4,5,90], intLength = 3", + "expected_output": "[101,111,121,131,141,999]", + "explanation": "The first few palindromes of length 3 are:\n101, 111, 121, 131, 141, 151, 161, 171, 181, 191, 202, ...\nThe 90th palindrome of length 3 is 999." + }, + { + "example_num": 2, + "expected_input": "queries = [2,4,6], intLength = 4", + "expected_output": "[1111,1331,1551]", + "explanation": "The first six palindromes of length 4 are:\n1001, 1111, 1221, 1331, 1441, and 1551." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d63", + "questionid": 664, + "title": "Greatest Sum Divisible by Three", + "slug": "greatest-sum-divisible-by-three", + "description": "Given an array nums of integers, we need to find the maximum possible sum of elements of the array such that it is divisible by three. ", + "category": [ + "Array", + "Dynamic Programming", + "Greedy" + ], + "complexity": "Medium", + "successrate": 50.8, + "totalsubmissions": 73929, + "totalaccepted": 37564, + "likes": 1184, + "dislikes": 34, + "hints": "Represent the state as DP[pos][mod]: maximum possible sum starting in the position \"pos\" in the array where the current sum modulo 3 is equal to mod.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [3,6,5,1,8]", + "expected_output": "18", + "explanation": "Pick numbers 3, 6, 1 and 8 their sum is 18 (maximum sum divisible by 3)." + }, + { + "example_num": 2, + "expected_input": "nums = [4]", + "expected_output": "0", + "explanation": "Since 4 is not divisible by 3, do not pick any number." + }, + { + "example_num": 3, + "expected_input": "nums = [1,2,3,4,4]", + "expected_output": "12", + "explanation": "Pick numbers 1, 3, 4 and 4 their sum is 12 (maximum sum divisible by 3)." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d67", + "questionid": 668, + "title": "Number of Ways to Stay in the Same Place After Some Steps", + "slug": "number-of-ways-to-stay-in-the-same-place-after-some-steps", + "description": "You have a pointer at index 0 in an array of size arrLen. At each step, you can move 1 position to the left, 1 position to the right in the array, or stay in the same place (The pointer should not be placed outside the array at any time). Given two integers steps and arrLen, return the number of ways such that your pointer still at index 0 after exactly steps steps. Since the answer may be too large, return it modulo 109 + 7. ", + "category": [ + "Dynamic Programming" + ], + "complexity": "Hard", + "successrate": 43.4, + "totalsubmissions": 63005, + "totalaccepted": 27329, + "likes": 531, + "dislikes": 30, + "hints": "Try with Dynamic programming, dp(pos,steps): number of ways to back pos = 0 using exactly \"steps\" moves. Notice that the computational complexity does not depend of \"arrlen\".", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "steps = 3, arrLen = 2", + "expected_output": "4\nExplanation: There are 4 differents ways to stay at index 0 after 3 steps.\nRight, Left, Stay\nStay, Right, Left\nRight, Stay, Left\nStay, Stay, Stay", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "steps = 2, arrLen = 4", + "expected_output": "2", + "explanation": "There are 2 differents ways to stay at index 0 after 2 steps\nRight, Left\nStay, Stay" + }, + { + "example_num": 3, + "expected_input": "steps = 4, arrLen = 2", + "expected_output": "8", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d6e", + "questionid": 675, + "title": "Find Numbers with Even Number of Digits", + "slug": "find-numbers-with-even-number-of-digits", + "description": "Given an array nums of integers, return how many of them contain an even number of digits. ", + "category": [ + "Array" + ], + "complexity": "Easy", + "successrate": 77.1, + "totalsubmissions": 545968, + "totalaccepted": 421174, + "likes": 1225, + "dislikes": 98, + "hints": "How to compute the number of digits of a number ? Divide the number by 10 again and again to get the number of digits.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [12,345,2,6,7896]", + "expected_output": "2\nExplanation: \n12 contains 2 digits (even number of digits). \n345 contains 3 digits (odd number of digits). \n2 contains 1 digit (odd number of digits). \n6 contains 1 digit (odd number of digits). \n7896 contains 4 digits (even number of digits). \nTherefore only 12 and 7896 contain an even number of digits.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "nums = [555,901,482,1771]", + "expected_output": "1 \nExplanation: \nOnly 1771 contains an even number of digits.", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d71", + "questionid": 678, + "title": "All Elements in Two Binary Search Trees", + "slug": "all-elements-in-two-binary-search-trees", + "description": "Given two binary search trees root1 and root2, return a list containing all the integers from both trees sorted in ascending order. ", + "category": [ + "Tree", + "Depth-First Search", + "Binary Search Tree", + "Sorting", + "Binary Tree" + ], + "complexity": "Medium", + "successrate": 79.6, + "totalsubmissions": 200538, + "totalaccepted": 159646, + "likes": 2179, + "dislikes": 64, + "hints": "Traverse the first tree in list1 and the second tree in list2. Merge the two trees in one list and sort it.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root1 = [2,1,4], root2 = [1,0,3]", + "expected_output": "[0,1,1,2,3,4]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "root1 = [1,null,8], root2 = [8,1]", + "expected_output": "[1,1,8,8]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d75", + "questionid": 682, + "title": "Get Watched Videos by Your Friends", + "slug": "get-watched-videos-by-your-friends", + "description": "There are n people, each person has a unique id between 0 and n-1. Given the arrays watchedVideos and friends, where watchedVideos[i] and friends[i] contain the list of watched videos and the list of friends respectively for the person with id = i. Level 1 of videos are all watched videos by your friends, level 2 of videos are all watched videos by the friends of your friends and so on. In general, the level k of videos are all watched videos by people with the shortest path exactly equal to k with you. Given your id and the level of videos, return the list of videos ordered by their frequencies (increasing). For videos with the same frequency order them alphabetically from least to greatest. ", + "category": [ + "Array", + "Hash Table", + "Breadth-First Search", + "Sorting" + ], + "complexity": "Medium", + "successrate": 45.2, + "totalsubmissions": 33009, + "totalaccepted": 14910, + "likes": 207, + "dislikes": 289, + "hints": "Do BFS to find the kth level friends. Then collect movies saw by kth level friends and sort them accordingly.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "watchedVideos = [["A","B"],["C"],["B","C"],["D"]], friends = [[1,2],[0,3],[0,3],[1,2]], id = 0, level = 1", + "expected_output": "["B","C"]", + "explanation": "You have id = 0 (green color in the figure) and your friends are (yellow color in the figure):\nPerson with id = 1 -> watchedVideos = ["C"] \nPerson with id = 2 -> watchedVideos = ["B","C"] \nThe frequencies of watchedVideos by your friends are: \nB -> 1 \nC -> 2" + }, + { + "example_num": 2, + "expected_input": "watchedVideos = [["A","B"],["C"],["B","C"],["D"]], friends = [[1,2],[0,3],[0,3],[1,2]], id = 0, level = 2", + "expected_output": "["D"]", + "explanation": "You have id = 0 (green color in the figure) and the only friend of your friends is the person with id = 3 (yellow color in the figure)." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d76", + "questionid": 683, + "title": "Minimum Insertion Steps to Make a String Palindrome", + "slug": "minimum-insertion-steps-to-make-a-string-palindrome", + "description": "Given a string s. In one step you can insert any character at any index of the string. Return the minimum number of steps to make s palindrome. A Palindrome String is one that reads the same backward as well as forward. ", + "category": [ + "String", + "Dynamic Programming" + ], + "complexity": "Hard", + "successrate": 63.6, + "totalsubmissions": 72187, + "totalaccepted": 45892, + "likes": 1686, + "dislikes": 25, + "hints": "Is dynamic programming suitable for this problem ? If we know the longest palindromic sub-sequence is x and the length of the string is n then, what is the answer to this problem? It is n - x as we need n - x insertions to make the remaining characters also palindrome.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "zzazz"", + "expected_output": "0", + "explanation": "The string "zzazz" is already palindrome we do not need any insertions." + }, + { + "example_num": 2, + "expected_input": "s = "mbadm"", + "expected_output": "2", + "explanation": "String can be "mbdadbm" or "mdbabdm"." + }, + { + "example_num": 3, + "expected_input": "s = "leetcode"", + "expected_output": "5", + "explanation": "Inserting 5 characters the string becomes "leetcodocteel"." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d78", + "questionid": 685, + "title": "Number of Operations to Make Network Connected", + "slug": "number-of-operations-to-make-network-connected", + "description": "There are n computers numbered from 0 to n - 1 connected by ethernet cables connections forming a network where connections[i] = [ai, bi] represents a connection between computers ai and bi. Any computer can reach any other computer directly or indirectly through the network. You are given an initial computer network connections. You can extract certain cables between two directly connected computers, and place them between any pair of disconnected computers to make them directly connected. Return the minimum number of times you need to do this in order to make all the computers connected. If it is not possible, return -1. ", + "category": [ + "Depth-First Search", + "Breadth-First Search", + "Union Find", + "Graph" + ], + "complexity": "Medium", + "successrate": 57.7, + "totalsubmissions": 127191, + "totalaccepted": 73342, + "likes": 2025, + "dislikes": 32, + "hints": "As long as there are at least (n - 1) connections, there is definitely a way to connect all computers. Use DFS to determine the number of isolated computer clusters.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 4, connections = [[0,1],[0,2],[1,2]]", + "expected_output": "1", + "explanation": "Remove cable between computer 1 and 2 and place between computers 1 and 3." + }, + { + "example_num": 2, + "expected_input": "n = 6, connections = [[0,1],[0,2],[0,3],[1,2],[1,3]]", + "expected_output": "2", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "n = 6, connections = [[0,1],[0,2],[0,3],[1,2]]", + "expected_output": "-1", + "explanation": "There are not enough cables." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d81", + "questionid": 694, + "title": "Remove Palindromic Subsequences", + "slug": "remove-palindromic-subsequences", + "description": "You are given a string s consisting only of letters 'a' and 'b'. In a single step you can remove one palindromic subsequence from s. Return the minimum number of steps to make the given string empty. A string is a subsequence of a given string if it is generated by deleting some characters of a given string without changing its order. Note that a subsequence does not necessarily need to be contiguous. A string is called palindrome if is one that reads the same backward as well as forward. ", + "category": [ + "Two Pointers", + "String" + ], + "complexity": "Easy", + "successrate": 69.5, + "totalsubmissions": 77351, + "totalaccepted": 53790, + "likes": 191, + "dislikes": 304, + "hints": "Use the fact that string contains only 2 characters. Are subsequences composed of only one type of letter always palindrome strings ?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "ababa"", + "expected_output": "1", + "explanation": "s is already a palindrome, so its entirety can be removed in a single step." + }, + { + "example_num": 2, + "expected_input": "s = "abb"", + "expected_output": "2", + "explanation": ""abb" -> "bb" -> "". \nRemove palindromic subsequence "a" then "bb"." + }, + { + "example_num": 3, + "expected_input": "s = "baabb"", + "expected_output": "2", + "explanation": ""baabb" -> "b" -> "". \nRemove palindromic subsequence "baab" then "b"." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d82", + "questionid": 695, + "title": "Filter Restaurants by Vegan-Friendly, Price and Distance", + "slug": "filter-restaurants-by-vegan-friendly-price-and-distance", + "description": "Given the array restaurants where  restaurants[i] = [idi, ratingi, veganFriendlyi, pricei, distancei]. You have to filter the restaurants using three filters. The veganFriendly filter will be either true (meaning you should only include restaurants with veganFriendlyi set to true) or false (meaning you can include any restaurant). In addition, you have the filters maxPrice and maxDistance which are the maximum value for price and distance of restaurants you should consider respectively. Return the array of restaurant IDs after filtering, ordered by rating from highest to lowest. For restaurants with the same rating, order them by id from highest to lowest. For simplicity veganFriendlyi and veganFriendly take value 1 when it is true, and 0 when it is false. ", + "category": [ + "Array", + "Sorting" + ], + "complexity": "Medium", + "successrate": 58.8, + "totalsubmissions": 36990, + "totalaccepted": 21750, + "likes": 208, + "dislikes": 174, + "hints": "Do the filtering and sort as said. Note that the id may not be the index in the array.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "restaurants = [[1,4,1,40,10],[2,8,0,50,5],[3,8,1,30,4],[4,10,0,10,3],[5,1,1,15,1]], veganFriendly = 1, maxPrice = 50, maxDistance = 10", + "expected_output": "[3,1,5] \nExplanation: \nThe restaurants are:\nRestaurant 1 [id=1, rating=4, veganFriendly=1, price=40, distance=10]\nRestaurant 2 [id=2, rating=8, veganFriendly=0, price=50, distance=5]\nRestaurant 3 [id=3, rating=8, veganFriendly=1, price=30, distance=4]\nRestaurant 4 [id=4, rating=10, veganFriendly=0, price=10, distance=3]\nRestaurant 5 [id=5, rating=1, veganFriendly=1, price=15, distance=1] \nAfter filter restaurants with veganFriendly = 1, maxPrice = 50 and maxDistance = 10 we have restaurant 3, restaurant 1 and restaurant 5 (ordered by rating from highest to lowest).", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "restaurants = [[1,4,1,40,10],[2,8,0,50,5],[3,8,1,30,4],[4,10,0,10,3],[5,1,1,15,1]], veganFriendly = 0, maxPrice = 50, maxDistance = 10", + "expected_output": "[4,3,2,1,5]", + "explanation": "The restaurants are the same as in example 1, but in this case the filter veganFriendly = 0, therefore all restaurants are considered." + }, + { + "example_num": 3, + "expected_input": "restaurants = [[1,4,1,40,10],[2,8,0,50,5],[3,8,1,30,4],[4,10,0,10,3],[5,1,1,15,1]], veganFriendly = 0, maxPrice = 30, maxDistance = 3", + "expected_output": "[4,5]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d88", + "questionid": 701, + "title": "Reduce Array Size to The Half", + "slug": "reduce-array-size-to-the-half", + "description": "You are given an integer array arr. You can choose a set of integers and remove all the occurrences of these integers in the array. Return the minimum size of the set so that at least half of the integers of the array are removed. ", + "category": [ + "Array", + "Hash Table", + "Greedy", + "Sorting", + "Heap (Priority Queue)" + ], + "complexity": "Medium", + "successrate": 68.4, + "totalsubmissions": 121669, + "totalaccepted": 83223, + "likes": 1228, + "dislikes": 84, + "hints": "Count the frequency of each integer in the array. Start with an empty set, add to the set the integer with the maximum frequency. Keep Adding the integer with the max frequency until you remove at least half of the integers.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "arr = [3,3,3,3,5,5,5,2,2,7]", + "expected_output": "2", + "explanation": "Choosing {3,7} will make the new array [5,5,5,2,2] which has size 5 (i.e equal to half of the size of the old array).\nPossible sets of size 2 are {3,5},{3,2},{5,2}.\nChoosing set {2,7} is not possible as it will make the new array [3,3,3,3,5,5,5] which has a size greater than half of the size of the old array." + }, + { + "example_num": 2, + "expected_input": "arr = [7,7,7,7,7,7]", + "expected_output": "1", + "explanation": "The only possible set you can choose is {7}. This will make the new array empty." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d8b", + "questionid": 704, + "title": "Maximum Students Taking Exam", + "slug": "maximum-students-taking-exam", + "description": "Given a m * n matrix seats  that represent seats distributions in a classroom. If a seat is broken, it is denoted by '#' character otherwise it is denoted by a '.' character. Students can see the answers of those sitting next to the left, right, upper left and upper right, but he cannot see the answers of the student sitting directly in front or behind him. Return the maximum number of students that can take the exam together without any cheating being possible.. Students must be placed in seats in good condition. ", + "category": [ + "Array", + "Dynamic Programming", + "Bit Manipulation", + "Matrix", + "Bitmask" + ], + "complexity": "Hard", + "successrate": 46.9, + "totalsubmissions": 21205, + "totalaccepted": 9937, + "likes": 554, + "dislikes": 11, + "hints": "Students in row i only can see exams in row i+1. Use Dynamic programming to compute the result given a (current row, bitmask people seated in previous row).", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "seats = [["#",".","#","#",".","#"],\n  [".","#","#","#","#","."],\n  ["#",".","#","#",".","#"]]", + "expected_output": "4", + "explanation": "Teacher can place 4 students in available seats so they don't cheat on the exam." + }, + { + "example_num": 2, + "expected_input": "seats = [[".","#"],\n  ["#","#"],\n  ["#","."],\n  ["#","#"],\n  [".","#"]]", + "expected_output": "3", + "explanation": "Place all students in available seats." + }, + { + "example_num": 3, + "expected_input": "seats = [["#",".",".",".","#"],\n  [".","#",".","#","."],\n  [".",".","#",".","."],\n  [".","#",".","#","."],\n  ["#",".",".",".","#"]]", + "expected_output": "10", + "explanation": "Place students in available seats in column 1, 3 and 5." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d52", + "questionid": 647, + "title": "Maximum Product of the Length of Two Palindromic Substrings", + "slug": "maximum-product-of-the-length-of-two-palindromic-substrings", + "description": "You are given a 0-indexed string s and are tasked with finding two non-intersecting palindromic substrings of odd length such that the product of their lengths is maximized. More formally, you want to choose four integers i, j, k, l such that 0 <= i <= j < k <= l < s.length and both the substrings s[i...j] and s[k...l] are palindromes and have odd lengths. s[i...j] denotes a substring from index i to index j inclusive. Return the maximum possible product of the lengths of the two non-intersecting palindromic substrings. A palindrome is a string that is the same forward and backward. A substring is a contiguous sequence of characters in a string. ", + "category": [ + "String", + "Rolling Hash", + "Hash Function" + ], + "complexity": "Hard", + "successrate": 29, + "totalsubmissions": 6832, + "totalaccepted": 1979, + "likes": 121, + "dislikes": 25, + "hints": "You can use Manacher's algorithm to get the maximum palindromic substring centered at each index After using Manacher's for each center use a line sweep from the center to the left and from the center to the right to find for each index the farthest center to it with distance ‰¤ palin[center] After that, find the maximum palindrome size for each prefix in the string and for each suffix and the answer would be max(prefix[i] * suffix[i + 1])", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "ababbb"", + "expected_output": "9", + "explanation": "Substrings "aba" and "bbb" are palindromes with odd length. product = 3 * 3 = 9." + }, + { + "example_num": 2, + "expected_input": "s = "zaaaxbbby"", + "expected_output": "9", + "explanation": "Substrings "aaa" and "bbb" are palindromes with odd length. product = 3 * 3 = 9." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d59", + "questionid": 654, + "title": "Minimum Number of Moves to Make Palindrome", + "slug": "minimum-number-of-moves-to-make-palindrome", + "description": "You are given a string s consisting only of lowercase English letters. In one move, you can select any two adjacent characters of s and swap them. Return the minimum number of moves needed to make s a palindrome. Note that the input will be generated such that s can always be converted to a palindrome. ", + "category": [ + "Two Pointers", + "String", + "Greedy", + "Binary Indexed Tree" + ], + "complexity": "Hard", + "successrate": 41.7, + "totalsubmissions": 11174, + "totalaccepted": 4659, + "likes": 194, + "dislikes": 50, + "hints": "Consider a greedy strategy. Let€™s start by making the leftmost and rightmost characters match with some number of swaps. If we figure out how to do that using the minimum number of swaps, then we can delete the leftmost and rightmost characters and solve the problem recursively.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "aabb"", + "expected_output": "2", + "explanation": "We can obtain two palindromes from s, "abba" and "baab". \n- We can obtain "abba" from s in 2 moves: "aabb" -> "abab" -> "abba".\n- We can obtain "baab" from s in 2 moves: "aabb" -> "abab" -> "baab".\nThus, the minimum number of moves needed to make s a palindrome is 2." + }, + { + "example_num": 2, + "expected_input": "s = "letelt"", + "expected_output": "2", + "explanation": "One of the palindromes we can obtain from s in 2 moves is "lettel".\nOne of the ways we can obtain it is "letelt" -> "letetl" -> "lettel".\nOther palindromes such as "tleelt" can also be obtained in 2 moves.\nIt can be shown that it is not possible to obtain a palindrome in less than 2 moves." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d62", + "questionid": 663, + "title": "Maximum Score Words Formed by Letters", + "slug": "maximum-score-words-formed-by-letters", + "description": "Given a list of words, list of  single letters (might be repeating) and score of every character. Return the maximum score of any valid set of words formed by using the given letters (words[i] cannot be used two or more times). It is not necessary to use all characters in letters and each letter can only be used once. Score of letters 'a', 'b', 'c', ... ,'z' is given by score[0], score[1], ... , score[25] respectively. ", + "category": [ + "Array", + "String", + "Dynamic Programming", + "Backtracking", + "Bit Manipulation", + "Bitmask" + ], + "complexity": "Hard", + "successrate": 72.1, + "totalsubmissions": 29091, + "totalaccepted": 20969, + "likes": 634, + "dislikes": 39, + "hints": "Note that words.length is small. This means you can iterate over every subset of words (2^N).", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "words = ["dog","cat","dad","good"], letters = ["a","a","c","d","d","d","g","o","o"], score = [1,0,9,5,0,0,3,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0]", + "expected_output": "23", + "explanation": "Score a=1, c=9, d=5, g=3, o=2\nGiven letters, we can form the words "dad" (5+1+5) and "good" (3+2+2+5) with a score of 23.\nWords "dad" and "dog" only get a score of 21." + }, + { + "example_num": 2, + "expected_input": "words = ["xxxz","ax","bx","cx"], letters = ["z","a","b","c","x","x","x"], score = [4,4,4,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,5,0,10]", + "expected_output": "27", + "explanation": "Score a=4, b=4, c=4, x=5, z=10\nGiven letters, we can form the words "ax" (4+5), "bx" (4+5) and "cx" (4+5) with a score of 27.\nWord "xxxz" only get a score of 25." + }, + { + "example_num": 3, + "expected_input": "words = ["leetcode"], letters = ["l","e","t","c","o","d"], score = [0,0,1,1,1,0,0,0,0,0,0,1,0,0,1,0,0,0,0,1,0,0,0,0,0,0]", + "expected_output": "0", + "explanation": "Letter "e" can only be used once." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d64", + "questionid": 665, + "title": "Maximum Value of K Coins From Piles", + "slug": "maximum-value-of-k-coins-from-piles", + "description": "There are n piles of coins on a table. Each pile consists of a positive number of coins of assorted denominations. In one move, you can choose any coin on top of any pile, remove it, and add it to your wallet. Given a list piles, where piles[i] is a list of integers denoting the composition of the ith pile from top to bottom, and a positive integer k, return the maximum total value of coins you can have in your wallet if you choose exactly k coins optimally. ", + "category": [ + "Array", + "Dynamic Programming", + "Prefix Sum" + ], + "complexity": "Hard", + "successrate": 48.8, + "totalsubmissions": 15910, + "totalaccepted": 7765, + "likes": 393, + "dislikes": 6, + "hints": "For each pile i, what will be the total value of coins we can collect if we choose the first j coins? How can we use dynamic programming to combine the results from different piles to find the most optimal answer?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "piles = [[1,100,3],[7,8,9]], k = 2", + "expected_output": "101", + "explanation": "The above diagram shows the different ways we can choose k coins.\nThe maximum total we can obtain is 101." + }, + { + "example_num": 2, + "expected_input": "piles = [[100],[100],[100],[100],[100],[100],[1,1,1,1,1,1,700]], k = 7", + "expected_output": "706\nExplanation:\nThe maximum total can be obtained if we choose all coins from the last pile.", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d6a", + "questionid": 671, + "title": "Minimum Number of Flips to Convert Binary Matrix to Zero Matrix", + "slug": "minimum-number-of-flips-to-convert-binary-matrix-to-zero-matrix", + "description": "Given a m x n binary matrix mat. In one step, you can choose one cell and flip it and all the four neighbors of it if they exist (Flip is changing 1 to 0 and 0 to 1). A pair of cells are called neighbors if they share one edge. Return the minimum number of steps required to convert mat to a zero matrix or -1 if you cannot. A binary matrix is a matrix with all cells equal to 0 or 1 only. A zero matrix is a matrix with all cells equal to 0. ", + "category": [ + "Array", + "Bit Manipulation", + "Breadth-First Search", + "Matrix" + ], + "complexity": "Hard", + "successrate": 72, + "totalsubmissions": 29496, + "totalaccepted": 21243, + "likes": 573, + "dislikes": 64, + "hints": "Flipping same index two times is like not flipping it at all. Each index can be flipped one time. Try all possible combinations. O(2^(n*m)).", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "mat = [[0,0],[0,1]]", + "expected_output": "3", + "explanation": "One possible solution is to flip (1, 0) then (0, 1) and finally (1, 1) as shown." + }, + { + "example_num": 2, + "expected_input": "mat = [[0]]", + "expected_output": "0", + "explanation": "Given matrix is a zero matrix. We do not need to change it." + }, + { + "example_num": 3, + "expected_input": "mat = [[1,0,0],[1,0,0]]", + "expected_output": "-1", + "explanation": "Given matrix cannot be a zero matrix." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d7a", + "questionid": 687, + "title": "Number of Steps to Reduce a Number to Zero", + "slug": "number-of-steps-to-reduce-a-number-to-zero", + "description": "Given an integer num, return the number of steps to reduce it to zero. In one step, if the current number is even, you have to divide it by 2, otherwise, you have to subtract 1 from it. ", + "category": [ + "Math", + "Bit Manipulation" + ], + "complexity": "Easy", + "successrate": 85.6, + "totalsubmissions": 294100, + "totalaccepted": 251848, + "likes": 1590, + "dislikes": 106, + "hints": "Simulate the process to get the final answer.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "num = 14", + "expected_output": "6", + "explanation": " \nStep 1) 14 is even; divide by 2 and obtain 7. \nStep 2) 7 is odd; subtract 1 and obtain 6.\nStep 3) 6 is even; divide by 2 and obtain 3. \nStep 4) 3 is odd; subtract 1 and obtain 2. \nStep 5) 2 is even; divide by 2 and obtain 1. \nStep 6) 1 is odd; subtract 1 and obtain 0." + }, + { + "example_num": 2, + "expected_input": "num = 8", + "expected_output": "4", + "explanation": " \nStep 1) 8 is even; divide by 2 and obtain 4. \nStep 2) 4 is even; divide by 2 and obtain 2. \nStep 3) 2 is even; divide by 2 and obtain 1. \nStep 4) 1 is odd; subtract 1 and obtain 0." + }, + { + "example_num": 3, + "expected_input": "num = 123", + "expected_output": "12", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d7d", + "questionid": 690, + "title": "Maximum 69 Number", + "slug": "maximum-69-number", + "description": "You are given a positive integer num consisting only of digits 6 and 9. Return the maximum number you can get by changing at most one digit (6 becomes 9, and 9 becomes 6). ", + "category": [ + "Math", + "Greedy" + ], + "complexity": "Easy", + "successrate": 78.9, + "totalsubmissions": 137155, + "totalaccepted": 108154, + "likes": 967, + "dislikes": 117, + "hints": "Convert the number in an array of its digits. Brute force on every digit to get the maximum number.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "num = 9669", + "expected_output": "9969", + "explanation": "Changing the first digit results in 6669.\nChanging the second digit results in 9969.\nChanging the third digit results in 9699.\nChanging the fourth digit results in 9666.\nThe maximum number is 9969." + }, + { + "example_num": 2, + "expected_input": "num = 9996", + "expected_output": "9999", + "explanation": "Changing the last digit 6 to 9 results in the maximum number." + }, + { + "example_num": 3, + "expected_input": "num = 9999", + "expected_output": "9999", + "explanation": "It is better not to apply any change." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d7f", + "questionid": 692, + "title": "Delete Leaves With a Given Value", + "slug": "delete-leaves-with-a-given-value", + "description": "Given a binary tree root and an integer target, delete all the leaf nodes with value target. Note that once you delete a leaf node with value target, if its parent node becomes a leaf node and has the value target, it should also be deleted (you need to continue doing that until you cannot). ", + "category": [ + "Tree", + "Depth-First Search", + "Binary Tree" + ], + "complexity": "Medium", + "successrate": 74.8, + "totalsubmissions": 87692, + "totalaccepted": 65562, + "likes": 1387, + "dislikes": 26, + "hints": "Use the DFS to reconstruct the tree such that no leaf node is equal to the target. If the leaf node is equal to the target, return an empty object instead.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [1,2,3,2,null,2,4], target = 2", + "expected_output": "[1,null,3,null,4]", + "explanation": "Leaf nodes in green with value (target = 2) are removed (Picture in left). \nAfter removing, new nodes become leaf nodes with value (target = 2) (Picture in center)." + }, + { + "example_num": 2, + "expected_input": "root = [1,3,3,3,2], target = 3", + "expected_output": "[1,3,null,null,2]", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "root = [1,2,null,2,null,2], target = 2", + "expected_output": "[1]", + "explanation": "Leaf nodes in green with value (target = 2) are removed at each step." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d80", + "questionid": 693, + "title": "Minimum Number of Taps to Open to Water a Garden", + "slug": "minimum-number-of-taps-to-open-to-water-a-garden", + "description": "There is a one-dimensional garden on the x-axis. The garden starts at the point 0 and ends at the point n. (i.e The length of the garden is n). There are n + 1 taps located at points [0, 1, ..., n] in the garden. Given an integer n and an integer array ranges of length n + 1 where ranges[i] (0-indexed) means the i-th tap can water the area [i - ranges[i], i + ranges[i]] if it was open. Return the minimum number of taps that should be open to water the whole garden, If the garden cannot be watered return -1. ", + "category": [ + "Array", + "Dynamic Programming", + "Greedy" + ], + "complexity": "Hard", + "successrate": 48.1, + "totalsubmissions": 113168, + "totalaccepted": 54380, + "likes": 1441, + "dislikes": 106, + "hints": "Create intervals of the area covered by each tap, sort intervals by the left end. We need to cover the interval [0, n]. we can start with the first interval and out of all intervals that intersect with it we choose the one that covers the farthest point to the right. What if there is a gap between intervals that is not covered ? we should stop and return -1 as there is some interval that cannot be covered.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 5, ranges = [3,4,1,1,0,0]", + "expected_output": "1", + "explanation": "The tap at point 0 can cover the interval [-3,3]\nThe tap at point 1 can cover the interval [-3,5]\nThe tap at point 2 can cover the interval [1,3]\nThe tap at point 3 can cover the interval [2,4]\nThe tap at point 4 can cover the interval [4,4]\nThe tap at point 5 can cover the interval [5,5]\nOpening Only the second tap will water the whole garden [0,5]" + }, + { + "example_num": 2, + "expected_input": "n = 3, ranges = [0,0,0,0]", + "expected_output": "-1", + "explanation": "Even if you activate all the four taps you cannot water the whole garden." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d87", + "questionid": 700, + "title": "Count All Valid Pickup and Delivery Options", + "slug": "count-all-valid-pickup-and-delivery-options", + "description": "Given n orders, each order consist in pickup and delivery services. Count all valid pickup/delivery possible sequences such that delivery(i) is always after of pickup(i). Since the answer may be too large, return it modulo 10^9 + 7. ", + "category": [ + "Math", + "Dynamic Programming", + "Combinatorics" + ], + "complexity": "Hard", + "successrate": 63.4, + "totalsubmissions": 80796, + "totalaccepted": 51194, + "likes": 1518, + "dislikes": 137, + "hints": "Use the permutation and combination theory to add one (P, D) pair each time until n pairs.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 1", + "expected_output": "1", + "explanation": "Unique order (P1, D1), Delivery 1 always is after of Pickup 1." + }, + { + "example_num": 2, + "expected_input": "n = 2", + "expected_output": "6", + "explanation": "All possible orders: \n(P1,P2,D1,D2), (P1,P2,D2,D1), (P1,D1,P2,D2), (P2,P1,D1,D2), (P2,P1,D2,D1) and (P2,D2,P1,D1).\nThis is an invalid order (P1,D2,P2,D1) because Pickup 2 is after of Delivery 2." + }, + { + "example_num": 3, + "expected_input": "n = 3", + "expected_output": "90", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d4c", + "questionid": 641, + "title": "Get Equal Substrings Within Budget", + "slug": "get-equal-substrings-within-budget", + "description": "You are given two strings s and t of the same length and an integer maxCost. You want to change s to t. Changing the ith character of s to ith character of t costs |s[i] - t[i]| (i.e., the absolute difference between the ASCII values of the characters). Return the maximum length of a substring of s that can be changed to be the same as the corresponding substring of t with a cost less than or equal to maxCost. If there is no substring from s that can be changed to its corresponding substring from t, return 0. ", + "category": [ + "String", + "Binary Search", + "Sliding Window", + "Prefix Sum" + ], + "complexity": "Medium", + "successrate": 46.5, + "totalsubmissions": 61338, + "totalaccepted": 28510, + "likes": 632, + "dislikes": 43, + "hints": "Calculate the differences between a[i] and b[i]. Use a sliding window to track the longest valid substring.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "abcd", t = "bcdf", maxCost = 3", + "expected_output": "3", + "explanation": ""abc" of s can change to "bcd".\nThat costs 3, so the maximum length is 3." + }, + { + "example_num": 2, + "expected_input": "s = "abcd", t = "cdef", maxCost = 3", + "expected_output": "1", + "explanation": "Each character in s costs 2 to change to character in t, so the maximum length is 1." + }, + { + "example_num": 3, + "expected_input": "s = "abcd", t = "acde", maxCost = 0", + "expected_output": "1", + "explanation": "You cannot make any change, so the maximum length is 1." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d4d", + "questionid": 642, + "title": "Where Will the Ball Fall", + "slug": "where-will-the-ball-fall", + "description": "You have a 2-D grid of size m x n representing a box, and you have n balls. The box is open on the top and bottom sides. Each cell in the box has a diagonal board spanning two corners of the cell that can redirect a ball to the right or to the left. We drop one ball at the top of each column of the box. Each ball can get stuck in the box or fall out of the bottom. A ball gets stuck if it hits a \"V\" shaped pattern between two boards or if a board redirects the ball into either wall of the box. Return an array answer of size n where answer[i] is the column that the ball falls out of at the bottom after dropping the ball from the ith column at the top, or -1 if the ball gets stuck in the box. ", + "category": [ + "Array", + "Dynamic Programming", + "Depth-First Search", + "Matrix", + "Simulation" + ], + "complexity": "Medium", + "successrate": 66.5, + "totalsubmissions": 40091, + "totalaccepted": 26652, + "likes": 744, + "dislikes": 54, + "hints": "Use DFS. Traverse the path of the ball downwards until you reach the bottom or get stuck.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "grid = [[1,1,1,-1,-1],[1,1,1,-1,-1],[-1,-1,-1,1,1],[1,1,1,1,-1],[-1,-1,-1,-1,-1]]", + "expected_output": "[1,-1,-1,-1,-1]", + "explanation": "This example is shown in the photo.\nBall b0 is dropped at column 0 and falls out of the box at column 1.\nBall b1 is dropped at column 1 and will get stuck in the box between column 2 and 3 and row 1.\nBall b2 is dropped at column 2 and will get stuck on the box between column 2 and 3 and row 0.\nBall b3 is dropped at column 3 and will get stuck on the box between column 2 and 3 and row 0.\nBall b4 is dropped at column 4 and will get stuck on the box between column 2 and 3 and row 1." + }, + { + "example_num": 2, + "expected_input": "grid = [[-1]]", + "expected_output": "[-1]", + "explanation": "The ball gets stuck against the left wall." + }, + { + "example_num": 3, + "expected_input": "grid = [[1,1,1,1,1,1],[-1,-1,-1,-1,-1,-1],[1,1,1,1,1,1],[-1,-1,-1,-1,-1,-1]]", + "expected_output": "[0,1,2,3,4,-1]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d4e", + "questionid": 643, + "title": "Path with Maximum Probability", + "slug": "path-with-maximum-probability", + "description": "You are given an undirected weighted graph of n nodes (0-indexed), represented by an edge list where edges[i] = [a, b] is an undirected edge connecting the nodes a and b with a probability of success of traversing that edge succProb[i]. Given two nodes start and end, find the path with the maximum probability of success to go from start to end and return its success probability. If there is no path from start to end, return 0. Your answer will be accepted if it differs from the correct answer by at most 1e-5. ", + "category": [ + "Graph", + "Heap (Priority Queue)", + "Shortest Path" + ], + "complexity": "Medium", + "successrate": 46.4, + "totalsubmissions": 89945, + "totalaccepted": 41690, + "likes": 1141, + "dislikes": 25, + "hints": "Multiplying probabilities will result in precision errors. Take log probabilities to sum up numbers instead of multiplying them. Use Dijkstra's algorithm to find the minimum path between the two nodes after negating all costs.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.2], start = 0, end = 2", + "expected_output": "0.25000", + "explanation": " There are two paths from start to end, one having a probability of success = 0.2 and the other has 0.5 * 0.5 = 0.25." + }, + { + "example_num": 2, + "expected_input": "n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.3], start = 0, end = 2", + "expected_output": "0.30000", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "n = 3, edges = [[0,1]], succProb = [0.5], start = 0, end = 2", + "expected_output": "0.00000", + "explanation": " There is no path between 0 and 2." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d50", + "questionid": 645, + "title": "Longest Arithmetic Subsequence of Given Difference", + "slug": "longest-arithmetic-subsequence-of-given-difference", + "description": "Given an integer array arr and an integer difference, return the length of the longest subsequence in arr which is an arithmetic sequence such that the difference between adjacent elements in the subsequence equals difference. A subsequence is a sequence that can be derived from arr by deleting some or no elements without changing the order of the remaining elements. ", + "category": [ + "Array", + "Hash Table", + "Dynamic Programming" + ], + "complexity": "Medium", + "successrate": 51.3, + "totalsubmissions": 90972, + "totalaccepted": 46671, + "likes": 983, + "dislikes": 42, + "hints": "Use dynamic programming. Let dp[i] be the maximum length of a subsequence of the given difference whose last element is i. dp[i] = 1 + dp[i-k]", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "arr = [1,2,3,4], difference = 1", + "expected_output": "4\nExplanation: The longest arithmetic subsequence is [1,2,3,4].", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "arr = [1,3,5,7], difference = 1", + "expected_output": "1\nExplanation: The longest arithmetic subsequence is any single element.", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "arr = [1,5,7,8,5,3,4,2,1], difference = -2", + "expected_output": "4\nExplanation: The longest arithmetic subsequence is [7,5,3,1].", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d51", + "questionid": 646, + "title": "Maximum Candies Allocated to K Children", + "slug": "maximum-candies-allocated-to-k-children", + "description": "You are given a 0-indexed integer array candies. Each element in the array denotes a pile of candies of size candies[i]. You can divide each pile into any number of sub piles, but you cannot merge two piles together. You are also given an integer k. You should allocate piles of candies to k children such that each child gets the same number of candies. Each child can take at most one pile of candies and some piles of candies may go unused. Return the maximum number of candies each child can get. ", + "category": [ + "Array", + "Binary Search" + ], + "complexity": "Medium", + "successrate": 34.6, + "totalsubmissions": 39951, + "totalaccepted": 13813, + "likes": 320, + "dislikes": 20, + "hints": "For a fixed number of candies c, how can you check if each child can get c candies? Use binary search to find the maximum c as the answer.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "candies = [5,8,6], k = 3", + "expected_output": "5", + "explanation": "We can divide candies[1] into 2 piles of size 5 and 3, and candies[2] into 2 piles of size 5 and 1. We now have five piles of candies of sizes 5, 5, 3, 5, and 1. We can allocate the 3 piles of size 5 to 3 children. It can be proven that each child cannot receive more than 5 candies." + }, + { + "example_num": 2, + "expected_input": "candies = [2,5], k = 11", + "expected_output": "0", + "explanation": "There are 11 children but only 7 candies in total, so it is impossible to ensure each child receives at least one candy. Thus, each child gets no candy and the answer is 0." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d54", + "questionid": 649, + "title": "Queens That Can Attack the King", + "slug": "queens-that-can-attack-the-king", + "description": "On an 8x8 chessboard, there can be multiple Black Queens and one White King. Given an array of integer coordinates queens that represents the positions of the Black Queens, and a pair of coordinates king that represent the position of the White King, return the coordinates of all the queens (in any order) that can attack the King. ", + "category": [ + "Array", + "Matrix", + "Simulation" + ], + "complexity": "Medium", + "successrate": 71.1, + "totalsubmissions": 44750, + "totalaccepted": 31819, + "likes": 674, + "dislikes": 124, + "hints": "Check 8 directions around the King. Find the nearest queen in each direction.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "queens = [[0,1],[1,0],[4,0],[0,4],[3,3],[2,4]], king = [0,0]", + "expected_output": "[[0,1],[1,0],[3,3]]", + "explanation": "The diagram above shows the three queens that can directly attack the king and the three queens that cannot attack the king (i.e., marked with red dashes)." + }, + { + "example_num": 2, + "expected_input": "queens = [[0,0],[1,1],[2,2],[3,4],[3,5],[4,4],[4,5]], king = [3,3]", + "expected_output": "[[2,2],[3,4],[4,4]]", + "explanation": "The diagram above shows the three queens that can directly attack the king and the three queens that cannot attack the king (i.e., marked with red dashes)." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d57", + "questionid": 652, + "title": "Check If It Is a Straight Line", + "slug": "check-if-it-is-a-straight-line", + "description": "You are given an array coordinates, coordinates[i] = [x, y], where [x, y] represents the coordinate of a point. Check if these points make a straight line in the XY plane. ", + "category": [ + "Array", + "Math", + "Geometry" + ], + "complexity": "Easy", + "successrate": 41.9, + "totalsubmissions": 268240, + "totalaccepted": 112522, + "likes": 871, + "dislikes": 128, + "hints": "If there're only 2 points, return true. Check if all other points lie on the line defined by the first 2 points. Use cross product to check collinearity.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "coordinates = [[1,2],[2,3],[3,4],[4,5],[5,6],[6,7]]", + "expected_output": "true", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "coordinates = [[1,1],[2,2],[3,4],[4,5],[5,6],[7,7]]", + "expected_output": "false", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d5b", + "questionid": 656, + "title": "Tiling a Rectangle with the Fewest Squares", + "slug": "tiling-a-rectangle-with-the-fewest-squares", + "description": "Given a rectangle of size n x m, return the minimum number of integer-sided squares that tile the rectangle. ", + "category": [ + "Dynamic Programming", + "Backtracking" + ], + "complexity": "Hard", + "successrate": 53.7, + "totalsubmissions": 30316, + "totalaccepted": 16265, + "likes": 460, + "dislikes": 428, + "hints": "Can you use backtracking to solve this problem ?. Suppose you've placed a bunch of squares. Where is the natural spot to place the next square ?. The maximum number of squares to be placed will be ‰¤ max(n,m).", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 2, m = 3", + "expected_output": "3", + "explanation": "3 squares are necessary to cover the rectangle.\n2 (squares of 1x1)\n1 (square of 2x2)" + }, + { + "example_num": 2, + "expected_input": "n = 5, m = 8", + "expected_output": "5", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "n = 11, m = 13", + "expected_output": "6", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d5d", + "questionid": 658, + "title": "Maximum Height by Stacking Cuboids ", + "slug": "maximum-height-by-stacking-cuboids", + "description": "Given n cuboids where the dimensions of the ith cuboid is cuboids[i] = [widthi, lengthi, heighti] (0-indexed). Choose a subset of cuboids and place them on each other. You can place cuboid i on cuboid j if widthi <= widthj and lengthi <= lengthj and heighti <= heightj. You can rearrange any cuboid's dimensions by rotating it to put it on another cuboid. Return the maximum height of the stacked cuboids. ", + "category": [ + "Array", + "Dynamic Programming", + "Sorting" + ], + "complexity": "Hard", + "successrate": 53.6, + "totalsubmissions": 20099, + "totalaccepted": 10767, + "likes": 477, + "dislikes": 16, + "hints": "Does the dynamic programming sound like the right algorithm after sorting? Let's say box1 can be placed on top of box2. No matter what orientation box2 is in, we can rotate box1 so that it can be placed on top. Why don't we orient everything such that height is the biggest?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "cuboids = [[50,45,20],[95,37,53],[45,23,12]]", + "expected_output": "190", + "explanation": "Cuboid 1 is placed on the bottom with the 53x37 side facing down with height 95.\nCuboid 0 is placed next with the 45x20 side facing down with height 50.\nCuboid 2 is placed next with the 23x12 side facing down with height 45.\nThe total height is 95 + 50 + 45 = 190." + }, + { + "example_num": 2, + "expected_input": "cuboids = [[38,25,45],[76,35,3]]", + "expected_output": "76", + "explanation": "You can't place any of the cuboids on the other.\nWe choose cuboid 1 and rotate it so that the 35x3 side is facing down and its height is 76." + }, + { + "example_num": 3, + "expected_input": "cuboids = [[7,11,17],[7,17,11],[11,7,17],[11,17,7],[17,7,11],[17,11,7]]", + "expected_output": "102", + "explanation": "After rearranging the cuboids, you can see that all cuboids have the same dimension.\nYou can place the 11x7 side down on all cuboids so their heights are 17.\nThe maximum height of stacked cuboids is 6 * 17 = 102." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d65", + "questionid": 666, + "title": "Count Servers that Communicate", + "slug": "count-servers-that-communicate", + "description": "You are given a map of a server center, represented as a m * n integer matrix grid, where 1 means that on that cell there is a server and 0 means that it is no server. Two servers are said to communicate if they are on the same row or on the same column.\n\nReturn the number of servers that communicate with any other server. ", + "category": [ + "Array", + "Depth-First Search", + "Breadth-First Search", + "Union Find", + "Matrix", + "Counting" + ], + "complexity": "Medium", + "successrate": 58.3, + "totalsubmissions": 68986, + "totalaccepted": 40205, + "likes": 849, + "dislikes": 73, + "hints": "Store number of computer in each row and column. Count all servers that are not isolated.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "grid = [[1,0],[0,1]]", + "expected_output": "0\nExplanation: No servers can communicate with others.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "grid = [[1,0],[1,1]]", + "expected_output": "3\nExplanation: All three servers can communicate with at least one other server.", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "grid = [[1,1,0,0],[0,0,1,0],[0,0,1,0],[0,0,0,1]]", + "expected_output": "4\nExplanation: The two servers in the first row can communicate with each other. The two servers in the third column can communicate with each other. The server at right bottom corner can't communicate with any other server.", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d66", + "questionid": 667, + "title": "Search Suggestions System", + "slug": "search-suggestions-system", + "description": "You are given an array of strings products and a string searchWord. Design a system that suggests at most three product names from products after each character of searchWord is typed. Suggested products should have common prefix with searchWord. If there are more than three products with a common prefix return the three lexicographically minimums products. Return a list of lists of the suggested products after each character of searchWord is typed. ", + "category": [ + "Array", + "String", + "Trie" + ], + "complexity": "Medium", + "successrate": 65.4, + "totalsubmissions": 229349, + "totalaccepted": 149953, + "likes": 2209, + "dislikes": 132, + "hints": "Brute force is a good choice because length of the string is ‰¤ 1000. Binary search the answer. Use Trie data structure to store the best three matching. Traverse the Trie.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "products = ["mobile","mouse","moneypot","monitor","mousepad"], searchWord = "mouse"", + "expected_output": "[["mobile","moneypot","monitor"],["mobile","moneypot","monitor"],["mouse","mousepad"],["mouse","mousepad"],["mouse","mousepad"]]", + "explanation": "products sorted lexicographically = ["mobile","moneypot","monitor","mouse","mousepad"].\nAfter typing m and mo all products match and we show user ["mobile","moneypot","monitor"].\nAfter typing mou, mous and mouse the system suggests ["mouse","mousepad"]." + }, + { + "example_num": 2, + "expected_input": "products = ["havana"], searchWord = "havana"", + "expected_output": "[["havana"],["havana"],["havana"],["havana"],["havana"],["havana"]]", + "explanation": "The only word "havana" will be always suggested while typing the search word." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d6d", + "questionid": 674, + "title": "Shortest Path in a Grid with Obstacles Elimination", + "slug": "shortest-path-in-a-grid-with-obstacles-elimination", + "description": "You are given an m x n integer matrix grid where each cell is either 0 (empty) or 1 (obstacle). You can move up, down, left, or right from and to an empty cell in one step. Return the minimum number of steps to walk from the upper left corner (0, 0) to the lower right corner (m - 1, n - 1) given that you can eliminate at most k obstacles. If it is not possible to find such walk return -1. ", + "category": [ + "Array", + "Breadth-First Search", + "Matrix" + ], + "complexity": "Hard", + "successrate": 43.6, + "totalsubmissions": 208324, + "totalaccepted": 90733, + "likes": 2097, + "dislikes": 39, + "hints": "Use BFS. BFS on (x,y,r) x,y is coordinate, r is remain number of obstacles you can remove.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "grid = [[0,0,0],[1,1,0],[0,0,0],[0,1,1],[0,0,0]], k = 1", + "expected_output": "6", + "explanation": "The shortest path without eliminating any obstacle is 10.\nThe shortest path with one obstacle elimination at position (3,2) is 6. Such path is (0,0) -> (0,1) -> (0,2) -> (1,2) -> (2,2) -> (3,2) -> (4,2)." + }, + { + "example_num": 2, + "expected_input": "grid = [[0,1,1],[1,1,1],[1,0,0]], k = 1", + "expected_output": "-1", + "explanation": "We need to eliminate at least two obstacles to find such a walk." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d6f", + "questionid": 676, + "title": "Divide Array in Sets of K Consecutive Numbers", + "slug": "divide-array-in-sets-of-k-consecutive-numbers", + "description": "Given an array of integers nums and a positive integer k, check whether it is possible to divide this array into sets of k consecutive numbers. Return true if it is possible. Otherwise, return false. ", + "category": [ + "Array", + "Hash Table", + "Greedy", + "Sorting" + ], + "complexity": "Medium", + "successrate": 56.5, + "totalsubmissions": 104160, + "totalaccepted": 58857, + "likes": 1067, + "dislikes": 81, + "hints": "If the smallest number in the possible-to-split array is V, then numbers V+1, V+2, ... V+k-1 must contain there as well. You can iteratively find k sets and remove them from array until it becomes empty. Failure to do so would mean that array is unsplittable.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,2,3,3,4,4,5,6], k = 4", + "expected_output": "true", + "explanation": "Array can be divided into [1,2,3,4] and [3,4,5,6]." + }, + { + "example_num": 2, + "expected_input": "nums = [3,2,1,2,3,4,3,4,5,9,10,11], k = 3", + "expected_output": "true", + "explanation": "Array can be divided into [1,2,3] , [2,3,4] , [3,4,5] and [9,10,11]." + }, + { + "example_num": 3, + "expected_input": "nums = [1,2,3,4], k = 3", + "expected_output": "false", + "explanation": "Each array should be divided in subarrays of size 3." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d73", + "questionid": 680, + "title": "All Ancestors of a Node in a Directed Acyclic Graph", + "slug": "all-ancestors-of-a-node-in-a-directed-acyclic-graph", + "description": "You are given a positive integer n representing the number of nodes of a Directed Acyclic Graph (DAG). The nodes are numbered from 0 to n - 1 (inclusive). You are also given a 2D integer array edges, where edges[i] = [fromi, toi] denotes that there is a unidirectional edge from fromi to toi in the graph. Return a list answer, where answer[i] is the list of ancestors of the ith node, sorted in ascending order. A node u is an ancestor of another node v if u can reach v via a set of edges. ", + "category": [ + "Depth-First Search", + "Breadth-First Search", + "Graph", + "Topological Sort" + ], + "complexity": "Medium", + "successrate": 46.1, + "totalsubmissions": 20517, + "totalaccepted": 9460, + "likes": 351, + "dislikes": 4, + "hints": "Consider how reversing each edge of the graph can help us. How can performing BFS/DFS on the reversed graph help us find the ancestors of every node?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 8, edgeList = [[0,3],[0,4],[1,3],[2,4],[2,7],[3,5],[3,6],[3,7],[4,6]]", + "expected_output": "[[],[],[],[0,1],[0,2],[0,1,3],[0,1,2,3,4],[0,1,2,3]]", + "explanation": "The above diagram represents the input graph.\n- Nodes 0, 1, and 2 do not have any ancestors.\n- Node 3 has two ancestors 0 and 1.\n- Node 4 has two ancestors 0 and 2.\n- Node 5 has three ancestors 0, 1, and 3.\n- Node 6 has five ancestors 0, 1, 2, 3, and 4.\n- Node 7 has four ancestors 0, 1, 2, and 3." + }, + { + "example_num": 2, + "expected_input": "n = 5, edgeList = [[0,1],[0,2],[0,3],[0,4],[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]", + "expected_output": "[[],[0],[0,1],[0,1,2],[0,1,2,3]]", + "explanation": "The above diagram represents the input graph.\n- Node 0 does not have any ancestor.\n- Node 1 has one ancestor 0.\n- Node 2 has two ancestors 0 and 1.\n- Node 3 has three ancestors 0, 1, and 2.\n- Node 4 has four ancestors 0, 1, 2, and 3." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d83", + "questionid": 696, + "title": "Find the City With the Smallest Number of Neighbors at a Threshold Distance", + "slug": "find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance", + "description": "There are n cities numbered from 0 to n-1. Given the array edges where edges[i] = [fromi, toi, weighti] represents a bidirectional and weighted edge between cities fromi and toi, and given the integer distanceThreshold. Return the city with the smallest number of cities that are reachable through some path and whose distance is at most distanceThreshold, If there are multiple such cities, return the city with the greatest number. Notice that the distance of a path connecting cities i and j is equal to the sum of the edges' weights along that path. ", + "category": [ + "Dynamic Programming", + "Graph", + "Shortest Path" + ], + "complexity": "Medium", + "successrate": 51.1, + "totalsubmissions": 74264, + "totalaccepted": 37977, + "likes": 1113, + "dislikes": 56, + "hints": "Use Floyd-Warshall's algorithm to compute any-point to any-point distances. (Or can also do Dijkstra from every node due to the weights are non-negative). For each city calculate the number of reachable cities within the threshold, then search for the optimal city.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 4, edges = [[0,1,3],[1,2,1],[1,3,4],[2,3,1]], distanceThreshold = 4", + "expected_output": "3\nExplanation: The figure above describes the graph. \nThe neighboring cities at a distanceThreshold = 4 for each city are:\nCity 0 -> [City 1, City 2] \nCity 1 -> [City 0, City 2, City 3] \nCity 2 -> [City 0, City 1, City 3] \nCity 3 -> [City 1, City 2] \nCities 0 and 3 have 2 neighboring cities at a distanceThreshold = 4, but we have to return city 3 since it has the greatest number.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "n = 5, edges = [[0,1,2],[0,4,8],[1,2,3],[1,4,2],[2,3,1],[3,4,1]], distanceThreshold = 2", + "expected_output": "0\nExplanation: The figure above describes the graph. \nThe neighboring cities at a distanceThreshold = 2 for each city are:\nCity 0 -> [City 1] \nCity 1 -> [City 0, City 4] \nCity 2 -> [City 3, City 4] \nCity 3 -> [City 2, City 4]\nCity 4 -> [City 1, City 2, City 3] \nThe city 0 has 1 neighboring city at a distanceThreshold = 2.", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d84", + "questionid": 697, + "title": "Minimum Difficulty of a Job Schedule", + "slug": "minimum-difficulty-of-a-job-schedule", + "description": "You want to schedule a list of jobs in d days. Jobs are dependent (i.e To work on the ith job, you have to finish all the jobs j where 0 <= j < i). You have to finish at least one task every day. The difficulty of a job schedule is the sum of difficulties of each day of the d days. The difficulty of a day is the maximum difficulty of a job done on that day. You are given an integer array jobDifficulty and an integer d. The difficulty of the ith job is jobDifficulty[i]. Return the minimum difficulty of a job schedule. If you cannot find a schedule for the jobs return -1. ", + "category": [ + "Array", + "Dynamic Programming" + ], + "complexity": "Hard", + "successrate": 56.5, + "totalsubmissions": 119707, + "totalaccepted": 67682, + "likes": 1212, + "dislikes": 140, + "hints": "Use DP. Try to cut the array into d non-empty sub-arrays. Try all possible cuts for the array. Use dp[i][j] where DP states are i the index of the last cut and j the number of remaining cuts. Complexity is O(n * n * d).", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "jobDifficulty = [6,5,4,3,2,1], d = 2", + "expected_output": "7", + "explanation": "First day you can finish the first 5 jobs, total difficulty = 6.\nSecond day you can finish the last job, total difficulty = 1.\nThe difficulty of the schedule = 6 + 1 = 7" + }, + { + "example_num": 2, + "expected_input": "jobDifficulty = [9,9,9], d = 4", + "expected_output": "-1", + "explanation": "If you finish a job per day you will still have a free day. you cannot find a schedule for the given jobs." + }, + { + "example_num": 3, + "expected_input": "jobDifficulty = [1,1,1], d = 3", + "expected_output": "3", + "explanation": "The schedule is one job per day. total difficulty will be 3." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d85", + "questionid": 698, + "title": "Sort Integers by The Number of 1 Bits", + "slug": "sort-integers-by-the-number-of-1-bits", + "description": "You are given an integer array arr. Sort the integers in the array in ascending order by the number of 1's in their binary representation and in case of two or more integers have the same number of 1's you have to sort them in ascending order. Return the array after sorting it. ", + "category": [ + "Array", + "Bit Manipulation", + "Sorting", + "Counting" + ], + "complexity": "Easy", + "successrate": 71.4, + "totalsubmissions": 91233, + "totalaccepted": 65098, + "likes": 988, + "dislikes": 45, + "hints": "Simulate the problem. Count the number of 1's in the binary representation of each integer. Sort by the number of 1's ascending and by the value in case of tie.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "arr = [0,1,2,3,4,5,6,7,8]", + "expected_output": "[0,1,2,4,8,3,5,6,7]\nExplantion: [0] is the only integer with 0 bits.\n[1,2,4,8] all have 1 bit.\n[3,5,6] have 2 bits.\n[7] has 3 bits.\nThe sorted array by bits is [0,1,2,4,8,3,5,6,7]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "arr = [1024,512,256,128,64,32,16,8,4,2,1]", + "expected_output": "[1,2,4,8,16,32,64,128,256,512,1024]\nExplantion: All integers have 1 bit in the binary representation, you should just sort them in ascending order.", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d89", + "questionid": 702, + "title": "Maximum Product of Splitted Binary Tree", + "slug": "maximum-product-of-splitted-binary-tree", + "description": "Given the root of a binary tree, split the binary tree into two subtrees by removing one edge such that the product of the sums of the subtrees is maximized. Return the maximum product of the sums of the two subtrees. Since the answer may be too large, return it modulo 109 + 7. Note that you need to maximize the answer before taking the mod and not after taking it. ", + "category": [ + "Tree", + "Depth-First Search", + "Binary Tree" + ], + "complexity": "Medium", + "successrate": 42.9, + "totalsubmissions": 130468, + "totalaccepted": 55984, + "likes": 1221, + "dislikes": 55, + "hints": "If we know the sum of a subtree, the answer is max( (total_sum - subtree_sum) * subtree_sum) in each node.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [1,2,3,4,5,6]", + "expected_output": "110", + "explanation": "Remove the red edge and get 2 binary trees with sum 11 and 10. Their product is 110 (11*10)" + }, + { + "example_num": 2, + "expected_input": "root = [1,null,2,3,4,null,null,5,6]", + "expected_output": "90", + "explanation": "Remove the red edge and get 2 binary trees with sum 15 and 6.Their product is 90 (15*6)" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d8a", + "questionid": 703, + "title": "Minimum Number of Steps to Make Two Strings Anagram", + "slug": "minimum-number-of-steps-to-make-two-strings-anagram", + "description": "You are given two strings of the same length s and t. In one step you can choose any character of t and replace it with another character. Return the minimum number of steps to make t an anagram of s. An Anagram of a string is a string that contains the same characters with a different (or the same) ordering. ", + "category": [ + "Hash Table", + "String", + "Counting" + ], + "complexity": "Medium", + "successrate": 76.3, + "totalsubmissions": 115048, + "totalaccepted": 87802, + "likes": 1203, + "dislikes": 56, + "hints": "Count the frequency of characters of each string. Loop over all characters if the frequency of a character in t is less than the frequency of the same character in s then add the difference between the frequencies to the answer.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "bab", t = "aba"", + "expected_output": "1", + "explanation": "Replace the first 'a' in t with b, t = "bba" which is anagram of s." + }, + { + "example_num": 2, + "expected_input": "s = "leetcode", t = "practice"", + "expected_output": "5", + "explanation": "Replace 'p', 'r', 'a', 'i' and 'c' from t with proper characters to make t anagram of s." + }, + { + "example_num": 3, + "expected_input": "s = "anagram", t = "mangaar"", + "expected_output": "0", + "explanation": ""anagram" and "mangaar" are anagrams." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d8f", + "questionid": 708, + "title": "How Many Numbers Are Smaller Than the Current Number", + "slug": "how-many-numbers-are-smaller-than-the-current-number", + "description": "Given the array nums, for each nums[i] find out how many numbers in the array are smaller than it. That is, for each nums[i] you have to count the number of valid j's such that j != i and nums[j] < nums[i]. Return the answer in an array. ", + "category": [ + "Array", + "Hash Table", + "Sorting", + "Counting" + ], + "complexity": "Easy", + "successrate": 86.3, + "totalsubmissions": 348022, + "totalaccepted": 300430, + "likes": 3039, + "dislikes": 62, + "hints": "Brute force for each array element. In order to improve the time complexity, we can sort the array and get the answer for each array element.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [8,1,2,2,3]", + "expected_output": "[4,0,1,1,3]", + "explanation": "For nums[0]=8 there exist four smaller numbers than it (1, 2, 2 and 3). \nFor nums[1]=1 does not exist any smaller number than it.\nFor nums[2]=2 there exist one smaller number than it (1). \nFor nums[3]=2 there exist one smaller number than it (1). \nFor nums[4]=3 there exist three smaller numbers than it (1, 2 and 2)." + }, + { + "example_num": 2, + "expected_input": "nums = [6,5,4,8]", + "expected_output": "[2,1,0,3]", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "nums = [7,7,7,7]", + "expected_output": "[0,0,0,0]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d8c", + "questionid": 705, + "title": "Find the Longest Substring Containing Vowels in Even Counts", + "slug": "find-the-longest-substring-containing-vowels-in-even-counts", + "description": "Given the string s, return the size of the longest substring containing each vowel an even number of times. That is, 'a', 'e', 'i', 'o', and 'u' must appear an even number of times. ", + "category": [ + "Hash Table", + "String", + "Bit Manipulation", + "Prefix Sum" + ], + "complexity": "Medium", + "successrate": 62.6, + "totalsubmissions": 29156, + "totalaccepted": 18248, + "likes": 1092, + "dislikes": 41, + "hints": "Represent the counts (odd or even) of vowels with a bitmask. Precompute the prefix xor for the bitmask of vowels and then get the longest valid substring.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "eleetminicoworoep"", + "expected_output": "13\nExplanation: The longest substring is "leetminicowor" which contains two each of the vowels: e, i and o and zero of the vowels: a and u.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "s = "leetcodeisgreat"", + "expected_output": "5", + "explanation": "The longest substring is "leetc" which contains two e's." + }, + { + "example_num": 3, + "expected_input": "s = "bcbcbc"", + "expected_output": "6", + "explanation": "In this case, the given string "bcbcbc" is the longest because all vowels: a, e, i, o and u appear zero times." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d8e", + "questionid": 707, + "title": "Maximum Number of Events That Can Be Attended", + "slug": "maximum-number-of-events-that-can-be-attended", + "description": "You are given an array of events where events[i] = [startDayi, endDayi]. Every event i starts at startDayi and ends at endDayi. You can attend an event i at any day d where startTimei <= d <= endTimei. You can only attend one event at any time d. Return the maximum number of events you can attend. ", + "category": [ + "Array", + "Greedy", + "Heap (Priority Queue)" + ], + "complexity": "Medium", + "successrate": 33.4, + "totalsubmissions": 161284, + "totalaccepted": 53903, + "likes": 1743, + "dislikes": 239, + "hints": "Sort the events by the start time and in case of tie by the end time in ascending order. Loop over the sorted events. Attend as much as you can and keep the last day occupied. When you try to attend new event keep in mind the first day you can attend a new event in.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "events = [[1,2],[2,3],[3,4]]", + "expected_output": "3", + "explanation": "You can attend all the three events.\nOne way to attend them all is as shown.\nAttend the first event on day 1.\nAttend the second event on day 2.\nAttend the third event on day 3." + }, + { + "example_num": 2, + "expected_input": "events= [[1,2],[2,3],[3,4],[1,2]]", + "expected_output": "4", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d91", + "questionid": 710, + "title": "Linked List in Binary Tree", + "slug": "linked-list-in-binary-tree", + "description": "Given a binary tree root and a linked list with head as the first node. Return True if all the elements in the linked list starting from the head correspond to some downward path connected in the binary tree otherwise return False. In this context downward path means a path that starts at some node and goes downwards. ", + "category": [ + "Linked List", + "Tree", + "Depth-First Search", + "Breadth-First Search", + "Binary Tree" + ], + "complexity": "Medium", + "successrate": 42.7, + "totalsubmissions": 109555, + "totalaccepted": 46815, + "likes": 1380, + "dislikes": 48, + "hints": "Create recursive function, given a pointer in a Linked List and any node in the Binary Tree. Check if all the elements in the linked list starting from the head correspond to some downward path in the binary tree.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "head = [4,2,8], root = [1,4,4,null,2,2,null,1,null,6,8,null,null,null,null,1,3]", + "expected_output": "true", + "explanation": "Nodes in blue form a subpath in the binary Tree." + }, + { + "example_num": 2, + "expected_input": "head = [1,4,2,6], root = [1,4,4,null,2,2,null,1,null,6,8,null,null,null,null,1,3]", + "expected_output": "true", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "head = [1,4,2,6,8], root = [1,4,4,null,2,2,null,1,null,6,8,null,null,null,null,1,3]", + "expected_output": "false", + "explanation": "There is no path in the binary tree that contains all the elements of the linked list from head." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d9d", + "questionid": 722, + "title": "Construct K Palindrome Strings", + "slug": "construct-k-palindrome-strings", + "description": "Given a string s and an integer k, return true if you can use all the characters in s to construct k palindrome strings or false otherwise. ", + "category": [ + "Hash Table", + "String", + "Greedy", + "Counting" + ], + "complexity": "Medium", + "successrate": 63.7, + "totalsubmissions": 55688, + "totalaccepted": 35479, + "likes": 691, + "dislikes": 69, + "hints": "If the s.length < k we cannot construct k strings from s and answer is false. If the number of characters that have odd counts is > k then the minimum number of palindrome strings we can construct is > k and answer is false. Otherwise you can construct exactly k palindrome strings and answer is true (why ?).", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "annabelle", k = 2", + "expected_output": "true", + "explanation": "You can construct two palindromes using all characters in s.\nSome possible constructions "anna" + "elble", "anbna" + "elle", "anellena" + "b"" + }, + { + "example_num": 2, + "expected_input": "s = "leetcode", k = 3", + "expected_output": "false", + "explanation": "It is impossible to construct 3 palindromes using all the characters of s." + }, + { + "example_num": 3, + "expected_input": "s = "true", k = 4", + "expected_output": "true", + "explanation": "The only possible solution is to put each character in a separate string." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d9e", + "questionid": 723, + "title": "Reducing Dishes", + "slug": "reducing-dishes", + "description": "A chef has collected data on the satisfaction level of his n dishes. Chef can cook any dish in 1 unit of time. Like-time coefficient of a dish is defined as the time taken to cook that dish including previous dishes multiplied by its satisfaction level i.e. time[i] * satisfaction[i]. Return the maximum sum of like-time coefficient that the chef can obtain after dishes preparation. Dishes can be prepared in any order and the chef can discard some dishes to get this maximum value. ", + "category": [ + "Array", + "Dynamic Programming", + "Greedy", + "Sorting" + ], + "complexity": "Hard", + "successrate": 72.5, + "totalsubmissions": 49975, + "totalaccepted": 36207, + "likes": 926, + "dislikes": 136, + "hints": "Use dynamic programming to find the optimal solution by saving the previous best like-time coefficient and its corresponding element sum. If adding the current element to the previous best like-time coefficient and its corresponding element sum would increase the best like-time coefficient, then go ahead and add it. Otherwise, keep the previous best like-time coefficient.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "satisfaction = [-1,-8,0,5,-9]", + "expected_output": "14", + "explanation": "After Removing the second and last dish, the maximum total like-time coefficient will be equal to (-1*1 + 0*2 + 5*3 = 14).\nEach dish is prepared in one unit of time." + }, + { + "example_num": 2, + "expected_input": "satisfaction = [4,3,2]", + "expected_output": "20", + "explanation": "Dishes can be prepared in any order, (2*1 + 3*2 + 4*3 = 20)" + }, + { + "example_num": 3, + "expected_input": "satisfaction = [-1,-4,-5]", + "expected_output": "0", + "explanation": "People do not like the dishes. No dish is prepared." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720da2", + "questionid": 727, + "title": "Minimum Value to Get Positive Step by Step Sum", + "slug": "minimum-value-to-get-positive-step-by-step-sum", + "description": "Given an array of integers nums, you start with an initial positive value startValue. In each iteration, you calculate the step by step sum of startValue plus elements in nums (from left to right). Return the minimum positive value of startValue such that the step by step sum is never less than 1. ", + "category": [ + "Array", + "Prefix Sum" + ], + "complexity": "Easy", + "successrate": 68.7, + "totalsubmissions": 100547, + "totalaccepted": 69049, + "likes": 1005, + "dislikes": 231, + "hints": "Find the minimum prefix sum.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [-3,2,-3,4,2]", + "expected_output": "5\nExplanation: If you choose startValue = 4, in the third iteration your step by step sum is less than 1.\nstep by step sum\nstartValue = 4 | startValue = 5 | nums\n (4 -3 ) = 1 | (5 -3 ) = 2 | -3\n (1 +2 ) = 3 | (2 +2 ) = 4 | 2\n (3 -3 ) = 0 | (4 -3 ) = 1 | -3\n (0 +4 ) = 4 | (1 +4 ) = 5 | 4\n (4 +2 ) = 6 | (5 +2 ) = 7 | 2", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "nums = [1,2]", + "expected_output": "1", + "explanation": "Minimum start value should be positive." + }, + { + "example_num": 3, + "expected_input": "nums = [1,-2,-3]", + "expected_output": "5", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720daa", + "questionid": 735, + "title": "Display Table of Food Orders in a Restaurant", + "slug": "display-table-of-food-orders-in-a-restaurant", + "description": "Given the array orders, which represents the orders that customers have done in a restaurant. More specifically orders[i]=[customerNamei,tableNumberi,foodItemi] where customerNamei is the name of the customer, tableNumberi is the table customer sit at, and foodItemi is the item customer orders. Return the restaurant's \"display table\". The \"display table\" is a table whose row entries denote how many of each food item each table ordered. The first column is the table number and the remaining columns correspond to each food item in alphabetical order. The first row should be a header whose first column is \"Table\", followed by the names of the food items. Note that the customer names are not part of the table. Additionally, the rows should be sorted in numerically increasing order. ", + "category": [ + "Array", + "Hash Table", + "String", + "Sorting", + "Ordered Set" + ], + "complexity": "Medium", + "successrate": 72.3, + "totalsubmissions": 25760, + "totalaccepted": 18637, + "likes": 200, + "dislikes": 338, + "hints": "Keep the frequency of all pairs (tableNumber, foodItem) using a hashmap. Sort rows by tableNumber and columns by foodItem, then process the resulted table.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "orders = [["David","3","Ceviche"],["Corina","10","Beef Burrito"],["David","3","Fried Chicken"],["Carla","5","Water"],["Carla","5","Ceviche"],["Rous","3","Ceviche"]]", + "expected_output": "[["Table","Beef Burrito","Ceviche","Fried Chicken","Water"],["3","0","2","1","0"],["5","0","1","0","1"],["10","1","0","0","0"]] \r\nExplanation:\r\nThe displaying table looks like:\r\nTable,Beef Burrito,Ceviche,Fried Chicken,Water\r\n3 ,0 ,2 ,1 ,0\r\n5 ,0 ,1 ,0 ,1\r\n10 ,1 ,0 ,0 ,0\r\nFor the table 3: David orders "Ceviche" and "Fried Chicken", and Rous orders "Ceviche".\r\nFor the table 5: Carla orders "Water" and "Ceviche".\r\nFor the table 10: Corina orders "Beef Burrito".", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "orders = [["James","12","Fried Chicken"],["Ratesh","12","Fried Chicken"],["Amadeus","12","Fried Chicken"],["Adam","1","Canadian Waffles"],["Brianna","1","Canadian Waffles"]]", + "expected_output": "[["Table","Canadian Waffles","Fried Chicken"],["1","2","0"],["12","0","3"]]", + "explanation": "For the table 1: Adam and Brianna order "Canadian Waffles".\r\nFor the table 12: James, Ratesh and Amadeus order "Fried Chicken"." + }, + { + "example_num": 3, + "expected_input": "orders = [["Laura","2","Bean Burrito"],["Jhon","2","Beef Burrito"],["Melissa","2","Soda"]]", + "expected_output": "[["Table","Bean Burrito","Beef Burrito","Soda"],["2","1","1","1"]]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720dab", + "questionid": 736, + "title": "Minimum Number of Frogs Croaking", + "slug": "minimum-number-of-frogs-croaking", + "description": "You are given the string croakOfFrogs, which represents a combination of the string \"croak\" from different frogs, that is, multiple frogs can croak at the same time, so multiple \"croak\" are mixed. Return the minimum number of different frogs to finish all the croaks in the given string. A valid \"croak\" means a frog is printing five letters 'c', 'r', 'o', 'a', and 'k' sequentially. The frogs have to print all five letters to finish a croak. If the given string is not a combination of a valid \"croak\" return -1. ", + "category": [ + "String", + "Counting" + ], + "complexity": "Medium", + "successrate": 49.6, + "totalsubmissions": 49977, + "totalaccepted": 24801, + "likes": 630, + "dislikes": 39, + "hints": "keep the frequency of all characters from \"croak\" using a hashmap. For each character in the given string, greedily match it to a possible \"croak\".", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "croakOfFrogs = "croakcroak"", + "expected_output": "1", + "explanation": "One frog yelling "croak" twice." + }, + { + "example_num": 2, + "expected_input": "croakOfFrogs = "crcoakroak"", + "expected_output": "2", + "explanation": "The minimum number of frogs is two. \nThe first frog could yell "crcoakroak".\nThe second frog could yell later "crcoakroak"." + }, + { + "example_num": 3, + "expected_input": "croakOfFrogs = "croakcrook"", + "expected_output": "-1", + "explanation": "The given string is an invalid combination of "croak" from different frogs." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720dac", + "questionid": 737, + "title": "Maximum Score After Splitting a String", + "slug": "maximum-score-after-splitting-a-string", + "description": "Given a string s of zeros and ones, return the maximum score after splitting the string into two non-empty substrings (i.e. left substring and right substring). The score after splitting a string is the number of zeros in the left substring plus the number of ones in the right substring. ", + "category": [ + "String" + ], + "complexity": "Easy", + "successrate": 57.8, + "totalsubmissions": 66177, + "totalaccepted": 38228, + "likes": 490, + "dislikes": 26, + "hints": "Precompute a prefix sum of ones ('1'). Iterate from left to right counting the number of zeros ('0'), then use the precomputed prefix sum for counting ones ('1'). Update the answer.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "011101"", + "expected_output": "5", + "explanation": "All possible ways of splitting s into two non-empty substrings are:\nleft = "0" and right = "11101", score = 1 + 4 = 5 \nleft = "01" and right = "1101", score = 1 + 3 = 4 \nleft = "011" and right = "101", score = 1 + 2 = 3 \nleft = "0111" and right = "01", score = 1 + 1 = 2 \nleft = "01110" and right = "1", score = 2 + 1 = 3" + }, + { + "example_num": 2, + "expected_input": "s = "00111"", + "expected_output": "5", + "explanation": "When left = "00" and right = "111", we get the maximum score = 2 + 3 = 5" + }, + { + "example_num": 3, + "expected_input": "s = "1111"", + "expected_output": "3", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720db1", + "questionid": 742, + "title": "Count Good Nodes in Binary Tree", + "slug": "count-good-nodes-in-binary-tree", + "description": "Given a binary tree root, a node X in the tree is named good if in the path from root to X there are no nodes with a value greater than X. Return the number of good nodes in the binary tree. ", + "category": [ + "Tree", + "Depth-First Search", + "Breadth-First Search", + "Binary Tree" + ], + "complexity": "Medium", + "successrate": 73, + "totalsubmissions": 216657, + "totalaccepted": 158078, + "likes": 2256, + "dislikes": 74, + "hints": "Use DFS (Depth First Search) to traverse the tree, and constantly keep track of the current path maximum.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [3,1,4,3,null,1,5]", + "expected_output": "4", + "explanation": "Nodes in blue are good.\r\nRoot Node (3) is always a good node.\r\nNode 4 -> (3,4) is the maximum value in the path starting from the root.\r\nNode 5 -> (3,4,5) is the maximum value in the path\r\nNode 3 -> (3,1,3) is the maximum value in the path." + }, + { + "example_num": 2, + "expected_input": "root = [3,3,null,4,2]", + "expected_output": "3", + "explanation": "Node 2 -> (3, 3, 2) is not good, because "3" is higher than it." + }, + { + "example_num": 3, + "expected_input": "root = [1]", + "expected_output": "1", + "explanation": "Root is considered as good." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720db9", + "questionid": 750, + "title": "Course Schedule IV", + "slug": "course-schedule-iv", + "description": "There are a total of numCourses courses you have to take, labeled from 0 to numCourses - 1. You are given an array prerequisites where prerequisites[i] = [ai, bi] indicates that you must take course ai first if you want to take course bi. Prerequisites can also be indirect. If course a is a prerequisite of course b, and course b is a prerequisite of course c, then course a is a prerequisite of course c. You are also given an array queries where queries[j] = [uj, vj]. For the jth query, you should answer whether course uj is a prerequisite of course vj or not. Return a boolean array answer, where answer[j] is the answer to the jth query. ", + "category": [ + "Depth-First Search", + "Breadth-First Search", + "Graph", + "Topological Sort" + ], + "complexity": "Medium", + "successrate": 47.8, + "totalsubmissions": 64004, + "totalaccepted": 30620, + "likes": 774, + "dislikes": 46, + "hints": "Imagine if the courses are nodes of a graph. We need to build an array isReachable[i][j]. Start a bfs from each course i and assign for each course j you visit isReachable[i][j] = True. Answer the queries from the isReachable array.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "numCourses = 2, prerequisites = [[1,0]], queries = [[0,1],[1,0]]", + "expected_output": "[false,true]", + "explanation": "The pair [1, 0] indicates that you have to take course 1 before you can take course 0.\nCourse 0 is not a prerequisite of course 1, but the opposite is true." + }, + { + "example_num": 2, + "expected_input": "numCourses = 2, prerequisites = [], queries = [[1,0],[0,1]]", + "expected_output": "[false,false]", + "explanation": "There are no prerequisites, and each course is independent." + }, + { + "example_num": 3, + "expected_input": "numCourses = 3, prerequisites = [[1,2],[1,0],[2,0]], queries = [[1,0],[1,2]]", + "expected_output": "[true,true]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720dc3", + "questionid": 760, + "title": "Find Two Non-overlapping Sub-arrays Each With Target Sum", + "slug": "find-two-non-overlapping-sub-arrays-each-with-target-sum", + "description": "You are given an array of integers arr and an integer target. You have to find two non-overlapping sub-arrays of arr each with a sum equal target. There can be multiple answers so you have to find an answer where the sum of the lengths of the two sub-arrays is minimum. Return the minimum sum of the lengths of the two required sub-arrays, or return -1 if you cannot find such two sub-arrays. ", + "category": [ + "Array", + "Hash Table", + "Binary Search", + "Dynamic Programming", + "Sliding Window" + ], + "complexity": "Medium", + "successrate": 36.7, + "totalsubmissions": 98780, + "totalaccepted": 36246, + "likes": 1198, + "dislikes": 59, + "hints": "Let's create two arrays prefix and suffix where prefix[i] is the minimum length of sub-array ends before i and has sum = k, suffix[i] is the minimum length of sub-array starting at or after i and has sum = k. The answer we are searching for is min(prefix[i] + suffix[i]) for all values of i from 0 to n-1 where n == arr.length. If you are still stuck with how to build prefix and suffix, you can store for each index i the length of the sub-array starts at i and has sum = k or infinity otherwise, and you can use it to build both prefix and suffix.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "arr = [3,2,2,4,3], target = 3", + "expected_output": "2", + "explanation": "Only two sub-arrays have sum = 3 ([3] and [3]). The sum of their lengths is 2." + }, + { + "example_num": 2, + "expected_input": "arr = [7,3,4,7], target = 7", + "expected_output": "2", + "explanation": "Although we have three non-overlapping sub-arrays of sum = 7 ([7], [3,4] and [7]), but we will choose the first and third sub-arrays as the sum of their lengths is 2." + }, + { + "example_num": 3, + "expected_input": "arr = [4,3,2,6,2,3,4], target = 6", + "expected_output": "-1", + "explanation": "We have only one sub-array of sum = 6." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720dca", + "questionid": 767, + "title": "Longest Subarray of 1's After Deleting One Element", + "slug": "longest-subarray-of-1s-after-deleting-one-element", + "description": "Given a binary array nums, you should delete one element from it. Return the size of the longest non-empty subarray containing only 1's in the resulting array. Return 0 if there is no such subarray. ", + "category": [ + "Math", + "Dynamic Programming", + "Sliding Window" + ], + "complexity": "Medium", + "successrate": 60.1, + "totalsubmissions": 65170, + "totalaccepted": 39141, + "likes": 869, + "dislikes": 21, + "hints": "Maintain a sliding window where there is at most one zero on it.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,1,0,1]", + "expected_output": "3", + "explanation": "After deleting the number in position 2, [1,1,1] contains 3 numbers with value of 1's." + }, + { + "example_num": 2, + "expected_input": "nums = [0,1,1,1,0,1,1,0,1]", + "expected_output": "5", + "explanation": "After deleting the number in position 4, [0,1,1,1,1,1,0,1] longest subarray with value of 1's is [1,1,1,1,1]." + }, + { + "example_num": 3, + "expected_input": "nums = [1,1,1]", + "expected_output": "2", + "explanation": "You must delete one element." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d97", + "questionid": 716, + "title": "Frog Position After T Seconds", + "slug": "frog-position-after-t-seconds", + "description": "Given an undirected tree consisting of n vertices numbered from 1 to n. A frog starts jumping from vertex 1. In one second, the frog jumps from its current vertex to another unvisited vertex if they are directly connected. The frog can not jump back to a visited vertex. In case the frog can jump to several vertices, it jumps randomly to one of them with the same probability. Otherwise, when the frog can not jump to any unvisited vertex, it jumps forever on the same vertex. The edges of the undirected tree are given in the array edges, where edges[i] = [ai, bi] means that exists an edge connecting the vertices ai and bi. Return the probability that after t seconds the frog is on the vertex target. Answers within 10-5 of the actual answer will be accepted. ", + "category": [ + "Tree", + "Depth-First Search", + "Breadth-First Search", + "Graph" + ], + "complexity": "Hard", + "successrate": 36.3, + "totalsubmissions": 52971, + "totalaccepted": 19246, + "likes": 407, + "dislikes": 95, + "hints": "Use a variation of DFS with parameters 'curent_vertex' and 'current_time'. Update the probability considering to jump to one of the children vertices.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 7, edges = [[1,2],[1,3],[1,7],[2,4],[2,6],[3,5]], t = 2, target = 4", + "expected_output": "0.16666666666666666", + "explanation": "The figure above shows the given graph. The frog starts at vertex 1, jumping with 1/3 probability to the vertex 2 after second 1 and then jumping with 1/2 probability to vertex 4 after second 2. Thus the probability for the frog is on the vertex 4 after 2 seconds is 1/3 * 1/2 = 1/6 = 0.16666666666666666." + }, + { + "example_num": 2, + "expected_input": "n = 7, edges = [[1,2],[1,3],[1,7],[2,4],[2,6],[3,5]], t = 1, target = 7", + "expected_output": "0.3333333333333333\nExplanation: The figure above shows the given graph. The frog starts at vertex 1, jumping with 1/3 = 0.3333333333333333 probability to the vertex 7 after second 1.", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d9c", + "questionid": 721, + "title": "Circle and Rectangle Overlapping", + "slug": "circle-and-rectangle-overlapping", + "description": "You are given a circle represented as (radius, xCenter, yCenter) and an axis-aligned rectangle represented as (x1, y1, x2, y2), where (x1, y1) are the coordinates of the bottom-left corner, and (x2, y2) are the coordinates of the top-right corner of the rectangle. Return true if the circle and rectangle are overlapped otherwise return false. In other words, check if there is any point (xi, yi) that belongs to the circle and the rectangle at the same time. ", + "category": [ + "Math", + "Geometry" + ], + "complexity": "Medium", + "successrate": 43.7, + "totalsubmissions": 22127, + "totalaccepted": 9667, + "likes": 223, + "dislikes": 55, + "hints": "Locate the closest point of the square to the circle, you can then find the distance from this point to the center of the circle and check if this is less than or equal to the radius.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "radius = 1, xCenter = 0, yCenter = 0, x1 = 1, y1 = -1, x2 = 3, y2 = 1", + "expected_output": "true", + "explanation": "Circle and rectangle share the point (1,0)." + }, + { + "example_num": 2, + "expected_input": "radius = 1, xCenter = 1, yCenter = 1, x1 = 1, y1 = -3, x2 = 2, y2 = -1", + "expected_output": "false", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "radius = 1, xCenter = 0, yCenter = 0, x1 = -1, y1 = 0, x2 = 0, y2 = 1", + "expected_output": "true", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d9f", + "questionid": 724, + "title": "Longest Happy Prefix", + "slug": "longest-happy-prefix", + "description": "A string is called a happy prefix if is a non-empty prefix which is also a suffix (excluding itself). Given a string s, return the longest happy prefix of s. Return an empty string \"\" if no such prefix exists. ", + "category": [ + "String", + "Rolling Hash", + "String Matching", + "Hash Function" + ], + "complexity": "Hard", + "successrate": 44.4, + "totalsubmissions": 45258, + "totalaccepted": 20110, + "likes": 637, + "dislikes": 24, + "hints": "Use Longest Prefix Suffix (KMP-table) or String Hashing.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "level"", + "expected_output": ""l"", + "explanation": "s contains 4 prefix excluding itself ("l", "le", "lev", "leve"), and suffix ("l", "el", "vel", "evel"). The largest prefix which is also suffix is given by "l"." + }, + { + "example_num": 2, + "expected_input": "s = "ababab"", + "expected_output": ""abab"", + "explanation": ""abab" is the largest prefix which is also suffix. They can overlap in the original string." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720da7", + "questionid": 732, + "title": "Kids With the Greatest Number of Candies", + "slug": "kids-with-the-greatest-number-of-candies", + "description": "There are n kids with candies. You are given an integer array candies, where each candies[i] represents the number of candies the ith kid has, and an integer extraCandies, denoting the number of extra candies that you have. Return a boolean array result of length n, where result[i] is true if, after giving the ith kid all the extraCandies, they will have the greatest number of candies among all the kids, or false otherwise. Note that multiple kids can have the greatest number of candies. ", + "category": [ + "Array" + ], + "complexity": "Easy", + "successrate": 87.7, + "totalsubmissions": 345368, + "totalaccepted": 302956, + "likes": 1514, + "dislikes": 269, + "hints": "Use greedy approach. For each kid check if candies[i] + extraCandies ‰¥ maximum in Candies[i].", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "candies = [2,3,5,1,3], extraCandies = 3", + "expected_output": "[true,true,true,false,true]", + "explanation": "If you give all extraCandies to:\n- Kid 1, they will have 2 + 3 = 5 candies, which is the greatest among the kids.\n- Kid 2, they will have 3 + 3 = 6 candies, which is the greatest among the kids.\n- Kid 3, they will have 5 + 3 = 8 candies, which is the greatest among the kids.\n- Kid 4, they will have 1 + 3 = 4 candies, which is not the greatest among the kids.\n- Kid 5, they will have 3 + 3 = 6 candies, which is the greatest among the kids." + }, + { + "example_num": 2, + "expected_input": "candies = [4,2,1,1,2], extraCandies = 1", + "expected_output": "[true,false,false,false,false]", + "explanation": "There is only 1 extra candy.\nKid 1 will always have the greatest number of candies, even if a different kid is given the extra candy." + }, + { + "example_num": 3, + "expected_input": "candies = [12,1,12], extraCandies = 10", + "expected_output": "[true,false,true]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720da9", + "questionid": 734, + "title": "Reformat The String", + "slug": "reformat-the-string", + "description": "You are given an alphanumeric string s. (Alphanumeric string is a string consisting of lowercase English letters and digits). You have to find a permutation of the string where no letter is followed by another letter and no digit is followed by another digit. That is, no two adjacent characters have the same type. Return the reformatted string or return an empty string if it is impossible to reformat the string. ", + "category": [ + "String" + ], + "complexity": "Easy", + "successrate": 56.3, + "totalsubmissions": 75088, + "totalaccepted": 42296, + "likes": 394, + "dislikes": 74, + "hints": "Count the number of letters and digits in the string. if cntLetters - cntDigits has any of the values [-1, 0, 1] we have an answer, otherwise we don't have any answer. Build the string anyway as you wish. Keep in mind that you need to start with the type that have more characters if cntLetters ‰  cntDigits.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "a0b1c2"", + "expected_output": ""0a1b2c"", + "explanation": "No two adjacent characters have the same type in "0a1b2c". "a0b1c2", "0a1b2c", "0c2a1b" are also valid permutations." + }, + { + "example_num": 2, + "expected_input": "s = "leetcode"", + "expected_output": """", + "explanation": ""leetcode" has only characters so we cannot separate them by digits." + }, + { + "example_num": 3, + "expected_input": "s = "1229857369"", + "expected_output": """", + "explanation": ""1229857369" has only digits so we cannot separate them by characters." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720dad", + "questionid": 738, + "title": "Maximum Points You Can Obtain from Cards", + "slug": "maximum-points-you-can-obtain-from-cards", + "description": "There are several cards arranged in a row, and each card has an associated number of points. The points are given in the integer array cardPoints. In one step, you can take one card from the beginning or from the end of the row. You have to take exactly k cards. Your score is the sum of the points of the cards you have taken. Given the integer array cardPoints and the integer k, return the maximum score you can obtain. ", + "category": [ + "Array", + "Sliding Window", + "Prefix Sum" + ], + "complexity": "Medium", + "successrate": 50, + "totalsubmissions": 254368, + "totalaccepted": 127286, + "likes": 2759, + "dislikes": 111, + "hints": "Let the sum of all points be total_pts. You need to remove a sub-array from cardPoints with length n - k. Keep a window of size n - k over the array. The answer is max(answer, total_pts - sumOfCurrentWindow)", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "cardPoints = [1,2,3,4,5,6,1], k = 3", + "expected_output": "12", + "explanation": "After the first step, your score will always be 1. However, choosing the rightmost card first will maximize your total score. The optimal strategy is to take the three cards on the right, giving a final score of 1 + 6 + 5 = 12." + }, + { + "example_num": 2, + "expected_input": "cardPoints = [2,2,2], k = 2", + "expected_output": "4", + "explanation": "Regardless of which two cards you take, your score will always be 4." + }, + { + "example_num": 3, + "expected_input": "cardPoints = [9,7,7,9,7,7,9], k = 7", + "expected_output": "55", + "explanation": "You have to take all the cards. Your score is the sum of points of all cards." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720db4", + "questionid": 745, + "title": "Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit", + "slug": "longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit", + "description": "Given an array of integers nums and an integer limit, return the size of the longest non-empty subarray such that the absolute difference between any two elements of this subarray is less than or equal to limit. ", + "category": [ + "Array", + "Queue", + "Sliding Window", + "Heap (Priority Queue)", + "Ordered Set", + "Monotonic Queue" + ], + "complexity": "Medium", + "successrate": 46.3, + "totalsubmissions": 170851, + "totalaccepted": 79025, + "likes": 2051, + "dislikes": 88, + "hints": "Use a sliding window approach keeping the maximum and minimum value using a data structure like a multiset from STL in C++. More specifically, use the two pointer technique, moving the right pointer as far as possible to the right until the subarray is not valid (maxValue - minValue > limit), then moving the left pointer until the subarray is valid again (maxValue - minValue <= limit). Keep repeating this process.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [8,2,4,7], limit = 4", + "expected_output": "2", + "explanation": "All subarrays are: \n[8] with maximum absolute diff |8-8| = 0 <= 4.\n[8,2] with maximum absolute diff |8-2| = 6 > 4. \n[8,2,4] with maximum absolute diff |8-2| = 6 > 4.\n[8,2,4,7] with maximum absolute diff |8-2| = 6 > 4.\n[2] with maximum absolute diff |2-2| = 0 <= 4.\n[2,4] with maximum absolute diff |2-4| = 2 <= 4.\n[2,4,7] with maximum absolute diff |2-7| = 5 > 4.\n[4] with maximum absolute diff |4-4| = 0 <= 4.\n[4,7] with maximum absolute diff |4-7| = 3 <= 4.\n[7] with maximum absolute diff |7-7| = 0 <= 4. \nTherefore, the size of the longest subarray is 2." + }, + { + "example_num": 2, + "expected_input": "nums = [10,1,2,4,7,2], limit = 5", + "expected_output": "4", + "explanation": "The subarray [2,4,7,2] is the longest since the maximum absolute diff is |2-7| = 5 <= 5." + }, + { + "example_num": 3, + "expected_input": "nums = [4,2,2,2,4,4,2,2], limit = 0", + "expected_output": "3", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720db8", + "questionid": 749, + "title": "Check If a String Contains All Binary Codes of Size K", + "slug": "check-if-a-string-contains-all-binary-codes-of-size-k", + "description": "Given a binary string s and an integer k, return true if every binary code of length k is a substring of s. Otherwise, return false. ", + "category": [ + "Hash Table", + "String", + "Bit Manipulation", + "Rolling Hash", + "Hash Function" + ], + "complexity": "Medium", + "successrate": 54.5, + "totalsubmissions": 87271, + "totalaccepted": 47554, + "likes": 685, + "dislikes": 66, + "hints": "We need only to check all sub-strings of length k. The number of distinct sub-strings should be exactly 2^k.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "00110110", k = 2", + "expected_output": "true", + "explanation": "The binary codes of length 2 are "00", "01", "10" and "11". They can be all found as substrings at indices 0, 1, 3 and 2 respectively." + }, + { + "example_num": 2, + "expected_input": "s = "0110", k = 1", + "expected_output": "true", + "explanation": "The binary codes of length 1 are "0" and "1", it is clear that both exist as a substring." + }, + { + "example_num": 3, + "expected_input": "s = "0110", k = 2", + "expected_output": "false", + "explanation": "The binary code "00" is of length 2 and does not exist in the array." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720dbb", + "questionid": 752, + "title": "People Whose List of Favorite Companies Is Not a Subset of Another List", + "slug": "people-whose-list-of-favorite-companies-is-not-a-subset-of-another-list", + "description": "Given the array favoriteCompanies where favoriteCompanies[i] is the list of favorites companies for the ith person (indexed from 0). Return the indices of people whose list of favorite companies is not a subset of any other list of favorites companies. You must return the indices in increasing order. ", + "category": [ + "Array", + "Hash Table", + "String" + ], + "complexity": "Medium", + "successrate": 56.6, + "totalsubmissions": 32870, + "totalaccepted": 18590, + "likes": 247, + "dislikes": 193, + "hints": "Use hashing to convert company names in numbers and then for each list check if this is a subset of any other list. In order to check if a list is a subset of another list, use two pointers technique to get a linear solution for this task. The total complexity will be O(n^2 * m) where n is the number of lists and m is the maximum number of elements in a list.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "favoriteCompanies = [["leetcode","google","facebook"],["google","microsoft"],["google","facebook"],["google"],["amazon"]]", + "expected_output": "[0,1,4]", + "explanation": "Person with index=2 has favoriteCompanies[2]=["google","facebook"] which is a subset of favoriteCompanies[0]=["leetcode","google","facebook"] corresponding to the person with index 0. \nPerson with index=3 has favoriteCompanies[3]=["google"] which is a subset of favoriteCompanies[0]=["leetcode","google","facebook"] and favoriteCompanies[1]=["google","microsoft"]. \nOther lists of favorite companies are not a subset of another list, therefore, the answer is [0,1,4]." + }, + { + "example_num": 2, + "expected_input": "favoriteCompanies = [["leetcode","google","facebook"],["leetcode","amazon"],["facebook","google"]]", + "expected_output": "[0,1]", + "explanation": "In this case favoriteCompanies[2]=["facebook","google"] is a subset of favoriteCompanies[0]=["leetcode","google","facebook"], therefore, the answer is [0,1]." + }, + { + "example_num": 3, + "expected_input": "favoriteCompanies = [["leetcode"],["google"],["facebook"],["amazon"]]", + "expected_output": "[0,1,2,3]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720dbc", + "questionid": 753, + "title": "Maximum Number of Darts Inside of a Circular Dartboard", + "slug": "maximum-number-of-darts-inside-of-a-circular-dartboard", + "description": "Alice is throwing n darts on a very large wall. You are given an array darts where darts[i] = [xi, yi] is the position of the ith dart that Alice threw on the wall. Bob knows the positions of the n darts on the wall. He wants to place a dartboard of radius r on the wall so that the maximum number of darts that Alice throws lies on the dartboard. Given the integer r, return the maximum number of darts that can lie on the dartboard. ", + "category": [ + "Array", + "Math", + "Geometry" + ], + "complexity": "Hard", + "successrate": 36.4, + "totalsubmissions": 12490, + "totalaccepted": 4546, + "likes": 108, + "dislikes": 240, + "hints": "If there is an optimal solution, you can always move the circle so that two points lie on the boundary of the circle. When the radius is fixed, you can find either 0 or 1 or 2 circles that pass two given points at the same time. Loop for each pair of points and find the center of the circle, after that count the number of points inside the circle.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "darts = [[-2,0],[2,0],[0,2],[0,-2]], r = 2", + "expected_output": "4", + "explanation": "Circle dartboard with center in (0,0) and radius = 2 contain all points." + }, + { + "example_num": 2, + "expected_input": "darts = [[-3,0],[3,0],[2,6],[5,4],[0,9],[7,8]], r = 5", + "expected_output": "5", + "explanation": "Circle dartboard with center in (0,4) and radius = 5 contain all points except the point (7,8)." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720dbf", + "questionid": 756, + "title": "Pseudo-Palindromic Paths in a Binary Tree", + "slug": "pseudo-palindromic-paths-in-a-binary-tree", + "description": "Given a binary tree where node values are digits from 1 to 9. A path in the binary tree is said to be pseudo-palindromic if at least one permutation of the node values in the path is a palindrome. Return the number of pseudo-palindromic paths going from the root node to leaf nodes. ", + "category": [ + "Bit Manipulation", + "Tree", + "Depth-First Search", + "Breadth-First Search", + "Binary Tree" + ], + "complexity": "Medium", + "successrate": 67.3, + "totalsubmissions": 75439, + "totalaccepted": 50739, + "likes": 961, + "dislikes": 34, + "hints": "Note that the node values of a path form a palindrome if at most one digit has an odd frequency (parity). Use a Depth First Search (DFS) keeping the frequency (parity) of the digits. Once you are in a leaf node check if at most one digit has an odd frequency (parity).", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [2,3,1,3,1,null,1]", + "expected_output": "2", + "explanation": "The figure above represents the given binary tree. There are three paths going from the root node to leaf nodes: the red path [2,3,3], the green path [2,1,1], and the path [2,3,1]. Among these paths only red path and green path are pseudo-palindromic paths since the red path [2,3,3] can be rearranged in [3,2,3] (palindrome) and the green path [2,1,1] can be rearranged in [1,2,1] (palindrome)." + }, + { + "example_num": 2, + "expected_input": "root = [2,1,1,1,3,null,null,null,null,null,1]", + "expected_output": "1", + "explanation": "The figure above represents the given binary tree. There are three paths going from the root node to leaf nodes: the green path [2,1,1], the path [2,1,3,1], and the path [2,1]. Among these paths only the green path is pseudo-palindromic since [2,1,1] can be rearranged in [1,2,1] (palindrome)." + }, + { + "example_num": 3, + "expected_input": "root = [9]", + "expected_output": "1", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720dc4", + "questionid": 761, + "title": "Reorder Routes to Make All Paths Lead to the City Zero", + "slug": "reorder-routes-to-make-all-paths-lead-to-the-city-zero", + "description": "There are n cities numbered from 0 to n - 1 and n - 1 roads such that there is only one way to travel between two different cities (this network form a tree). Last year, The ministry of transport decided to orient the roads in one direction because they are too narrow. Roads are represented by connections where connections[i] = [ai, bi] represents a road from city ai to city bi. This year, there will be a big event in the capital (city 0), and many people want to travel to this city. Your task consists of reorienting some roads such that each city can visit the city 0. Return the minimum number of edges changed. It's guaranteed that each city can reach city 0 after reorder. ", + "category": [ + "Depth-First Search", + "Breadth-First Search", + "Graph" + ], + "complexity": "Medium", + "successrate": 61, + "totalsubmissions": 84269, + "totalaccepted": 51446, + "likes": 1425, + "dislikes": 36, + "hints": "Treat the graph as undirected. Start a dfs from the root, if you come across an edge in the forward direction, you need to reverse the edge.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 6, connections = [[0,1],[1,3],[2,3],[4,0],[4,5]]", + "expected_output": "3\nExplanation: Change the direction of edges show in red such that each node can reach the node 0 (capital).", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "n = 5, connections = [[1,0],[1,2],[3,2],[3,4]]", + "expected_output": "2\nExplanation: Change the direction of edges show in red such that each node can reach the node 0 (capital).", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "n = 3, connections = [[1,0],[2,0]]", + "expected_output": "0", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720dc7", + "questionid": 764, + "title": "The k Strongest Values in an Array", + "slug": "the-k-strongest-values-in-an-array", + "description": "Given an array of integers arr and an integer k. A value arr[i] is said to be stronger than a value arr[j] if |arr[i] - m| > |arr[j] - m| where m is the median of the array.\nIf |arr[i] - m| == |arr[j] - m|, then arr[i] is said to be stronger than arr[j] if arr[i] > arr[j]. Return a list of the strongest k values in the array. return the answer in any arbitrary order. Median is the middle value in an ordered integer list. More formally, if the length of the list is n, the median is the element in position ((n - 1) / 2) in the sorted list (0-indexed). ", + "category": [ + "Array", + "Two Pointers", + "Sorting" + ], + "complexity": "Medium", + "successrate": 59.7, + "totalsubmissions": 45468, + "totalaccepted": 27166, + "likes": 399, + "dislikes": 94, + "hints": "Calculate the median of the array as defined in the statement. Use custom sort function to sort values (Strongest first), then slice the first k.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "arr = [1,2,3,4,5], k = 2", + "expected_output": "[5,1]", + "explanation": "Median is 3, the elements of the array sorted by the strongest are [5,1,4,2,3]. The strongest 2 elements are [5, 1]. [1, 5] is also accepted answer.\nPlease note that although |5 - 3| == |1 - 3| but 5 is stronger than 1 because 5 > 1." + }, + { + "example_num": 2, + "expected_input": "arr = [1,1,3,5,5], k = 2", + "expected_output": "[5,5]", + "explanation": "Median is 3, the elements of the array sorted by the strongest are [5,5,1,1,3]. The strongest 2 elements are [5, 5]." + }, + { + "example_num": 3, + "expected_input": "arr = [6,7,11,7,6,8], k = 5", + "expected_output": "[11,8,6,6,7]", + "explanation": "Median is 7, the elements of the array sorted by the strongest are [11,8,6,6,7,7].\nAny permutation of [11,8,6,6,7] is accepted." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720dc8", + "questionid": 765, + "title": "Average Salary Excluding the Minimum and Maximum Salary", + "slug": "average-salary-excluding-the-minimum-and-maximum-salary", + "description": "You are given an array of unique integers salary where salary[i] is the salary of the ith employee. Return the average salary of employees excluding the minimum and maximum salary. Answers within 10-5 of the actual answer will be accepted. ", + "category": [ + "Array", + "Sorting" + ], + "complexity": "Easy", + "successrate": 65.1, + "totalsubmissions": 141589, + "totalaccepted": 92237, + "likes": 624, + "dislikes": 87, + "hints": "Get the total sum and subtract the minimum and maximum value in the array. Finally divide the result by n - 2.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "salary = [4000,3000,1000,2000]", + "expected_output": "2500.00000", + "explanation": "Minimum salary and maximum salary are 1000 and 4000 respectively.\nAverage salary excluding minimum and maximum salary is (2000+3000) / 2 = 2500" + }, + { + "example_num": 2, + "expected_input": "salary = [1000,2000,3000]", + "expected_output": "2000.00000", + "explanation": "Minimum salary and maximum salary are 1000 and 3000 respectively.\nAverage salary excluding minimum and maximum salary is (2000) / 1 = 2000" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720dc9", + "questionid": 766, + "title": "The kth Factor of n", + "slug": "the-kth-factor-of-n", + "description": "You are given two positive integers n and k. A factor of an integer n is defined as an integer i where n % i == 0. Consider a list of all factors of n sorted in ascending order, return the kth factor in this list or return -1 if n has less than k factors. ", + "category": [ + "Math" + ], + "complexity": "Medium", + "successrate": 62.1, + "totalsubmissions": 140760, + "totalaccepted": 87388, + "likes": 704, + "dislikes": 205, + "hints": "The factors of n will be always in the range [1, n]. Keep a list of all factors sorted. Loop i from 1 to n and add i if n % i == 0. Return the kth factor if it exist in this list.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 12, k = 3", + "expected_output": "3", + "explanation": "Factors list is [1, 2, 3, 4, 6, 12], the 3rd factor is 3." + }, + { + "example_num": 2, + "expected_input": "n = 7, k = 2", + "expected_output": "7", + "explanation": "Factors list is [1, 7], the 2nd factor is 7." + }, + { + "example_num": 3, + "expected_input": "n = 4, k = 4", + "expected_output": "-1", + "explanation": "Factors list is [1, 2, 4], there is only 3 factors. We should return -1." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d95", + "questionid": 714, + "title": "Number of Times Binary String Is Prefix-Aligned", + "slug": "number-of-times-binary-string-is-prefix-aligned", + "description": "You have a 1-indexed binary string of length n where all the bits are 0 initially. We will flip all the bits of this binary string (i.e., change them from 0 to 1) one by one. You are given a 1-indexed integer array flips where flips[i] indicates that the bit at index i will be flipped in the ith step. A binary string is prefix-aligned if, after the ith step, all the bits in the inclusive range [1, i] are ones and all the other bits are zeros. Return the number of times the binary string is prefix-aligned during the flipping process. ", + "category": [ + "Array" + ], + "complexity": "Medium", + "successrate": 65.7, + "totalsubmissions": 59427, + "totalaccepted": 39026, + "likes": 699, + "dislikes": 110, + "hints": "If in the step x all bulb shines then bulbs 1,2,3,..,x should shines too.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "flips = [3,2,4,1,5]", + "expected_output": "2", + "explanation": "The binary string is initially "00000".\nAfter applying step 1: The string becomes "00100", which is not prefix-aligned.\nAfter applying step 2: The string becomes "01100", which is not prefix-aligned.\nAfter applying step 3: The string becomes "01110", which is not prefix-aligned.\nAfter applying step 4: The string becomes "11110", which is prefix-aligned.\nAfter applying step 5: The string becomes "11111", which is prefix-aligned.\nWe can see that the string was prefix-aligned 2 times, so we return 2." + }, + { + "example_num": 2, + "expected_input": "flips = [4,1,2,3]", + "expected_output": "1", + "explanation": "The binary string is initially "0000".\nAfter applying step 1: The string becomes "0001", which is not prefix-aligned.\nAfter applying step 2: The string becomes "1001", which is not prefix-aligned.\nAfter applying step 3: The string becomes "1101", which is not prefix-aligned.\nAfter applying step 4: The string becomes "1111", which is prefix-aligned.\nWe can see that the string was prefix-aligned 1 time, so we return 1." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d96", + "questionid": 715, + "title": "Time Needed to Inform All Employees", + "slug": "time-needed-to-inform-all-employees", + "description": "A company has n employees with a unique ID for each employee from 0 to n - 1. The head of the company is the one with headID. Each employee has one direct manager given in the manager array where manager[i] is the direct manager of the i-th employee, manager[headID] = -1. Also, it is guaranteed that the subordination relationships have a tree structure. The head of the company wants to inform all the company employees of an urgent piece of news. He will inform his direct subordinates, and they will inform their subordinates, and so on until all employees know about the urgent news. The i-th employee needs informTime[i] minutes to inform all of his direct subordinates (i.e., After informTime[i] minutes, all his direct subordinates can start spreading the news). Return the number of minutes needed to inform all the employees about the urgent news. ", + "category": [ + "Tree", + "Depth-First Search", + "Breadth-First Search" + ], + "complexity": "Medium", + "successrate": 58, + "totalsubmissions": 150014, + "totalaccepted": 87042, + "likes": 1663, + "dislikes": 98, + "hints": "The company can be represented as a tree, headID is always the root. Store for each node the time needed to be informed of the news. Answer is the max time a leaf node needs to be informed.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 1, headID = 0, manager = [-1], informTime = [0]", + "expected_output": "0", + "explanation": "The head of the company is the only employee in the company." + }, + { + "example_num": 2, + "expected_input": "n = 6, headID = 2, manager = [2,2,-1,2,2,2], informTime = [0,0,1,0,0,0]", + "expected_output": "1", + "explanation": "The head of the company with id = 2 is the direct manager of all the employees in the company and needs 1 minute to inform them all.\nThe tree structure of the employees in the company is shown." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d9a", + "questionid": 719, + "title": "Maximum Performance of a Team", + "slug": "maximum-performance-of-a-team", + "description": "You are given two integers n and k and two integer arrays speed and efficiency both of length n. There are n engineers numbered from 1 to n. speed[i] and efficiency[i] represent the speed and efficiency of the ith engineer respectively. Choose at most k different engineers out of the n engineers to form a team with the maximum performance. The performance of a team is the sum of their engineers' speeds multiplied by the minimum efficiency among their engineers. Return the maximum performance of this team. Since the answer can be a huge number, return it modulo 109 + 7. ", + "category": [ + "Array", + "Greedy", + "Sorting", + "Heap (Priority Queue)" + ], + "complexity": "Hard", + "successrate": 41.5, + "totalsubmissions": 92816, + "totalaccepted": 38501, + "likes": 1137, + "dislikes": 39, + "hints": "Keep track of the engineers by their efficiency in decreasing order. Starting from one engineer, to build a team, it suffices to bring K-1 more engineers who have higher efficiencies as well as high speeds.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 6, speed = [2,10,3,1,5,8], efficiency = [5,4,3,9,7,2], k = 2", + "expected_output": "60", + "explanation": "We have the maximum performance of the team by selecting engineer 2 (with speed=10 and efficiency=4) and engineer 5 (with speed=5 and efficiency=7). That is, performance = (10 + 5) * min(4, 7) = 60." + }, + { + "example_num": 2, + "expected_input": "n = 6, speed = [2,10,3,1,5,8], efficiency = [5,4,3,9,7,2], k = 3", + "expected_output": "68\nExplanation:\nThis is the same example as the first but k = 3. We can select engineer 1, engineer 2 and engineer 5 to get the maximum performance of the team. That is, performance = (2 + 10 + 5) * min(5, 4, 7) = 68.", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "n = 6, speed = [2,10,3,1,5,8], efficiency = [5,4,3,9,7,2], k = 4", + "expected_output": "72", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d9b", + "questionid": 720, + "title": "Count Largest Group", + "slug": "count-largest-group", + "description": "You are given an integer n. Each number from 1 to n is grouped according to the sum of its digits. Return the number of groups that have the largest size. ", + "category": [ + "Hash Table", + "Math" + ], + "complexity": "Easy", + "successrate": 66.8, + "totalsubmissions": 45418, + "totalaccepted": 30319, + "likes": 265, + "dislikes": 653, + "hints": "Count the digit sum for each integer in the range and find out the largest groups.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 13", + "expected_output": "4", + "explanation": "There are 9 groups in total, they are grouped according sum of its digits of numbers from 1 to 13:\n[1,10], [2,11], [3,12], [4,13], [5], [6], [7], [8], [9].\nThere are 4 groups with largest size." + }, + { + "example_num": 2, + "expected_input": "n = 2", + "expected_output": "2", + "explanation": "There are 2 groups [1], [2] of size 1." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720da1", + "questionid": 726, + "title": "Find All Good Strings", + "slug": "find-all-good-strings", + "description": "Given the strings s1 and s2 of size n and the string evil, return the number of good strings. A good string has size n, it is alphabetically greater than or equal to s1, it is alphabetically smaller than or equal to s2, and it does not contain the string evil as a substring. Since the answer can be a huge number, return this modulo 109 + 7. ", + "category": [ + "String", + "Dynamic Programming", + "String Matching" + ], + "complexity": "Hard", + "successrate": 40.7, + "totalsubmissions": 9701, + "totalaccepted": 3948, + "likes": 285, + "dislikes": 102, + "hints": "Use DP with 4 states (pos: Int, posEvil: Int, equalToS1: Bool, equalToS2: Bool) which compute the number of valid strings of size \"pos\" where the maximum common suffix with string \"evil\" has size \"posEvil\". When \"equalToS1\" is \"true\", the current valid string is equal to \"S1\" otherwise it is greater. In a similar way when equalToS2 is \"true\" the current valid string is equal to \"S2\" otherwise it is smaller. To update the maximum common suffix with string \"evil\" use KMP preprocessing.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 2, s1 = "aa", s2 = "da", evil = "b"", + "expected_output": "51", + "explanation": "There are 25 good strings starting with 'a': "aa","ac","ad",...,"az". Then there are 25 good strings starting with 'c': "ca","cc","cd",...,"cz" and finally there is one good string starting with 'd': "da". " + }, + { + "example_num": 2, + "expected_input": "n = 8, s1 = "leetcode", s2 = "leetgoes", evil = "leet"", + "expected_output": "0", + "explanation": "All strings greater than or equal to s1 and smaller than or equal to s2 start with the prefix "leet", therefore, there is not any good string." + }, + { + "example_num": 3, + "expected_input": "n = 2, s1 = "gx", s2 = "gz", evil = "x"", + "expected_output": "2", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720da3", + "questionid": 728, + "title": "Restore The Array", + "slug": "restore-the-array", + "description": "A program was supposed to print an array of integers. The program forgot to print whitespaces and the array is printed as a string of digits s and all we know is that all integers in the array were in the range [1, k] and there are no leading zeros in the array. Given the string s and the integer k, return the number of the possible arrays that can be printed as s using the mentioned program. Since the answer may be very large, return it modulo 109 + 7. ", + "category": [ + "String", + "Dynamic Programming" + ], + "complexity": "Hard", + "successrate": 37.9, + "totalsubmissions": 31534, + "totalaccepted": 11955, + "likes": 355, + "dislikes": 14, + "hints": "Use dynamic programming. Build an array dp where dp[i] is the number of ways you can divide the string starting from index i to the end. Keep in mind that the answer is modulo 10^9 + 7 and take the mod for each operation.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "1000", k = 10000", + "expected_output": "1", + "explanation": "The only possible array is [1000]" + }, + { + "example_num": 2, + "expected_input": "s = "1000", k = 10", + "expected_output": "0", + "explanation": "There cannot be an array that was printed this way and has all integer >= 1 and <= 10." + }, + { + "example_num": 3, + "expected_input": "s = "1317", k = 2000", + "expected_output": "8", + "explanation": "Possible arrays are [1317],[131,7],[13,17],[1,317],[13,1,7],[1,31,7],[1,3,17],[1,3,1,7]" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720daf", + "questionid": 740, + "title": "Consecutive Characters", + "slug": "consecutive-characters", + "description": "The power of the string is the maximum length of a non-empty substring that contains only one unique character. Given a string s, return the power of s. ", + "category": [ + "String" + ], + "complexity": "Easy", + "successrate": 62, + "totalsubmissions": 190331, + "totalaccepted": 117956, + "likes": 1210, + "dislikes": 24, + "hints": "Keep an array power where power[i] is the maximum power of the i-th character. The answer is max(power[i]).", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "leetcode"", + "expected_output": "2", + "explanation": "The substring "ee" is of length 2 with the character 'e' only." + }, + { + "example_num": 2, + "expected_input": "s = "abbcccddddeeeeedcba"", + "expected_output": "5", + "explanation": "The substring "eeeee" is of length 5 with the character 'e' only." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720db3", + "questionid": 744, + "title": "Check If All 1's Are at Least Length K Places Away", + "slug": "check-if-all-1s-are-at-least-length-k-places-away", + "description": "Given an binary array nums and an integer k, return true if all 1's are at least k places away from each other, otherwise return false. ", + "category": [ + "Array" + ], + "complexity": "Easy", + "successrate": 60, + "totalsubmissions": 95564, + "totalaccepted": 57340, + "likes": 392, + "dislikes": 193, + "hints": "Each time you find a number 1, check whether or not it is K or more places away from the next one. If it's not, return false.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,0,0,0,1,0,0,1], k = 2", + "expected_output": "true", + "explanation": "Each of the 1s are at least 2 places away from each other." + }, + { + "example_num": 2, + "expected_input": "nums = [1,0,0,1,0,1], k = 2", + "expected_output": "false", + "explanation": "The second 1 and third 1 are only one apart from each other." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720db5", + "questionid": 746, + "title": "Find the Kth Smallest Sum of a Matrix With Sorted Rows", + "slug": "find-the-kth-smallest-sum-of-a-matrix-with-sorted-rows", + "description": "You are given an m x n matrix mat that has its rows sorted in non-decreasing order and an integer k. You are allowed to choose exactly one element from each row to form an array. Return the kth smallest array sum among all possible arrays. ", + "category": [ + "Array", + "Binary Search", + "Heap (Priority Queue)", + "Matrix" + ], + "complexity": "Hard", + "successrate": 61.5, + "totalsubmissions": 39655, + "totalaccepted": 24388, + "likes": 832, + "dislikes": 13, + "hints": "Save all visited sums and corresponding indexes in a priority queue. Then, once you pop the smallest sum so far, you can quickly identify the next m candidates for smallest sum by incrementing each row index by 1.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "mat = [[1,3,11],[2,4,6]], k = 5", + "expected_output": "7", + "explanation": "Choosing one element from each row, the first k smallest sum are:\n[1,2], [1,4], [3,2], [3,4], [1,6]. Where the 5th sum is 7." + }, + { + "example_num": 2, + "expected_input": "mat = [[1,3,11],[2,4,6]], k = 9", + "expected_output": "17", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "mat = [[1,10,10],[1,4,5],[2,3,6]], k = 7", + "expected_output": "9", + "explanation": "Choosing one element from each row, the first k smallest sum are:\n[1,1,2], [1,1,3], [1,4,2], [1,4,3], [1,1,6], [1,5,2], [1,5,3]. Where the 7th sum is 9." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720db6", + "questionid": 747, + "title": "Minimum Time to Collect All Apples in a Tree", + "slug": "minimum-time-to-collect-all-apples-in-a-tree", + "description": "Given an undirected tree consisting of n vertices numbered from 0 to n-1, which has some apples in their vertices. You spend 1 second to walk over one edge of the tree. Return the minimum time in seconds you have to spend to collect all apples in the tree, starting at vertex 0 and coming back to this vertex. The edges of the undirected tree are given in the array edges, where edges[i] = [ai, bi] means that exists an edge connecting the vertices ai and bi. Additionally, there is a boolean array hasApple, where hasApple[i] = true means that vertex i has an apple; otherwise, it does not have any apple. ", + "category": [ + "Hash Table", + "Tree", + "Depth-First Search", + "Breadth-First Search" + ], + "complexity": "Medium", + "successrate": 55.6, + "totalsubmissions": 51391, + "totalaccepted": 28593, + "likes": 928, + "dislikes": 87, + "hints": "Note that if a node u contains an apple then all edges in the path from the root to the node u have to be used forward and backward (2 times). Therefore use a depth-first search (DFS) to check if an edge will be used or not.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], hasApple = [false,false,true,false,true,true,false]", + "expected_output": "8", + "explanation": "The figure above represents the given tree where red vertices have an apple. One optimal path to collect all apples is shown by the green arrows." + }, + { + "example_num": 2, + "expected_input": "n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], hasApple = [false,false,true,false,false,true,false]", + "expected_output": "6", + "explanation": "The figure above represents the given tree where red vertices have an apple. One optimal path to collect all apples is shown by the green arrows." + }, + { + "example_num": 3, + "expected_input": "n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], hasApple = [false,false,false,false,false,false,false]", + "expected_output": "0", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720dc0", + "questionid": 757, + "title": "Max Dot Product of Two Subsequences", + "slug": "max-dot-product-of-two-subsequences", + "description": "Given two arrays nums1 and nums2. Return the maximum dot product between non-empty subsequences of nums1 and nums2 with the same length. A subsequence of a array is a new array which is formed from the original array by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, [2,3,5] is a subsequence of [1,2,3,4,5] while [1,5,3] is not). ", + "category": [ + "Array", + "Dynamic Programming" + ], + "complexity": "Hard", + "successrate": 45.2, + "totalsubmissions": 36088, + "totalaccepted": 16301, + "likes": 573, + "dislikes": 11, + "hints": "Use dynamic programming, define DP[i][j] as the maximum dot product of two subsequences starting in the position i of nums1 and position j of nums2.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums1 = [2,1,-2,5], nums2 = [3,0,-6]", + "expected_output": "18", + "explanation": "Take subsequence [2,-2] from nums1 and subsequence [3,-6] from nums2.\nTheir dot product is (2*3 + (-2)*(-6)) = 18." + }, + { + "example_num": 2, + "expected_input": "nums1 = [3,-2], nums2 = [2,-6,7]", + "expected_output": "21", + "explanation": "Take subsequence [3] from nums1 and subsequence [7] from nums2.\nTheir dot product is (3*7) = 21." + }, + { + "example_num": 3, + "expected_input": "nums1 = [-1,-1], nums2 = [1,1]", + "expected_output": "-1\nExplanation: Take subsequence [-1] from nums1 and subsequence [1] from nums2.\nTheir dot product is -1.", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720dc1", + "questionid": 758, + "title": "Final Prices With a Special Discount in a Shop", + "slug": "final-prices-with-a-special-discount-in-a-shop", + "description": "Given the array prices where prices[i] is the price of the ith item in a shop. There is a special discount for items in the shop, if you buy the ith item, then you will receive a discount equivalent to prices[j] where j is the minimum index such that j > i and prices[j] <= prices[i], otherwise, you will not receive any discount at all. Return an array where the ith element is the final price you will pay for the ith item of the shop considering the special discount. ", + "category": [ + "Array", + "Stack", + "Monotonic Stack" + ], + "complexity": "Easy", + "successrate": 75.2, + "totalsubmissions": 98680, + "totalaccepted": 74225, + "likes": 1022, + "dislikes": 65, + "hints": "Use brute force: For the ith item in the shop with a loop find the first position j satisfying the conditions and apply the discount, otherwise, the discount is 0.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "prices = [8,4,6,2,3]", + "expected_output": "[4,2,4,2,3]", + "explanation": "For item 0 with price[0]=8 you will receive a discount equivalent to prices[1]=4, therefore, the final price you will pay is 8 - 4 = 4.\nFor item 1 with price[1]=4 you will receive a discount equivalent to prices[3]=2, therefore, the final price you will pay is 4 - 2 = 2.\nFor item 2 with price[2]=6 you will receive a discount equivalent to prices[3]=2, therefore, the final price you will pay is 6 - 2 = 4.\nFor items 3 and 4 you will not receive any discount at all." + }, + { + "example_num": 2, + "expected_input": "prices = [1,2,3,4,5]", + "expected_output": "[1,2,3,4,5]", + "explanation": "In this case, for all items, you will not receive any discount at all." + }, + { + "example_num": 3, + "expected_input": "prices = [10,1,1,6]", + "expected_output": "[9,0,1,6]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720dc2", + "questionid": 759, + "title": "Allocate Mailboxes", + "slug": "allocate-mailboxes", + "description": "Given the array houses where houses[i] is the location of the ith house along a street and an integer k, allocate k mailboxes in the street. Return the minimum total distance between each house and its nearest mailbox. The test cases are generated so that the answer fits in a 32-bit integer. ", + "category": [ + "Array", + "Math", + "Dynamic Programming", + "Sorting" + ], + "complexity": "Hard", + "successrate": 55.4, + "totalsubmissions": 27496, + "totalaccepted": 15237, + "likes": 698, + "dislikes": 12, + "hints": "If k =1, the minimum distance is obtained allocating the mailbox in the median of the array houses. Generalize this idea, using dynamic programming allocating k mailboxes.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "houses = [1,4,8,10,20], k = 3", + "expected_output": "5", + "explanation": "Allocate mailboxes in position 3, 9 and 20.\nMinimum total distance from each houses to nearest mailboxes is |3-1| + |4-3| + |9-8| + |10-9| + |20-20| = 5" + }, + { + "example_num": 2, + "expected_input": "houses = [2,3,5,12,18], k = 2", + "expected_output": "9", + "explanation": "Allocate mailboxes in position 3 and 14.\nMinimum total distance from each houses to nearest mailboxes is |2-3| + |3-3| + |5-3| + |12-14| + |18-14| = 9." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720dc6", + "questionid": 763, + "title": "Shuffle the Array", + "slug": "shuffle-the-array", + "description": "Given the array nums consisting of 2n elements in the form [x1,x2,...,xn,y1,y2,...,yn]. Return the array in the form [x1,y1,x2,y2,...,xn,yn]. ", + "category": [ + "Array" + ], + "complexity": "Easy", + "successrate": 88.3, + "totalsubmissions": 348393, + "totalaccepted": 307691, + "likes": 2264, + "dislikes": 170, + "hints": "Use two pointers to create the new array of 2n elements. The first starting at the beginning and the other starting at (n+1)th position. Alternate between them and create the new array.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [2,5,1,3,4,7], n = 3", + "expected_output": "[2,3,5,4,1,7]", + "explanation": "Since x1=2, x2=5, x3=1, y1=3, y2=4, y3=7 then the answer is [2,3,5,4,1,7]." + }, + { + "example_num": 2, + "expected_input": "nums = [1,2,3,4,4,3,2,1], n = 4", + "expected_output": "[1,4,2,3,3,2,4,1]", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "nums = [1,1,2,2], n = 2", + "expected_output": "[1,2,1,2]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d8d", + "questionid": 706, + "title": "Count Negative Numbers in a Sorted Matrix", + "slug": "count-negative-numbers-in-a-sorted-matrix", + "description": "Given a m x n matrix grid which is sorted in non-increasing order both row-wise and column-wise, return the number of negative numbers in grid. ", + "category": [ + "Array", + "Binary Search", + "Matrix" + ], + "complexity": "Easy", + "successrate": 75.2, + "totalsubmissions": 223434, + "totalaccepted": 167991, + "likes": 2094, + "dislikes": 70, + "hints": "Use binary search for optimization or simply brute force.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "grid = [[4,3,2,-1],[3,2,1,-1],[1,1,-1,-2],[-1,-1,-2,-3]]", + "expected_output": "8", + "explanation": "There are 8 negatives number in the matrix." + }, + { + "example_num": 2, + "expected_input": "grid = [[3,2],[1,0]]", + "expected_output": "0", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d90", + "questionid": 709, + "title": "Rank Teams by Votes", + "slug": "rank-teams-by-votes", + "description": "In a special ranking system, each voter gives a rank from highest to lowest to all teams participated in the competition. The ordering of teams is decided by who received the most position-one votes. If two or more teams tie in the first position, we consider the second position to resolve the conflict, if they tie again, we continue this process until the ties are resolved. If two or more teams are still tied after considering all positions, we rank them alphabetically based on their team letter. Given an array of strings votes which is the votes of all voters in the ranking systems. Sort all teams according to the ranking system described above. Return a string of all teams sorted by the ranking system. ", + "category": [ + "Array", + "Hash Table", + "String", + "Sorting", + "Counting" + ], + "complexity": "Medium", + "successrate": 58.6, + "totalsubmissions": 62191, + "totalaccepted": 36468, + "likes": 780, + "dislikes": 82, + "hints": "Build array rank where rank[i][j] is the number of votes for team i to be the j-th rank. Sort the trams by rank array. if rank array is the same for two or more teams, sort them by the ID in ascending order.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "votes = ["ABC","ACB","ABC","ACB","ACB"]", + "expected_output": ""ACB"", + "explanation": "Team A was ranked first place by 5 voters. No other team was voted as first place, so team A is the first team.\nTeam B was ranked second by 2 voters and ranked third by 3 voters.\nTeam C was ranked second by 3 voters and ranked third by 2 voters.\nAs most of the voters ranked C second, team C is the second team, and team B is the third." + }, + { + "example_num": 2, + "expected_input": "votes = ["WXYZ","XYZW"]", + "expected_output": ""XWYZ"", + "explanation": "X is the winner due to the tie-breaking rule. X has the same votes as W for the first position, but X has one vote in the second position, while W does not have any votes in the second position." + }, + { + "example_num": 3, + "expected_input": "votes = ["ZMNAGUEDSJYLBOPHRQICWFXTVK"]", + "expected_output": ""ZMNAGUEDSJYLBOPHRQICWFXTVK"", + "explanation": "Only one voter, so their votes are used for the ranking." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d92", + "questionid": 711, + "title": "Find the Distance Value Between Two Arrays", + "slug": "find-the-distance-value-between-two-arrays", + "description": "Given two integer arrays arr1 and arr2, and the integer d, return the distance value between the two arrays. The distance value is defined as the number of elements arr1[i] such that there is not any element arr2[j] where |arr1[i]-arr2[j]| <= d. ", + "category": [ + "Array", + "Two Pointers", + "Binary Search", + "Sorting" + ], + "complexity": "Easy", + "successrate": 66.1, + "totalsubmissions": 65405, + "totalaccepted": 43242, + "likes": 370, + "dislikes": 1370, + "hints": "Sort 'arr2' and use binary search to get the closest element for each 'arr1[i]', it gives a time complexity of O(nlogn).", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "arr1 = [4,5,8], arr2 = [10,9,1,8], d = 2", + "expected_output": "2", + "explanation": "For arr1[0]=4 we have: \n|4-10|=6 > d=2 \n|4-9|=5 > d=2 \n|4-1|=3 > d=2 \n|4-8|=4 > d=2 \nFor arr1[1]=5 we have: \n|5-10|=5 > d=2 \n|5-9|=4 > d=2 \n|5-1|=4 > d=2 \n|5-8|=3 > d=2\nFor arr1[2]=8 we have:\n|8-10|=2 <= d=2\n|8-9|=1 <= d=2\n|8-1|=7 > d=2\n|8-8|=0 <= d=2" + }, + { + "example_num": 2, + "expected_input": "arr1 = [1,4,2,3], arr2 = [-4,-3,6,10,20,30], d = 3", + "expected_output": "2", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "arr1 = [2,1,100,3], arr2 = [-5,-2,10,-3,7], d = 6", + "expected_output": "1", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d93", + "questionid": 712, + "title": "Cinema Seat Allocation", + "slug": "cinema-seat-allocation", + "description": " A cinema has n rows of seats, numbered from 1 to n and there are ten seats in each row, labelled from 1 to 10 as shown in the figure above. Given the array reservedSeats containing the numbers of seats already reserved, for example, reservedSeats[i] = [3,8] means the seat located in row 3 and labelled with 8 is already reserved. Return the maximum number of four-person groups you can assign on the cinema seats. A four-person group occupies four adjacent seats in one single row. Seats across an aisle (such as [3,3] and [3,4]) are not considered to be adjacent, but there is an exceptional case on which an aisle split a four-person group, in that case, the aisle split a four-person group in the middle, which means to have two people on each side. ", + "category": [ + "Array", + "Hash Table", + "Greedy", + "Bit Manipulation" + ], + "complexity": "Medium", + "successrate": 39.5, + "totalsubmissions": 58948, + "totalaccepted": 23256, + "likes": 463, + "dislikes": 246, + "hints": "Note you can allocate at most two families in one row. Greedily check if you can allocate seats for two families, one family or none. Process only rows that appear in the input, for other rows you can always allocate seats for two families.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 3, reservedSeats = [[1,2],[1,3],[1,8],[2,6],[3,1],[3,10]]", + "expected_output": "4", + "explanation": "The figure above shows the optimal allocation for four groups, where seats mark with blue are already reserved and contiguous seats mark with orange are for one group." + }, + { + "example_num": 2, + "expected_input": "n = 2, reservedSeats = [[2,1],[1,8],[2,6]]", + "expected_output": "2", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "n = 4, reservedSeats = [[4,3],[1,4],[4,6],[1,7]]", + "expected_output": "4", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d94", + "questionid": 713, + "title": "Generate a String With Characters That Have Odd Counts", + "slug": "generate-a-string-with-characters-that-have-odd-counts", + "description": "Given an integer n, return a string with n characters such that each character in such string occurs an odd number of times. The returned string must contain only lowercase English letters. If there are multiples valid strings, return any of them. ", + "category": [ + "String" + ], + "complexity": "Easy", + "successrate": 77.4, + "totalsubmissions": 83800, + "totalaccepted": 64849, + "likes": 301, + "dislikes": 985, + "hints": "If n is odd, return a string of size n formed only by 'a', else return string formed with n-1 'a' and 1 'b''.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 4", + "expected_output": ""pppz"", + "explanation": ""pppz" is a valid string since the character 'p' occurs three times and the character 'z' occurs once. Note that there are many other valid strings such as "ohhh" and "love"." + }, + { + "example_num": 2, + "expected_input": "n = 2", + "expected_output": ""xy"", + "explanation": ""xy" is a valid string since the characters 'x' and 'y' occur once. Note that there are many other valid strings such as "ag" and "ur"." + }, + { + "example_num": 3, + "expected_input": "n = 7", + "expected_output": ""holasss"", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d98", + "questionid": 717, + "title": "Lucky Numbers in a Matrix", + "slug": "lucky-numbers-in-a-matrix", + "description": "Given an m x n matrix of distinct numbers, return all lucky numbers in the matrix in any order. A lucky number is an element of the matrix such that it is the minimum element in its row and maximum in its column. ", + "category": [ + "Array", + "Matrix" + ], + "complexity": "Easy", + "successrate": 70.9, + "totalsubmissions": 88698, + "totalaccepted": 62865, + "likes": 929, + "dislikes": 65, + "hints": "Find out and save the minimum of each row and maximum of each column in two lists. Then scan through the whole matrix to identify the elements that satisfy the criteria.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "matrix = [[3,7,8],[9,11,13],[15,16,17]]", + "expected_output": "[15]", + "explanation": "15 is the only lucky number since it is the minimum in its row and the maximum in its column." + }, + { + "example_num": 2, + "expected_input": "matrix = [[1,10,4,2],[9,3,8,7],[15,16,17,12]]", + "expected_output": "[12]", + "explanation": "12 is the only lucky number since it is the minimum in its row and the maximum in its column." + }, + { + "example_num": 3, + "expected_input": "matrix = [[7,8],[1,2]]", + "expected_output": "[7]", + "explanation": "7 is the only lucky number since it is the minimum in its row and the maximum in its column." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720d99", + "questionid": 718, + "title": "Find a Corresponding Node of a Binary Tree in a Clone of That Tree", + "slug": "find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree", + "description": "Given two binary trees original and cloned and given a reference to a node target in the original tree. The cloned tree is a copy of the original tree. Return a reference to the same node in the cloned tree. Note that you are not allowed to change any of the two trees or the target node and the answer must be a reference to a node in the cloned tree. ", + "category": [ + "Tree", + "Depth-First Search", + "Breadth-First Search", + "Binary Tree" + ], + "complexity": "Medium", + "successrate": 85.5, + "totalsubmissions": 119043, + "totalaccepted": 101779, + "likes": 720, + "dislikes": 928, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "tree = [7,4,3,null,null,6,19], target = 3", + "expected_output": "3", + "explanation": "In all examples the original and cloned trees are shown. The target node is a green node from the original tree. The answer is the yellow node from the cloned tree." + }, + { + "example_num": 2, + "expected_input": "tree = [7], target = 7", + "expected_output": "7", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "tree = [8,null,6,null,5,null,4,null,3,null,2,null,1], target = 4", + "expected_output": "4", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720da0", + "questionid": 725, + "title": "Find Lucky Integer in an Array", + "slug": "find-lucky-integer-in-an-array", + "description": "Given an array of integers arr, a lucky integer is an integer that has a frequency in the array equal to its value. Return the largest lucky integer in the array. If there is no lucky integer return -1. ", + "category": [ + "Array", + "Hash Table", + "Counting" + ], + "complexity": "Easy", + "successrate": 63.6, + "totalsubmissions": 106984, + "totalaccepted": 68034, + "likes": 625, + "dislikes": 19, + "hints": "Count the frequency of each integer in the array. Get all lucky numbers and return the largest of them.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "arr = [2,2,3,4]", + "expected_output": "2", + "explanation": "The only lucky number in the array is 2 because frequency[2] == 2." + }, + { + "example_num": 2, + "expected_input": "arr = [1,2,2,3,3,3]", + "expected_output": "3", + "explanation": "1, 2 and 3 are all lucky numbers, return the largest of them." + }, + { + "example_num": 3, + "expected_input": "arr = [2,2,2,3,3]", + "expected_output": "-1", + "explanation": "There are no lucky numbers in the array." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720da4", + "questionid": 729, + "title": "Minimum Subsequence in Non-Increasing Order", + "slug": "minimum-subsequence-in-non-increasing-order", + "description": "Given the array nums, obtain a subsequence of the array whose sum of elements is strictly greater than the sum of the non included elements in such subsequence. If there are multiple solutions, return the subsequence with minimum size and if there still exist multiple solutions, return the subsequence with the maximum total sum of all its elements. A subsequence of an array can be obtained by erasing some (possibly zero) elements from the array. Note that the solution with the given constraints is guaranteed to be unique. Also return the answer sorted in non-increasing order. ", + "category": [ + "Array", + "Greedy", + "Sorting" + ], + "complexity": "Easy", + "successrate": 72.2, + "totalsubmissions": 68538, + "totalaccepted": 49486, + "likes": 349, + "dislikes": 376, + "hints": "Sort elements and take each element from the largest until accomplish the conditions.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [4,3,10,9,8]", + "expected_output": "[10,9]", + "explanation": "The subsequences [10,9] and [10,8] are minimal such that the sum of their elements is strictly greater than the sum of elements not included. However, the subsequence [10,9] has the maximum total sum of its elements. " + }, + { + "example_num": 2, + "expected_input": "nums = [4,4,7,6,7]", + "expected_output": "[7,7,6]", + "explanation": "The subsequence [7,7] has the sum of its elements equal to 14 which is not strictly greater than the sum of elements not included (14 = 4 + 4 + 6). Therefore, the subsequence [7,6,7] is the minimal satisfying the conditions. Note the subsequence has to be returned in non-increasing order." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720da5", + "questionid": 730, + "title": "Stone Game III", + "slug": "stone-game-iii", + "description": "Alice and Bob continue their games with piles of stones. There are several stones arranged in a row, and each stone has an associated value which is an integer given in the array stoneValue. Alice and Bob take turns, with Alice starting first. On each player's turn, that player can take 1, 2, or 3 stones from the first remaining stones in the row. The score of each player is the sum of the values of the stones taken. The score of each player is 0 initially. The objective of the game is to end with the highest score, and the winner is the player with the highest score and there could be a tie. The game continues until all the stones have been taken. Assume Alice and Bob play optimally. Return \"Alice\" if Alice will win, \"Bob\" if Bob will win, or \"Tie\" if they will end the game with the same score. ", + "category": [ + "Array", + "Math", + "Dynamic Programming", + "Game Theory" + ], + "complexity": "Hard", + "successrate": 60.2, + "totalsubmissions": 59197, + "totalaccepted": 35638, + "likes": 959, + "dislikes": 22, + "hints": "The game can be mapped to minmax game. Alice tries to maximize the total score and Bob tries to minimize it. Use dynamic programming to simulate the game. If the total score was 0 the game is \"Tie\", and if it has positive value then \"Alice\" wins, otherwise \"Bob\" wins.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "stoneValue = [1,2,3,7]", + "expected_output": ""Bob"", + "explanation": "Alice will always lose. Her best move will be to take three piles and the score become 6. Now the score of Bob is 7 and Bob wins." + }, + { + "example_num": 2, + "expected_input": "stoneValue = [1,2,3,-9]", + "expected_output": ""Alice"", + "explanation": "Alice must choose all the three piles at the first move to win and leave Bob with negative score.\nIf Alice chooses one pile her score will be 1 and the next move Bob's score becomes 5. In the next move, Alice will take the pile with value = -9 and lose.\nIf Alice chooses two piles her score will be 3 and the next move Bob's score becomes 3. In the next move, Alice will take the pile with value = -9 and also lose.\nRemember that both play optimally so here Alice will choose the scenario that makes her win." + }, + { + "example_num": 3, + "expected_input": "stoneValue = [1,2,3,6]", + "expected_output": ""Tie"", + "explanation": "Alice cannot win this game. She can end the game in a draw if she decided to choose all the first three piles, otherwise she will lose." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720da6", + "questionid": 731, + "title": "String Matching in an Array", + "slug": "string-matching-in-an-array", + "description": "Given an array of string words. Return all strings in words which is substring of another word in any order. String words[i] is substring of words[j], if can be obtained removing some characters to left and/or right side of words[j]. ", + "category": [ + "String", + "String Matching" + ], + "complexity": "Easy", + "successrate": 63.8, + "totalsubmissions": 84583, + "totalaccepted": 54002, + "likes": 509, + "dislikes": 72, + "hints": "Bruteforce to find if one string is substring of another or use KMP algorithm.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "words = ["mass","as","hero","superhero"]", + "expected_output": "["as","hero"]", + "explanation": ""as" is substring of "mass" and "hero" is substring of "superhero".\n["hero","as"] is also a valid answer." + }, + { + "example_num": 2, + "expected_input": "words = ["leetcode","et","code"]", + "expected_output": "["et","code"]", + "explanation": ""et", "code" are substring of "leetcode"." + }, + { + "example_num": 3, + "expected_input": "words = ["blue","green","bu"]", + "expected_output": "[]", + "explanation": "No string of words is substring of another string." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720da8", + "questionid": 733, + "title": "Number of Ways to Wear Different Hats to Each Other", + "slug": "number-of-ways-to-wear-different-hats-to-each-other", + "description": "There are n people and 40 types of hats labeled from 1 to 40. Given a 2D integer array hats, where hats[i] is a list of all hats preferred by the ith person. Return the number of ways that the n people wear different hats to each other. Since the answer may be too large, return it modulo 109 + 7. ", + "category": [ + "Array", + "Dynamic Programming", + "Bit Manipulation", + "Bitmask" + ], + "complexity": "Hard", + "successrate": 41.9, + "totalsubmissions": 21320, + "totalaccepted": 8931, + "likes": 591, + "dislikes": 7, + "hints": "Dynamic programming + bitmask. dp(peopleMask, idHat) number of ways to wear different hats given a bitmask (people visited) and used hats from 1 to idHat-1.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "hats = [[3,4],[4,5],[5]]", + "expected_output": "1", + "explanation": "There is only one way to choose hats given the conditions. \nFirst person choose hat 3, Second person choose hat 4 and last one hat 5." + }, + { + "example_num": 2, + "expected_input": "hats = [[3,5,1],[3,5]]", + "expected_output": "4", + "explanation": "There are 4 ways to choose hats:\n(3,5), (5,3), (1,3) and (1,5)" + }, + { + "example_num": 3, + "expected_input": "hats = [[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]]", + "expected_output": "24", + "explanation": "Each person can choose hats labeled from 1 to 4.\nNumber of Permutations of (1,2,3,4) = 24." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720dae", + "questionid": 739, + "title": "Diagonal Traverse II", + "slug": "diagonal-traverse-ii", + "description": "Given a 2D integer array nums, return all elements of nums in diagonal order as shown in the below images. ", + "category": [ + "Array", + "Sorting", + "Heap (Priority Queue)" + ], + "complexity": "Medium", + "successrate": 49.9, + "totalsubmissions": 80647, + "totalaccepted": 40270, + "likes": 810, + "dislikes": 75, + "hints": "Notice that numbers with equal sums of row and column indexes belong to the same diagonal. Store them in tuples (sum, row, val), sort them, and then regroup the answer.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [[1,2,3],[4,5,6],[7,8,9]]", + "expected_output": "[1,4,2,7,5,3,8,6,9]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "nums = [[1,2,3,4,5],[6,7],[8],[9,10,11],[12,13,14,15,16]]", + "expected_output": "[1,6,2,8,7,3,9,4,12,10,5,13,11,14,15,16]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720db0", + "questionid": 741, + "title": "Simplified Fractions", + "slug": "simplified-fractions", + "description": "Given an integer n, return a list of all simplified fractions between 0 and 1 (exclusive) such that the denominator is less-than-or-equal-to n. You can return the answer in any order. ", + "category": [ + "Math", + "String", + "Number Theory" + ], + "complexity": "Medium", + "successrate": 63.9, + "totalsubmissions": 32065, + "totalaccepted": 20489, + "likes": 237, + "dislikes": 32, + "hints": "A fraction is fully simplified if there is no integer that divides cleanly into the numerator and denominator. In other words the greatest common divisor of the numerator and the denominator of a simplified fraction is 1.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 2", + "expected_output": "["1/2"]", + "explanation": ""1/2" is the only unique fraction with a denominator less-than-or-equal-to 2." + }, + { + "example_num": 2, + "expected_input": "n = 3", + "expected_output": "["1/2","1/3","2/3"]", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "n = 4", + "expected_output": "["1/2","1/3","1/4","2/3","3/4"]", + "explanation": ""2/4" is not a simplified fraction because it can be simplified to "1/2"." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720db2", + "questionid": 743, + "title": "Destination City", + "slug": "destination-city", + "description": "You are given the array paths, where paths[i] = [cityAi, cityBi] means there exists a direct path going from cityAi to cityBi. Return the destination city, that is, the city without any path outgoing to another city. It is guaranteed that the graph of paths forms a line without any loop, therefore, there will be exactly one destination city. ", + "category": [ + "Hash Table", + "String" + ], + "complexity": "Easy", + "successrate": 77.7, + "totalsubmissions": 125127, + "totalaccepted": 97208, + "likes": 934, + "dislikes": 59, + "hints": "Start in any city and use the path to move to the next city. Eventually, you will reach a city with no path outgoing, this is the destination city.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "paths = [["London","New York"],["New York","Lima"],["Lima","Sao Paulo"]]", + "expected_output": ""Sao Paulo"", + "explanation": "Starting at "London" city you will reach "Sao Paulo" city which is the destination city. Your trip consist of: "London" -> "New York" -> "Lima" -> "Sao Paulo"." + }, + { + "example_num": 2, + "expected_input": "paths = [["B","C"],["D","B"],["C","A"]]", + "expected_output": ""A"", + "explanation": "All possible trips are: \n"D" -> "B" -> "C" -> "A". \n"B" -> "C" -> "A". \n"C" -> "A". \n"A". \nClearly the destination city is "A"." + }, + { + "example_num": 3, + "expected_input": "paths = [["A","Z"]]", + "expected_output": ""Z"", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720dba", + "questionid": 751, + "title": "Number of Students Doing Homework at a Given Time", + "slug": "number-of-students-doing-homework-at-a-given-time", + "description": "Given two integer arrays startTime and endTime and given an integer queryTime. The ith student started doing their homework at the time startTime[i] and finished it at time endTime[i]. Return the number of students doing their homework at time queryTime. More formally, return the number of students where queryTime lays in the interval [startTime[i], endTime[i]] inclusive. ", + "category": [ + "Array" + ], + "complexity": "Easy", + "successrate": 76.4, + "totalsubmissions": 108069, + "totalaccepted": 82597, + "likes": 564, + "dislikes": 128, + "hints": "Imagine that startTime[i] and endTime[i] form an interval (i.e. [startTime[i], endTime[i]]). The answer is how many times the queryTime laid in those mentioned intervals.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "startTime = [1,2,3], endTime = [3,2,7], queryTime = 4", + "expected_output": "1", + "explanation": "We have 3 students where:\nThe first student started doing homework at time 1 and finished at time 3 and wasn't doing anything at time 4.\nThe second student started doing homework at time 2 and finished at time 2 and also wasn't doing anything at time 4.\nThe third student started doing homework at time 3 and finished at time 7 and was the only student doing homework at time 4." + }, + { + "example_num": 2, + "expected_input": "startTime = [4], endTime = [4], queryTime = 4", + "expected_output": "1", + "explanation": "The only student was doing their homework at the queryTime." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720dbd", + "questionid": 754, + "title": "Check If a Word Occurs As a Prefix of Any Word in a Sentence", + "slug": "check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence", + "description": "Given a sentence that consists of some words separated by a single space, and a searchWord, check if searchWord is a prefix of any word in sentence. Return the index of the word in sentence (1-indexed) where searchWord is a prefix of this word. If searchWord is a prefix of more than one word, return the index of the first word (minimum index). If there is no such word return -1. A prefix of a string s is any leading contiguous substring of s. ", + "category": [ + "String", + "String Matching" + ], + "complexity": "Easy", + "successrate": 64.5, + "totalsubmissions": 75561, + "totalaccepted": 48740, + "likes": 495, + "dislikes": 23, + "hints": "First extract the words of the sentence. Check for each word if searchWord occurs at index 0, if so return the index of this word (1-indexed) If searchWord doesn't exist as a prefix of any word return the default value (-1).", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "sentence = "i love eating burger", searchWord = "burg"", + "expected_output": "4", + "explanation": ""burg" is prefix of "burger" which is the 4th word in the sentence." + }, + { + "example_num": 2, + "expected_input": "sentence = "this problem is an easy problem", searchWord = "pro"", + "expected_output": "2", + "explanation": ""pro" is prefix of "problem" which is the 2nd and the 6th word in the sentence, but we return 2 as it's the minimal index." + }, + { + "example_num": 3, + "expected_input": "sentence = "i am tired", searchWord = "you"", + "expected_output": "-1", + "explanation": ""you" is not a prefix of any word in the sentence." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720dbe", + "questionid": 755, + "title": "Maximum Number of Vowels in a Substring of Given Length", + "slug": "maximum-number-of-vowels-in-a-substring-of-given-length", + "description": "Given a string s and an integer k, return the maximum number of vowel letters in any substring of s with length k. Vowel letters in English are 'a', 'e', 'i', 'o', and 'u'. ", + "category": [ + "String", + "Sliding Window" + ], + "complexity": "Medium", + "successrate": 57.4, + "totalsubmissions": 73875, + "totalaccepted": 42389, + "likes": 691, + "dislikes": 37, + "hints": "Keep a window of size k and maintain the number of vowels in it. Keep moving the window and update the number of vowels while moving. Answer is max number of vowels of any window.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "abciiidef", k = 3", + "expected_output": "3", + "explanation": "The substring "iii" contains 3 vowel letters." + }, + { + "example_num": 2, + "expected_input": "s = "aeiou", k = 2", + "expected_output": "2", + "explanation": "Any substring of length 2 contains 2 vowels." + }, + { + "example_num": 3, + "expected_input": "s = "leetcode", k = 3", + "expected_output": "2", + "explanation": ""lee", "eet" and "ode" contain 2 vowels." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720dc5", + "questionid": 762, + "title": "Probability of a Two Boxes Having The Same Number of Distinct Balls", + "slug": "probability-of-a-two-boxes-having-the-same-number-of-distinct-balls", + "description": "Given 2n balls of k distinct colors. You will be given an integer array balls of size k where balls[i] is the number of balls of color i. All the balls will be shuffled uniformly at random, then we will distribute the first n balls to the first box and the remaining n balls to the other box (Please read the explanation of the second example carefully). Please note that the two boxes are considered different. For example, if we have two balls of colors a and b, and two boxes [] and (), then the distribution [a] (b) is considered different than the distribution [b] (a) (Please read the explanation of the first example carefully). Return the probability that the two boxes have the same number of distinct balls. Answers within 10-5 of the actual value will be accepted as correct. ", + "category": [ + "Math", + "Dynamic Programming", + "Backtracking", + "Combinatorics", + "Probability and Statistics" + ], + "complexity": "Hard", + "successrate": 60.9, + "totalsubmissions": 9746, + "totalaccepted": 5937, + "likes": 193, + "dislikes": 142, + "hints": "Check how many ways you can distribute the balls between the boxes. Consider that one way you will use (x1, x2, x3, ..., xk) where xi is the number of balls from colour i. The probability of achieving this way randomly is ( (ball1 C x1) * (ball2 C x2) * (ball3 C x3) * ... * (ballk C xk)) / (2n C n). The probability of a draw is the sigma of probabilities of different ways to achieve draw. Can you use Dynamic programming to solve this problem in a better complexity ?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "balls = [1,1]", + "expected_output": "1.00000", + "explanation": "Only 2 ways to divide the balls equally:\n- A ball of color 1 to box 1 and a ball of color 2 to box 2\n- A ball of color 2 to box 1 and a ball of color 1 to box 2\nIn both ways, the number of distinct colors in each box is equal. The probability is 2/2 = 1" + }, + { + "example_num": 2, + "expected_input": "balls = [2,1,1]", + "expected_output": "0.66667", + "explanation": "We have the set of balls [1, 1, 2, 3]\nThis set of balls will be shuffled randomly and we may have one of the 12 distinct shuffles with equal probability (i.e. 1/12):\n[1,1 / 2,3], [1,1 / 3,2], [1,2 / 1,3], [1,2 / 3,1], [1,3 / 1,2], [1,3 / 2,1], [2,1 / 1,3], [2,1 / 3,1], [2,3 / 1,1], [3,1 / 1,2], [3,1 / 2,1], [3,2 / 1,1]\nAfter that, we add the first two balls to the first box and the second two balls to the second box.\nWe can see that 8 of these 12 possible random distributions have the same number of distinct colors of balls in each box.\nProbability is 8/12 = 0.66667" + }, + { + "example_num": 3, + "expected_input": "balls = [1,2,1,2]", + "expected_output": "0.60000", + "explanation": "The set of balls is [1, 2, 2, 3, 4, 4]. It is hard to display all the 180 possible random shuffles of this set but it is easy to check that 108 of them will have the same number of distinct colors in each box.\nProbability = 108 / 180 = 0.6" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720dcb", + "questionid": 768, + "title": "Running Sum of 1d Array", + "slug": "running-sum-of-1d-array", + "description": "Given an array nums. We define a running sum of an array as runningSum[i] = sum(nums[0]...nums[i]). Return the running sum of nums. ", + "category": [ + "Array", + "Prefix Sum" + ], + "complexity": "Easy", + "successrate": 89.6, + "totalsubmissions": 566858, + "totalaccepted": 507777, + "likes": 2513, + "dislikes": 177, + "hints": "Think about how we can calculate the i-th number in the running sum from the (i-1)-th number.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,2,3,4]", + "expected_output": "[1,3,6,10]", + "explanation": "Running sum is obtained as follows: [1, 1+2, 1+2+3, 1+2+3+4]." + }, + { + "example_num": 2, + "expected_input": "nums = [1,1,1,1,1]", + "expected_output": "[1,2,3,4,5]", + "explanation": "Running sum is obtained as follows: [1, 1+1, 1+1+1, 1+1+1+1, 1+1+1+1+1]." + }, + { + "example_num": 3, + "expected_input": "nums = [3,1,2,10,1]", + "expected_output": "[3,4,6,16,17]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720dd7", + "questionid": 780, + "title": "Max Value of Equation", + "slug": "max-value-of-equation", + "description": "You are given an array points containing the coordinates of points on a 2D plane, sorted by the x-values, where points[i] = [xi, yi] such that xi < xj for all 1 <= i < j <= points.length. You are also given an integer k. Return the maximum value of the equation yi + yj + |xi - xj| where |xi - xj| <= k and 1 <= i < j <= points.length. It is guaranteed that there exists at least one pair of points that satisfy the constraint |xi - xj| <= k. ", + "category": [ + "Array", + "Queue", + "Sliding Window", + "Heap (Priority Queue)", + "Monotonic Queue" + ], + "complexity": "Hard", + "successrate": 46.9, + "totalsubmissions": 63274, + "totalaccepted": 29650, + "likes": 782, + "dislikes": 29, + "hints": "Use a priority queue to store for each point i, the tuple [yi-xi, xi] Loop through the array and pop elements from the heap if the condition xj - xi > k, where j is the current index and i is the point on top the queue. After popping elements from the queue. If the queue is not empty, calculate the equation with the current point and the point on top of the queue and maximize the answer.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "points = [[1,3],[2,0],[5,10],[6,-10]], k = 1", + "expected_output": "4", + "explanation": "The first two points satisfy the condition |xi - xj| <= 1 and if we calculate the equation we get 3 + 0 + |1 - 2| = 4. Third and fourth points also satisfy the condition and give a value of 10 + -10 + |5 - 6| = 1.\nNo other pairs satisfy the condition, so we return the max of 4 and 1." + }, + { + "example_num": 2, + "expected_input": "points = [[0,0],[3,0],[9,2]], k = 3", + "expected_output": "3\nExplanation: Only the first two points have an absolute difference of 3 or less in the x-values, and give the value of 0 + 0 + |0 - 3| = 3.", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720dcc", + "questionid": 769, + "title": "Least Number of Unique Integers after K Removals", + "slug": "least-number-of-unique-integers-after-k-removals", + "description": "Given an array of integers arr and an integer k. Find the least number of unique integers after removing exactly k elements. ", + "category": [ + "Array", + "Hash Table", + "Greedy", + "Sorting", + "Counting" + ], + "complexity": "Medium", + "successrate": 60.2, + "totalsubmissions": 114592, + "totalaccepted": 68982, + "likes": 868, + "dislikes": 64, + "hints": "Use a map to count the frequencies of the numbers in the array. An optimal strategy is to remove the numbers with the smallest count first.", + "deleted": false, + "examples": [] + }, + { + "_id": "66f925ddfdfb8e1665720dd9", + "questionid": 782, + "title": "Last Moment Before All Ants Fall Out of a Plank", + "slug": "last-moment-before-all-ants-fall-out-of-a-plank", + "description": "We have a wooden plank of the length n units. Some ants are walking on the plank, each ant moves with a speed of 1 unit per second. Some of the ants move to the left, the other move to the right. When two ants moving in two different directions meet at some point, they change their directions and continue moving again. Assume changing directions does not take any additional time. When an ant reaches one end of the plank at a time t, it falls out of the plank immediately. Given an integer n and two integer arrays left and right, the positions of the ants moving to the left and the right, return the moment when the last ant(s) fall out of the plank. ", + "category": [ + "Array", + "Brainteaser", + "Simulation" + ], + "complexity": "Medium", + "successrate": 54.8, + "totalsubmissions": 27754, + "totalaccepted": 15220, + "likes": 335, + "dislikes": 180, + "hints": "The ants change their way when they meet is equivalent to continue moving without changing their direction. Answer is the max distance for one ant to reach the end of the plank in the facing direction.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 4, left = [4,3], right = [0,1]", + "expected_output": "4", + "explanation": "In the image above:\n-The ant at index 0 is named A and going to the right.\n-The ant at index 1 is named B and going to the right.\n-The ant at index 3 is named C and going to the left.\n-The ant at index 4 is named D and going to the left.\nThe last moment when an ant was on the plank is t = 4 seconds. After that, it falls immediately out of the plank. (i.e., We can say that at t = 4.0000000001, there are no ants on the plank)." + }, + { + "example_num": 2, + "expected_input": "n = 7, left = [], right = [0,1,2,3,4,5,6,7]", + "expected_output": "7", + "explanation": "All ants are going to the right, the ant at index 0 needs 7 seconds to fall." + }, + { + "example_num": 3, + "expected_input": "n = 7, left = [0,1,2,3,4,5,6,7], right = []", + "expected_output": "7", + "explanation": "All ants are going to the left, the ant at index 7 needs 7 seconds to fall." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720dda", + "questionid": 783, + "title": "Count Submatrices With All Ones", + "slug": "count-submatrices-with-all-ones", + "description": "Given an m x n binary matrix mat, return the number of submatrices that have all ones. ", + "category": [ + "Array", + "Dynamic Programming", + "Stack", + "Matrix", + "Monotonic Stack" + ], + "complexity": "Medium", + "successrate": 58.6, + "totalsubmissions": 59639, + "totalaccepted": 34967, + "likes": 1499, + "dislikes": 116, + "hints": "For each row i, create an array nums where: if mat[i][j] == 0 then nums[j] = 0 else nums[j] = nums[j-1] +1. In the row i, number of rectangles between column j and k(inclusive) and ends in row i, is equal to SUM(min(nums[j, .. idx])) where idx go from j to k. Expected solution is O(n^3).", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "mat = [[1,0,1],[1,1,0],[1,1,0]]", + "expected_output": "13", + "explanation": "There are 6 rectangles of side 1x1.\nThere are 2 rectangles of side 1x2.\nThere are 3 rectangles of side 2x1.\nThere is 1 rectangle of side 2x2. \nThere is 1 rectangle of side 3x1.\nTotal number of rectangles = 6 + 2 + 3 + 1 + 1 = 13." + }, + { + "example_num": 2, + "expected_input": "mat = [[0,1,1,0],[0,1,1,1],[1,1,1,0]]", + "expected_output": "24", + "explanation": "There are 8 rectangles of side 1x1.\nThere are 5 rectangles of side 1x2.\nThere are 2 rectangles of side 1x3. \nThere are 4 rectangles of side 2x1.\nThere are 2 rectangles of side 2x2. \nThere are 2 rectangles of side 3x1. \nThere is 1 rectangle of side 3x2. \nTotal number of rectangles = 8 + 5 + 2 + 4 + 2 + 2 + 1 = 24." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720ddf", + "questionid": 788, + "title": "Minimum Number of Increments on Subarrays to Form a Target Array", + "slug": "minimum-number-of-increments-on-subarrays-to-form-a-target-array", + "description": "You are given an integer array target. You have an integer array initial of the same size as target with all elements initially zeros. In one operation you can choose any subarray from initial and increment each value by one. Return the minimum number of operations to form a target array from initial. The test cases are generated so that the answer fits in a 32-bit integer. ", + "category": [ + "Array", + "Dynamic Programming", + "Stack", + "Greedy", + "Monotonic Stack" + ], + "complexity": "Hard", + "successrate": 68, + "totalsubmissions": 35423, + "totalaccepted": 24071, + "likes": 849, + "dislikes": 52, + "hints": "For a given range of values in target, an optimal strategy is to increment the entire range by the minimum value. The minimum in a range could be obtained with Range minimum query or Segment trees algorithm.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "target = [1,2,3,2,1]", + "expected_output": "3", + "explanation": "We need at least 3 operations to form the target array from the initial array.\n[0,0,0,0,0] increment 1 from index 0 to 4 (inclusive).\n[1,1,1,1,1] increment 1 from index 1 to 3 (inclusive).\n[1,2,2,2,1] increment 1 at index 2.\n[1,2,3,2,1] target array is formed." + }, + { + "example_num": 2, + "expected_input": "target = [3,1,1,2]", + "expected_output": "4", + "explanation": "[0,0,0,0] -> [1,1,1,1] -> [1,1,1,2] -> [2,1,1,2] -> [3,1,1,2]" + }, + { + "example_num": 3, + "expected_input": "target = [3,1,5,4,2]", + "expected_output": "7", + "explanation": "[0,0,0,0,0] -> [1,1,1,1,1] -> [2,1,1,1,1] -> [3,1,1,1,1] -> [3,1,2,2,2] -> [3,1,3,3,2] -> [3,1,4,4,2] -> [3,1,5,4,2]." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720de3", + "questionid": 792, + "title": "Water Bottles", + "slug": "water-bottles", + "description": "There are numBottles water bottles that are initially full of water. You can exchange numExchange empty water bottles from the market with one full water bottle. The operation of drinking a full water bottle turns it into an empty bottle. Given the two integers numBottles and numExchange, return the maximum number of water bottles you can drink. ", + "category": [ + "Math", + "Simulation" + ], + "complexity": "Easy", + "successrate": 60.4, + "totalsubmissions": 80287, + "totalaccepted": 48484, + "likes": 667, + "dislikes": 54, + "hints": "Simulate the process until there are not enough empty bottles for even one full bottle of water.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "numBottles = 9, numExchange = 3", + "expected_output": "13", + "explanation": "You can exchange 3 empty bottles to get 1 full water bottle.\nNumber of water bottles you can drink: 9 + 3 + 1 = 13." + }, + { + "example_num": 2, + "expected_input": "numBottles = 15, numExchange = 4", + "expected_output": "19", + "explanation": "You can exchange 4 empty bottles to get 1 full water bottle. \nNumber of water bottles you can drink: 15 + 3 + 1 = 19." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720de4", + "questionid": 793, + "title": "Number of Nodes in the Sub-Tree With the Same Label", + "slug": "number-of-nodes-in-the-sub-tree-with-the-same-label", + "description": "You are given a tree (i.e. a connected, undirected graph that has no cycles) consisting of n nodes numbered from 0 to n - 1 and exactly n - 1 edges. The root of the tree is the node 0, and each node of the tree has a label which is a lower-case character given in the string labels (i.e. The node with the number i has the label labels[i]). The edges array is given on the form edges[i] = [ai, bi], which means there is an edge between nodes ai and bi in the tree. Return an array of size n where ans[i] is the number of nodes in the subtree of the ith node which have the same label as node i. A subtree of a tree T is the tree consisting of a node in T and all of its descendant nodes. ", + "category": [ + "Hash Table", + "Tree", + "Depth-First Search", + "Breadth-First Search", + "Counting" + ], + "complexity": "Medium", + "successrate": 39.8, + "totalsubmissions": 41122, + "totalaccepted": 16365, + "likes": 379, + "dislikes": 357, + "hints": "Start traversing the tree and each node should return a vector to its parent node. The vector should be of length 26 and have the count of all the labels in the sub-tree of this node.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], labels = "abaedcd"", + "expected_output": "[2,1,1,1,1,1,1]", + "explanation": "Node 0 has label 'a' and its sub-tree has node 2 with label 'a' as well, thus the answer is 2. Notice that any node is part of its sub-tree.\nNode 1 has a label 'b'. The sub-tree of node 1 contains nodes 1,4 and 5, as nodes 4 and 5 have different labels than node 1, the answer is just 1 (the node itself)." + }, + { + "example_num": 2, + "expected_input": "n = 4, edges = [[0,1],[1,2],[0,3]], labels = "bbbb"", + "expected_output": "[4,2,1,1]", + "explanation": "The sub-tree of node 2 contains only node 2, so the answer is 1.\nThe sub-tree of node 3 contains only node 3, so the answer is 1.\nThe sub-tree of node 1 contains nodes 1 and 2, both have label 'b', thus the answer is 2.\nThe sub-tree of node 0 contains nodes 0, 1, 2 and 3, all with label 'b', thus the answer is 4." + }, + { + "example_num": 3, + "expected_input": "n = 5, edges = [[0,1],[0,2],[1,3],[0,4]], labels = "aabab"", + "expected_output": "[3,2,1,1,1]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720de8", + "questionid": 797, + "title": "Shuffle String", + "slug": "shuffle-string", + "description": "You are given a string s and an integer array indices of the same length. The string s will be shuffled such that the character at the ith position moves to indices[i] in the shuffled string. Return the shuffled string. ", + "category": [ + "Array", + "String" + ], + "complexity": "Easy", + "successrate": 85.8, + "totalsubmissions": 230975, + "totalaccepted": 198080, + "likes": 1333, + "dislikes": 248, + "hints": "You can create an auxiliary string t of length n. Assign t[indexes[i]] to s[i] for each i from 0 to n-1.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "codeleet", indices = [4,5,6,7,0,2,1,3]", + "expected_output": ""leetcode"", + "explanation": "As shown, "codeleet" becomes "leetcode" after shuffling." + }, + { + "example_num": 2, + "expected_input": "s = "abc", indices = [0,1,2]", + "expected_output": ""abc"", + "explanation": "After shuffling, each character remains in its position." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720dea", + "questionid": 799, + "title": "Number of Good Leaf Nodes Pairs", + "slug": "number-of-good-leaf-nodes-pairs", + "description": "You are given the root of a binary tree and an integer distance. A pair of two different leaf nodes of a binary tree is said to be good if the length of the shortest path between them is less than or equal to distance. Return the number of good leaf node pairs in the tree. ", + "category": [ + "Tree", + "Depth-First Search", + "Binary Tree" + ], + "complexity": "Medium", + "successrate": 59.6, + "totalsubmissions": 42009, + "totalaccepted": 25053, + "likes": 1069, + "dislikes": 21, + "hints": "Start DFS from each leaf node. stop the DFS when the number of steps done > distance. If you reach another leaf node within distance steps, add 1 to the answer. Note that all pairs will be counted twice so divide the answer by 2.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [1,2,3,null,4], distance = 3", + "expected_output": "1", + "explanation": "The leaf nodes of the tree are 3 and 4 and the length of the shortest path between them is 3. This is the only good pair." + }, + { + "example_num": 2, + "expected_input": "root = [1,2,3,4,5,6,7], distance = 3", + "expected_output": "2", + "explanation": "The good pairs are [4,5] and [6,7] with shortest path = 2. The pair [4,6] is not good because the length of ther shortest path between them is 4." + }, + { + "example_num": 3, + "expected_input": "root = [7,1,4,6,null,5,3,null,null,null,null,null,2], distance = 3", + "expected_output": "1", + "explanation": "The only good pair is [2,5]." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720deb", + "questionid": 800, + "title": "Find the Winner of an Array Game", + "slug": "find-the-winner-of-an-array-game", + "description": "Given an integer array arr of distinct integers and an integer k. A game will be played between the first two elements of the array (i.e. arr[0] and arr[1]). In each round of the game, we compare arr[0] with arr[1], the larger integer wins and remains at position 0, and the smaller integer moves to the end of the array. The game ends when an integer wins k consecutive rounds. Return the integer which will win the game. It is guaranteed that there will be a winner of the game. ", + "category": [ + "Array", + "Simulation" + ], + "complexity": "Medium", + "successrate": 48.8, + "totalsubmissions": 49686, + "totalaccepted": 24246, + "likes": 449, + "dislikes": 25, + "hints": "If k ‰¥ arr.length return the max element of the array. If k < arr.length simulate the game until a number wins k consecutive games.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "arr = [2,1,3,5,4,6,7], k = 2", + "expected_output": "5", + "explanation": "Let's see the rounds of the game:\nRound | arr | winner | win_count\n 1 | [2,1,3,5,4,6,7] | 2 | 1\n 2 | [2,3,5,4,6,7,1] | 3 | 1\n 3 | [3,5,4,6,7,1,2] | 5 | 1\n 4 | [5,4,6,7,1,2,3] | 5 | 2\nSo we can see that 4 rounds will be played and 5 is the winner because it wins 2 consecutive games." + }, + { + "example_num": 2, + "expected_input": "arr = [3,2,1], k = 10", + "expected_output": "3", + "explanation": "3 will win the first 10 rounds consecutively." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720dfb", + "questionid": 816, + "title": "Maximum Length of Subarray With Positive Product", + "slug": "maximum-length-of-subarray-with-positive-product", + "description": "Given an array of integers nums, find the maximum length of a subarray where the product of all its elements is positive. A subarray of an array is a consecutive sequence of zero or more values taken out of that array. Return the maximum length of a subarray with positive product. ", + "category": [ + "Array", + "Dynamic Programming", + "Greedy" + ], + "complexity": "Medium", + "successrate": 42.9, + "totalsubmissions": 104080, + "totalaccepted": 44627, + "likes": 1312, + "dislikes": 23, + "hints": "Split the whole array into subarrays by zeroes since a subarray with positive product cannot contain any zero. If the subarray has even number of negative numbers, the whole subarray has positive product. Otherwise, we have two choices, either - remove the prefix till the first negative element in this subarray, or remove the suffix starting from the last negative element in this subarray.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,-2,-3,4]", + "expected_output": "4", + "explanation": "The array nums already has a positive product of 24." + }, + { + "example_num": 2, + "expected_input": "nums = [0,1,-2,-3,-4]", + "expected_output": "3", + "explanation": "The longest subarray with positive product is [1,-2,-3] which has a product of 6.\nNotice that we cannot include 0 in the subarray since that'll make the product 0 which is not positive." + }, + { + "example_num": 3, + "expected_input": "nums = [-1,-2,-3,0,1]", + "expected_output": "2", + "explanation": "The longest subarray with positive product is [-1,-2] or [-2,-3]." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720dfd", + "questionid": 818, + "title": "Number of Ways to Reorder Array to Get Same BST", + "slug": "number-of-ways-to-reorder-array-to-get-same-bst", + "description": "Given an array nums that represents a permutation of integers from 1 to n. We are going to construct a binary search tree (BST) by inserting the elements of nums in order into an initially empty BST. Find the number of different ways to reorder nums so that the constructed BST is identical to that formed from the original array nums. Return the number of ways to reorder nums such that the BST formed is identical to the original BST formed from nums. Since the answer may be very large, return it modulo 109 + 7. ", + "category": [ + "Array", + "Math", + "Divide and Conquer", + "Dynamic Programming", + "Tree", + "Union Find", + "Binary Search Tree", + "Memoization", + "Combinatorics", + "Binary Tree" + ], + "complexity": "Hard", + "successrate": 49.2, + "totalsubmissions": 19046, + "totalaccepted": 9367, + "likes": 397, + "dislikes": 43, + "hints": "Use a divide and conquer strategy. The first number will always be the root. Consider the numbers smaller and larger than the root separately. When merging the results together, how many ways can you order x elements in x+y positions?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [2,1,3]", + "expected_output": "1", + "explanation": "We can reorder nums to be [2,3,1] which will yield the same BST. There are no other ways to reorder nums which will yield the same BST." + }, + { + "example_num": 2, + "expected_input": "nums = [3,4,5,1,2]", + "expected_output": "5", + "explanation": "The following 5 arrays will yield the same BST: \n[3,1,2,4,5]\n[3,1,4,2,5]\n[3,1,4,5,2]\n[3,4,1,2,5]\n[3,4,1,5,2]" + }, + { + "example_num": 3, + "expected_input": "nums = [1,2,3]", + "expected_output": "0", + "explanation": "There are no other orderings of nums that will yield the same BST." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e04", + "questionid": 825, + "title": "Find Valid Matrix Given Row and Column Sums", + "slug": "find-valid-matrix-given-row-and-column-sums", + "description": "You are given two arrays rowSum and colSum of non-negative integers where rowSum[i] is the sum of the elements in the ith row and colSum[j] is the sum of the elements of the jth column of a 2D matrix. In other words, you do not know the elements of the matrix, but you do know the sums of each row and column. Find any matrix of non-negative integers of size rowSum.length x colSum.length that satisfies the rowSum and colSum requirements. Return a 2D array representing any matrix that fulfills the requirements. It's guaranteed that at least one matrix that fulfills the requirements exists. ", + "category": [ + "Array", + "Greedy", + "Matrix" + ], + "complexity": "Medium", + "successrate": 78.3, + "totalsubmissions": 31857, + "totalaccepted": 24953, + "likes": 880, + "dislikes": 26, + "hints": "Find the smallest rowSum or colSum, and let it be x. Place that number in the grid, and subtract x from rowSum and colSum. Continue until all the sums are satisfied.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "rowSum = [3,8], colSum = [4,7]", + "expected_output": "[[3,0],\n [1,7]]", + "explanation": "0th row: 3 + 0 = 3 == rowSum[0]\n1st row: 1 + 7 = 8 == rowSum[1]\n0th column: 3 + 1 = 4 == colSum[0]\n1st column: 0 + 7 = 7 == colSum[1]\nThe row and column sums match, and all matrix elements are non-negative.\nAnother possible matrix is: [[1,2],\n [3,5]]" + }, + { + "example_num": 2, + "expected_input": "rowSum = [5,7,10], colSum = [8,6,8]", + "expected_output": "[[0,5,0],\n [6,1,0],\n [2,0,8]]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e07", + "questionid": 828, + "title": "Maximum Non Negative Product in a Matrix", + "slug": "maximum-non-negative-product-in-a-matrix", + "description": "You are given a m x n matrix grid. Initially, you are located at the top-left corner (0, 0), and in each step, you can only move right or down in the matrix. Among all possible paths starting from the top-left corner (0, 0) and ending in the bottom-right corner (m - 1, n - 1), find the path with the maximum non-negative product. The product of a path is the product of all integers in the grid cells visited along the path. Return the maximum non-negative product modulo 109 + 7. If the maximum product is negative, return -1. Notice that the modulo is performed after getting the maximum product. ", + "category": [ + "Array", + "Dynamic Programming", + "Matrix" + ], + "complexity": "Medium", + "successrate": 33, + "totalsubmissions": 49057, + "totalaccepted": 16210, + "likes": 530, + "dislikes": 23, + "hints": "Use Dynamic programming. Keep the highest value and lowest value you can achieve up to a point.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "grid = [[-1,-2,-3],[-2,-3,-3],[-3,-3,-2]]", + "expected_output": "-1", + "explanation": "It is not possible to get non-negative product in the path from (0, 0) to (2, 2), so return -1." + }, + { + "example_num": 2, + "expected_input": "grid = [[1,-2,1],[1,-2,1],[3,-4,1]]", + "expected_output": "8", + "explanation": "Maximum non-negative product is shown (1 * 1 * -2 * -4 * 1 = 8)." + }, + { + "example_num": 3, + "expected_input": "grid = [[1,3],[0,-4]]", + "expected_output": "0", + "explanation": "Maximum non-negative product is shown (1 * 0 * -4 = 0)." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e0a", + "questionid": 831, + "title": "Maximum Number of Achievable Transfer Requests", + "slug": "maximum-number-of-achievable-transfer-requests", + "description": "We have n buildings numbered from 0 to n - 1. Each building has a number of employees. It's transfer season, and some employees want to change the building they reside in. You are given an array requests where requests[i] = [fromi, toi] represents an employee's request to transfer from building fromi to building toi. All buildings are full, so a list of requests is achievable only if for each building, the net change in employee transfers is zero. This means the number of employees leaving is equal to the number of employees moving in. For example if n = 3 and two employees are leaving building 0, one is leaving building 1, and one is leaving building 2, there should be two employees moving to building 0, one employee moving to building 1, and one employee moving to building 2. Return the maximum number of achievable requests. ", + "category": [ + "Array", + "Backtracking", + "Bit Manipulation", + "Enumeration" + ], + "complexity": "Hard", + "successrate": 50.7, + "totalsubmissions": 15465, + "totalaccepted": 7841, + "likes": 217, + "dislikes": 26, + "hints": "Think brute force When is a subset of requests okay?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 5, requests = [[0,1],[1,0],[0,1],[1,2],[2,0],[3,4]]", + "expected_output": "5\nExplantion: Let's see the requests:\nFrom building 0 we have employees x and y and both want to move to building 1.\nFrom building 1 we have employees a and b and they want to move to buildings 2 and 0 respectively.\nFrom building 2 we have employee z and they want to move to building 0.\nFrom building 3 we have employee c and they want to move to building 4.\nFrom building 4 we don't have any requests.\nWe can achieve the requests of users x and b by swapping their places.\nWe can achieve the requests of users y, a and z by swapping the places in the 3 buildings.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "n = 3, requests = [[0,0],[1,2],[2,1]]", + "expected_output": "3\nExplantion: Let's see the requests:\nFrom building 0 we have employee x and they want to stay in the same building 0.\nFrom building 1 we have employee y and they want to move to building 2.\nFrom building 2 we have employee z and they want to move to building 1.\nWe can achieve all the requests.", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "n = 4, requests = [[0,3],[3,1],[1,2],[2,0]]", + "expected_output": "4", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720dd1", + "questionid": 774, + "title": "Range Sum of Sorted Subarray Sums", + "slug": "range-sum-of-sorted-subarray-sums", + "description": "You are given the array nums consisting of n positive integers. You computed the sum of all non-empty continuous subarrays from the array and then sorted them in non-decreasing order, creating a new array of n * (n + 1) / 2 numbers. Return the sum of the numbers from index left to index right (indexed from 1), inclusive, in the new array. Since the answer can be a huge number return it modulo 109 + 7. ", + "category": [ + "Array", + "Two Pointers", + "Binary Search", + "Sorting" + ], + "complexity": "Medium", + "successrate": 59.1, + "totalsubmissions": 41099, + "totalaccepted": 24279, + "likes": 560, + "dislikes": 102, + "hints": "Compute all sums and save it in array. Then just go from LEFT to RIGHT index and calculate answer modulo 1e9 + 7.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,2,3,4], n = 4, left = 1, right = 5", + "expected_output": "13", + "explanation": "All subarray sums are 1, 3, 6, 10, 2, 5, 9, 3, 7, 4. After sorting them in non-decreasing order we have the new array [1, 2, 3, 3, 4, 5, 6, 7, 9, 10]. The sum of the numbers from index le = 1 to ri = 5 is 1 + 2 + 3 + 3 + 4 = 13." + }, + { + "example_num": 2, + "expected_input": "nums = [1,2,3,4], n = 4, left = 3, right = 4", + "expected_output": "6", + "explanation": "The given array is the same as example 1. We have the new array [1, 2, 3, 3, 4, 5, 6, 7, 9, 10]. The sum of the numbers from index le = 3 to ri = 4 is 3 + 3 = 6." + }, + { + "example_num": 3, + "expected_input": "nums = [1,2,3,4], n = 4, left = 1, right = 10", + "expected_output": "50", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720de0", + "questionid": 789, + "title": "Number of Good Pairs", + "slug": "number-of-good-pairs", + "description": "Given an array of integers nums, return the number of good pairs. A pair (i, j) is called good if nums[i] == nums[j] and i < j. ", + "category": [ + "Array", + "Hash Table", + "Math", + "Counting" + ], + "complexity": "Easy", + "successrate": 87.9, + "totalsubmissions": 325449, + "totalaccepted": 286227, + "likes": 2366, + "dislikes": 141, + "hints": "Count how many times each number appears. If a number appears n times, then n * (n €“ 1) // 2 good pairs can be made with this number.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,2,3,1,1,3]", + "expected_output": "4", + "explanation": "There are 4 good pairs (0,3), (0,4), (3,4), (2,5) 0-indexed." + }, + { + "example_num": 2, + "expected_input": "nums = [1,1,1,1]", + "expected_output": "6", + "explanation": "Each pair in the array are good." + }, + { + "example_num": 3, + "expected_input": "nums = [1,2,3]", + "expected_output": "0", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720de5", + "questionid": 794, + "title": "Find a Value of a Mysterious Function Closest to Target", + "slug": "find-a-value-of-a-mysterious-function-closest-to-target", + "description": " Winston was given the above mysterious function func. He has an integer array arr and an integer target and he wants to find the values l and r that make the value |func(arr, l, r) - target| minimum possible. Return the minimum possible value of |func(arr, l, r) - target|. Notice that func should be called with the values l and r where 0 <= l, r < arr.length. ", + "category": [ + "Array", + "Binary Search", + "Bit Manipulation", + "Segment Tree" + ], + "complexity": "Hard", + "successrate": 43.6, + "totalsubmissions": 16901, + "totalaccepted": 7361, + "likes": 260, + "dislikes": 10, + "hints": "If the and value of sub-array arr[i...j] is ‰¥ the and value of the sub-array arr[i...j+1]. For each index i using binary search or ternary search find the index j where |target - AND(arr[i...j])| is minimum, minimize this value with the global answer.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "arr = [9,12,3,7,15], target = 5", + "expected_output": "2", + "explanation": "Calling func with all the pairs of [l,r] = [[0,0],[1,1],[2,2],[3,3],[4,4],[0,1],[1,2],[2,3],[3,4],[0,2],[1,3],[2,4],[0,3],[1,4],[0,4]], Winston got the following results [9,12,3,7,15,8,0,3,7,0,0,3,0,0,0]. The value closest to 5 is 7 and 3, thus the minimum difference is 2." + }, + { + "example_num": 2, + "expected_input": "arr = [1000000,1000000,1000000], target = 1", + "expected_output": "999999", + "explanation": "Winston called the func with all possible values of [l,r] and he always got 1000000, thus the min difference is 999999." + }, + { + "example_num": 3, + "expected_input": "arr = [1,2,4,8,16], target = 0", + "expected_output": "0", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720de6", + "questionid": 795, + "title": "Kth Missing Positive Number", + "slug": "kth-missing-positive-number", + "description": "Given an array arr of positive integers sorted in a strictly increasing order, and an integer k. Find the kth positive integer that is missing from this array. ", + "category": [ + "Array", + "Binary Search" + ], + "complexity": "Easy", + "successrate": 55.5, + "totalsubmissions": 284961, + "totalaccepted": 158113, + "likes": 2359, + "dislikes": 172, + "hints": "Keep track of how many positive numbers are missing as you scan the array.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "arr = [2,3,4,7,11], k = 5", + "expected_output": "9\nExplanation: The missing positive integers are [1,5,6,8,9,10,12,13,...]. The 5th missing positive integer is 9.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "arr = [1,2,3,4], k = 2", + "expected_output": "6\nExplanation: The missing positive integers are [5,6,7,...]. The 2nd missing positive integer is 6.", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720df1", + "questionid": 806, + "title": "Minimum Operations to Make Array Equal", + "slug": "minimum-operations-to-make-array-equal", + "description": "You have an array arr of length n where arr[i] = (2 * i) + 1 for all valid values of i (i.e., 0 <= i < n). In one operation, you can select two indices x and y where 0 <= x, y < n and subtract 1 from arr[x] and add 1 to arr[y] (i.e., perform arr[x] -=1 and arr[y] += 1). The goal is to make all the elements of the array equal. It is guaranteed that all the elements of the array can be made equal using some operations. Given an integer n, the length of the array, return the minimum number of operations needed to make all the elements of arr equal. ", + "category": [ + "Math" + ], + "complexity": "Medium", + "successrate": 80.8, + "totalsubmissions": 80139, + "totalaccepted": 64778, + "likes": 785, + "dislikes": 135, + "hints": "Build the array arr using the given formula, define target = sum(arr) / n What is the number of operations needed to convert arr so that all elements equal target ?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 3", + "expected_output": "2", + "explanation": "arr = [1, 3, 5]\nFirst operation choose x = 2 and y = 0, this leads arr to be [2, 3, 4]\nIn the second operation choose x = 2 and y = 0 again, thus arr = [3, 3, 3]." + }, + { + "example_num": 2, + "expected_input": "n = 6", + "expected_output": "9", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720df2", + "questionid": 807, + "title": "Magnetic Force Between Two Balls", + "slug": "magnetic-force-between-two-balls", + "description": "In the universe Earth C-137, Rick discovered a special form of magnetic force between two balls if they are put in his new invented basket. Rick has n empty baskets, the ith basket is at position[i], Morty has m balls and needs to distribute the balls into the baskets such that the minimum magnetic force between any two balls is maximum. Rick stated that magnetic force between two different balls at positions x and y is |x - y|. Given the integer array position and the integer m. Return the required force. ", + "category": [ + "Array", + "Binary Search", + "Sorting" + ], + "complexity": "Medium", + "successrate": 54.5, + "totalsubmissions": 47462, + "totalaccepted": 25844, + "likes": 1106, + "dislikes": 78, + "hints": "If you can place balls such that the answer is x then you can do it for y where y < x. Similarly if you cannot place balls such that the answer is x then you can do it for y where y > x. Binary search on the answer and greedily see if it is possible.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "position = [1,2,3,4,7], m = 3", + "expected_output": "3", + "explanation": "Distributing the 3 balls into baskets 1, 4 and 7 will make the magnetic force between ball pairs [3, 3, 6]. The minimum magnetic force is 3. We cannot achieve a larger minimum magnetic force than 3." + }, + { + "example_num": 2, + "expected_input": "position = [5,4,3,2,1,1000000000], m = 2", + "expected_output": "999999999", + "explanation": "We can use baskets 1 and 1000000000." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720df5", + "questionid": 810, + "title": "Shortest Subarray to be Removed to Make Array Sorted", + "slug": "shortest-subarray-to-be-removed-to-make-array-sorted", + "description": "Given an integer array arr, remove a subarray (can be empty) from arr such that the remaining elements in arr are non-decreasing. Return the length of the shortest subarray to remove. A subarray is a contiguous subsequence of the array. ", + "category": [ + "Array", + "Two Pointers", + "Binary Search", + "Stack", + "Monotonic Stack" + ], + "complexity": "Medium", + "successrate": 35.3, + "totalsubmissions": 50421, + "totalaccepted": 17815, + "likes": 959, + "dislikes": 29, + "hints": "The key is to find the longest non-decreasing subarray starting with the first element or ending with the last element, respectively. After removing some subarray, the result is the concatenation of a sorted prefix and a sorted suffix, where the last element of the prefix is smaller than the first element of the suffix.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "arr = [1,2,3,10,4,2,3,5]", + "expected_output": "3", + "explanation": "The shortest subarray we can remove is [10,4,2] of length 3. The remaining elements after that will be [1,2,3,3,5] which are sorted.\nAnother correct solution is to remove the subarray [3,10,4]." + }, + { + "example_num": 2, + "expected_input": "arr = [5,4,3,2,1]", + "expected_output": "4", + "explanation": "Since the array is strictly decreasing, we can only keep a single element. Therefore we need to remove a subarray of length 4, either [5,4,3,2] or [4,3,2,1]." + }, + { + "example_num": 3, + "expected_input": "arr = [1,2,3]", + "expected_output": "0", + "explanation": "The array is already non-decreasing. We do not need to remove any elements." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720df6", + "questionid": 811, + "title": "Count All Possible Routes", + "slug": "count-all-possible-routes", + "description": "You are given an array of distinct positive integers locations where locations[i] represents the position of city i. You are also given integers start, finish and fuel representing the starting city, ending city, and the initial amount of fuel you have, respectively. At each step, if you are at city i, you can pick any city j such that j != i and 0 <= j < locations.length and move to city j. Moving from city i to city j reduces the amount of fuel you have by |locations[i] - locations[j]|. Please notice that |x| denotes the absolute value of x. Notice that fuel cannot become negative at any point in time, and that you are allowed to visit any city more than once (including start and finish). Return the count of all possible routes from start to finish. Since the answer may be too large, return it modulo 109 + 7. ", + "category": [ + "Array", + "Dynamic Programming", + "Memoization" + ], + "complexity": "Hard", + "successrate": 57.6, + "totalsubmissions": 16965, + "totalaccepted": 9767, + "likes": 351, + "dislikes": 18, + "hints": "Use dynamic programming to solve this problem with each state defined by the city index and fuel left. Since the array contains distinct integers fuel will always be spent in each move and so there can be no cycles.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "locations = [2,3,6,8,4], start = 1, finish = 3, fuel = 5", + "expected_output": "4", + "explanation": "The following are all possible routes, each uses 5 units of fuel:\n1 -> 3\n1 -> 2 -> 3\n1 -> 4 -> 3\n1 -> 4 -> 2 -> 3" + }, + { + "example_num": 2, + "expected_input": "locations = [4,3,1], start = 1, finish = 0, fuel = 6", + "expected_output": "5", + "explanation": "The following are all possible routes:\n1 -> 0, used fuel = 1\n1 -> 2 -> 0, used fuel = 5\n1 -> 2 -> 1 -> 0, used fuel = 5\n1 -> 0 -> 1 -> 0, used fuel = 3\n1 -> 0 -> 1 -> 0 -> 1 -> 0, used fuel = 5" + }, + { + "example_num": 3, + "expected_input": "locations = [5,2,1], start = 0, finish = 2, fuel = 3", + "expected_output": "0", + "explanation": "It is impossible to get from 0 to 2 using only 3 units of fuel since the shortest route needs 4 units of fuel." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720df7", + "questionid": 812, + "title": "Most Visited Sector in a Circular Track", + "slug": "most-visited-sector-in-a-circular-track", + "description": "Given an integer n and an integer array rounds. We have a circular track which consists of n sectors labeled from 1 to n. A marathon will be held on this track, the marathon consists of m rounds. The ith round starts at sector rounds[i - 1] and ends at sector rounds[i]. For example, round 1 starts at sector rounds[0] and ends at sector rounds[1] Return an array of the most visited sectors sorted in ascending order. Notice that you circulate the track in ascending order of sector numbers in the counter-clockwise direction (See the first example). ", + "category": [ + "Array", + "Simulation" + ], + "complexity": "Easy", + "successrate": 58.1, + "totalsubmissions": 36263, + "totalaccepted": 21075, + "likes": 202, + "dislikes": 427, + "hints": "For each round increment the visits of the sectors visited during the marathon with 1. Determine the max number of visits, and return any sector visited the max number of visits.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 4, rounds = [1,3,1,2]", + "expected_output": "[1,2]", + "explanation": "The marathon starts at sector 1. The order of the visited sectors is as follows:\n1 --> 2 --> 3 (end of round 1) --> 4 --> 1 (end of round 2) --> 2 (end of round 3 and the marathon)\nWe can see that both sectors 1 and 2 are visited twice and they are the most visited sectors. Sectors 3 and 4 are visited only once." + }, + { + "example_num": 2, + "expected_input": "n = 2, rounds = [2,1,2,1,2,1,2,1,2]", + "expected_output": "[2]", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "n = 7, rounds = [1,3,5,7]", + "expected_output": "[1,2,3,4,5,6,7]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720dfc", + "questionid": 817, + "title": "Minimum Number of Days to Disconnect Island", + "slug": "minimum-number-of-days-to-disconnect-island", + "description": "You are given an m x n binary grid grid where 1 represents land and 0 represents water. An island is a maximal 4-directionally (horizontal or vertical) connected group of 1's. The grid is said to be connected if we have exactly one island, otherwise is said disconnected. In one day, we are allowed to change any single land cell (1) into a water cell (0). Return the minimum number of days to disconnect the grid. ", + "category": [ + "Array", + "Depth-First Search", + "Breadth-First Search", + "Matrix", + "Strongly Connected Component" + ], + "complexity": "Hard", + "successrate": 48.6, + "totalsubmissions": 16911, + "totalaccepted": 8223, + "likes": 377, + "dislikes": 121, + "hints": "Return 0 if the grid is already disconnected. Return 1 if changing a single land to water disconnect the island. Otherwise return 2. We can disconnect the grid within at most 2 days.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "grid = [[0,1,1,0],[0,1,1,0],[0,0,0,0]]", + "expected_output": "2", + "explanation": "We need at least 2 days to get a disconnected grid.\nChange land grid[1][1] and grid[0][2] to water and get 2 disconnected island." + }, + { + "example_num": 2, + "expected_input": "grid = [[1,1]]", + "expected_output": "2", + "explanation": "Grid of full water is also disconnected ([[1,1]] -> [[0,0]]), 0 islands." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e03", + "questionid": 824, + "title": "Special Positions in a Binary Matrix", + "slug": "special-positions-in-a-binary-matrix", + "description": "Given an m x n binary matrix mat, return the number of special positions in mat. A position (i, j) is called special if mat[i][j] == 1 and all other elements in row i and column j are 0 (rows and columns are 0-indexed). ", + "category": [ + "Array", + "Matrix" + ], + "complexity": "Easy", + "successrate": 65, + "totalsubmissions": 47176, + "totalaccepted": 30652, + "likes": 424, + "dislikes": 18, + "hints": "Keep track of 1s in each row and in each column. Then while iterating over matrix, if the current position is 1 and current row as well as current column contains exactly one occurrence of 1.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "mat = [[1,0,0],[0,0,1],[1,0,0]]", + "expected_output": "1", + "explanation": "(1, 2) is a special position because mat[1][2] == 1 and all other elements in row 1 and column 2 are 0." + }, + { + "example_num": 2, + "expected_input": "mat = [[1,0,0],[0,1,0],[0,0,1]]", + "expected_output": "3", + "explanation": "(0, 0), (1, 1) and (2, 2) are special positions." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e06", + "questionid": 827, + "title": "Split a String Into the Max Number of Unique Substrings", + "slug": "split-a-string-into-the-max-number-of-unique-substrings", + "description": "Given a string s, return the maximum number of unique substrings that the given string can be split into. You can split string s into any list of non-empty substrings, where the concatenation of the substrings forms the original string. However, you must split the substrings such that all of them are unique. A substring is a contiguous sequence of characters within a string. ", + "category": [ + "Hash Table", + "String", + "Backtracking" + ], + "complexity": "Medium", + "successrate": 54.2, + "totalsubmissions": 37163, + "totalaccepted": 20134, + "likes": 545, + "dislikes": 24, + "hints": "Use a set to keep track of which substrings have been used already Try each possible substring at every position and backtrack if a complete split is not possible", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "ababccc"", + "expected_output": "5\nExplanation: One way to split maximally is ['a', 'b', 'ab', 'c', 'cc']. Splitting like ['a', 'b', 'a', 'b', 'c', 'cc'] is not valid as you have 'a' and 'b' multiple times.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "s = "aba"", + "expected_output": "2\nExplanation: One way to split maximally is ['a', 'ba'].", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "s = "aa"", + "expected_output": "1\nExplanation: It is impossible to split the string any further.", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e0b", + "questionid": 832, + "title": "Number of Sets of K Non-Overlapping Line Segments", + "slug": "number-of-sets-of-k-non-overlapping-line-segments", + "description": "Given n points on a 1-D plane, where the ith point (from 0 to n-1) is at x = i, find the number of ways we can draw exactly k non-overlapping line segments such that each segment covers two or more points. The endpoints of each segment must have integral coordinates. The k line segments do not have to cover all n points, and they are allowed to share endpoints. Return the number of ways we can draw k non-overlapping line segments. Since this number can be huge, return it modulo 109 + 7. ", + "category": [ + "Math", + "Dynamic Programming" + ], + "complexity": "Medium", + "successrate": 42.4, + "totalsubmissions": 15711, + "totalaccepted": 6668, + "likes": 317, + "dislikes": 35, + "hints": "Try to use dynamic programming where the current index and remaining number of line segments to form can describe any intermediate state. To make the computation of each state in constant time, we could add another flag to the state that indicates whether or not we are in the middle of placing a line (placed start point but no endpoint).", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 4, k = 2", + "expected_output": "5", + "explanation": "The two line segments are shown in red and blue.\nThe image above shows the 5 different ways {(0,2),(2,3)}, {(0,1),(1,3)}, {(0,1),(2,3)}, {(1,2),(2,3)}, {(0,1),(1,2)}." + }, + { + "example_num": 2, + "expected_input": "n = 3, k = 1", + "expected_output": "3", + "explanation": "The 3 ways are {(0,1)}, {(0,2)}, {(1,2)}." + }, + { + "example_num": 3, + "expected_input": "n = 30, k = 7", + "expected_output": "796297179", + "explanation": "The total number of possible ways to draw 7 line segments is 3796297200. Taking this number modulo 109 + 7 gives us 796297179." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720dce", + "questionid": 771, + "title": "XOR Operation in an Array", + "slug": "xor-operation-in-an-array", + "description": "You are given an integer n and an integer start. Define an array nums where nums[i] = start + 2 * i (0-indexed) and n == nums.length. Return the bitwise XOR of all elements of nums. ", + "category": [ + "Math", + "Bit Manipulation" + ], + "complexity": "Easy", + "successrate": 84.2, + "totalsubmissions": 141261, + "totalaccepted": 118966, + "likes": 796, + "dislikes": 281, + "hints": "Simulate the process, create an array nums and return the Bitwise XOR of all elements of it.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 5, start = 0", + "expected_output": "8", + "explanation": "Array nums is equal to [0, 2, 4, 6, 8] where (0 ^ 2 ^ 4 ^ 6 ^ 8) = 8.\nWhere "^" corresponds to bitwise XOR operator." + }, + { + "example_num": 2, + "expected_input": "n = 4, start = 3", + "expected_output": "8", + "explanation": "Array nums is equal to [3, 5, 7, 9] where (3 ^ 5 ^ 7 ^ 9) = 8." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720dcf", + "questionid": 772, + "title": "Making File Names Unique", + "slug": "making-file-names-unique", + "description": "Given an array of strings names of size n. You will create n folders in your file system such that, at the ith minute, you will create a folder with the name names[i]. Since two files cannot have the same name, if you enter a folder name that was previously used, the system will have a suffix addition to its name in the form of (k), where, k is the smallest positive integer such that the obtained name remains unique. Return an array of strings of length n where ans[i] is the actual name the system will assign to the ith folder when you create it. ", + "category": [ + "Array", + "Hash Table", + "String" + ], + "complexity": "Medium", + "successrate": 34.8, + "totalsubmissions": 65871, + "totalaccepted": 22938, + "likes": 321, + "dislikes": 507, + "hints": "Keep a map of each name and the smallest valid integer that can be appended as a suffix to it. If the name is not present in the map, you can use it without adding any suffixes. If the name is present in the map, append the smallest proper suffix, and add the new name to the map.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "names = ["pes","fifa","gta","pes(2019)"]", + "expected_output": "["pes","fifa","gta","pes(2019)"]", + "explanation": "Let's see how the file system creates folder names:\n"pes" --> not assigned before, remains "pes"\n"fifa" --> not assigned before, remains "fifa"\n"gta" --> not assigned before, remains "gta"\n"pes(2019)" --> not assigned before, remains "pes(2019)"" + }, + { + "example_num": 2, + "expected_input": "names = ["gta","gta(1)","gta","avalon"]", + "expected_output": "["gta","gta(1)","gta(2)","avalon"]", + "explanation": "Let's see how the file system creates folder names:\n"gta" --> not assigned before, remains "gta"\n"gta(1)" --> not assigned before, remains "gta(1)"\n"gta" --> the name is reserved, system adds (k), since "gta(1)" is also reserved, systems put k = 2. it becomes "gta(2)"\n"avalon" --> not assigned before, remains "avalon"" + }, + { + "example_num": 3, + "expected_input": "names = ["onepiece","onepiece(1)","onepiece(2)","onepiece(3)","onepiece"]", + "expected_output": "["onepiece","onepiece(1)","onepiece(2)","onepiece(3)","onepiece(4)"]", + "explanation": "When the last folder is created, the smallest positive valid k is 4, and it becomes "onepiece(4)"." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720dd2", + "questionid": 775, + "title": "Minimum Difference Between Largest and Smallest Value in Three Moves", + "slug": "minimum-difference-between-largest-and-smallest-value-in-three-moves", + "description": "You are given an integer array nums. In one move, you can choose one element of nums and change it by any value. Return the minimum difference between the largest and smallest value of nums after performing at most three moves. ", + "category": [ + "Array", + "Greedy", + "Sorting" + ], + "complexity": "Medium", + "successrate": 55.5, + "totalsubmissions": 109003, + "totalaccepted": 60540, + "likes": 1058, + "dislikes": 147, + "hints": "The minimum difference possible is is obtained by removing 3 elements between the 3 smallest and 3 largest values in the array.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [5,3,2,4]", + "expected_output": "0", + "explanation": "We can make at most 3 moves.\nIn the first move, change 2 to 3. nums becomes [5,3,3,4].\nIn the second move, change 4 to 3. nums becomes [5,3,3,3].\nIn the third move, change 5 to 3. nums becomes [3,3,3,3].\nAfter performing 3 moves, the difference between the minimum and maximum is 3 - 3 = 0." + }, + { + "example_num": 2, + "expected_input": "nums = [1,5,0,10,14]", + "expected_output": "1", + "explanation": "We can make at most 3 moves.\nIn the first move, change 5 to 0. nums becomes [1,0,0,10,14].\nIn the second move, change 10 to 0. nums becomes [1,0,0,0,14].\nIn the third move, change 14 to 1. nums becomes [1,0,0,0,1].\nAfter performing 3 moves, the difference between the minimum and maximum is 1 - 0 = 1.\nIt can be shown that there is no way to make the difference 0 in 3 moves." + }, + { + "example_num": 3, + "expected_input": "nums = [3,100,20]", + "expected_output": "0", + "explanation": "We can make at most 3 moves.\nIn the first move, change 100 to 7. nums becomes [3,7,20].\nIn the second move, change 20 to 7. nums becomes [3,7,7].\nIn the third move, change 3 to 7. nums becomes [7,7,7].\nAfter performing 3 moves, the difference between the minimum and maximum is 7 - 7 = 0." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720dd6", + "questionid": 779, + "title": "Number of Subsequences That Satisfy the Given Sum Condition", + "slug": "number-of-subsequences-that-satisfy-the-given-sum-condition", + "description": "You are given an array of integers nums and an integer target. Return the number of non-empty subsequences of nums such that the sum of the minimum and maximum element on it is less or equal to target. Since the answer may be too large, return it modulo 109 + 7. ", + "category": [ + "Array", + "Two Pointers", + "Binary Search", + "Sorting" + ], + "complexity": "Medium", + "successrate": 39.1, + "totalsubmissions": 71143, + "totalaccepted": 27790, + "likes": 1105, + "dislikes": 104, + "hints": "Sort the array nums. Use two pointers approach: Given an index i (choose it as the minimum in a subsequence) find the maximum j where j ‰¥ i and nums[i] +nums[j] ‰¤ target. Count the number of subsequences.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [3,5,6,7], target = 9", + "expected_output": "4", + "explanation": "There are 4 subsequences that satisfy the condition.\n[3] -> Min value + max value <= target (3 + 3 <= 9)\n[3,5] -> (3 + 5 <= 9)\n[3,5,6] -> (3 + 6 <= 9)\n[3,6] -> (3 + 6 <= 9)" + }, + { + "example_num": 2, + "expected_input": "nums = [3,3,6,8], target = 10", + "expected_output": "6", + "explanation": "There are 6 subsequences that satisfy the condition. (nums can have repeated numbers).\n[3] , [3] , [3,3], [3,6] , [3,6] , [3,3,6]" + }, + { + "example_num": 3, + "expected_input": "nums = [2,3,3,4,6,7], target = 12", + "expected_output": "61", + "explanation": "There are 63 non-empty subsequences, two of them do not satisfy the condition ([6,7], [7]).\nNumber of valid subsequences (63 - 2 = 61)." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720dd8", + "questionid": 781, + "title": "Can Make Arithmetic Progression From Sequence", + "slug": "can-make-arithmetic-progression-from-sequence", + "description": "A sequence of numbers is called an arithmetic progression if the difference between any two consecutive elements is the same. Given an array of numbers arr, return true if the array can be rearranged to form an arithmetic progression. Otherwise, return false. ", + "category": [ + "Array", + "Sorting" + ], + "complexity": "Easy", + "successrate": 69.8, + "totalsubmissions": 111412, + "totalaccepted": 77739, + "likes": 650, + "dislikes": 44, + "hints": "Consider that any valid arithmetic progression will be in sorted order. Sort the array, then check if the differences of all consecutive elements are equal.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "arr = [3,5,1]", + "expected_output": "true\nExplanation: We can reorder the elements as [1,3,5] or [5,3,1] with differences 2 and -2 respectively, between each consecutive elements.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "arr = [1,2,4]", + "expected_output": "false\nExplanation: There is no way to reorder the elements to obtain an arithmetic progression.", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720ddb", + "questionid": 784, + "title": "Minimum Possible Integer After at Most K Adjacent Swaps On Digits", + "slug": "minimum-possible-integer-after-at-most-k-adjacent-swaps-on-digits", + "description": "You are given a string num representing the digits of a very large integer and an integer k. You are allowed to swap any two adjacent digits of the integer at most k times. Return the minimum integer you can obtain also as a string. ", + "category": [ + "String", + "Greedy", + "Binary Indexed Tree", + "Segment Tree" + ], + "complexity": "Hard", + "successrate": 37.7, + "totalsubmissions": 19494, + "totalaccepted": 7347, + "likes": 310, + "dislikes": 20, + "hints": "We want to make the smaller digits the most significant digits in the number. For each index i, check the smallest digit in a window of size k and append it to the answer. Update the indices of all digits in this range accordingly.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "num = "4321", k = 4", + "expected_output": ""1342"", + "explanation": "The steps to obtain the minimum integer from 4321 with 4 adjacent swaps are shown." + }, + { + "example_num": 2, + "expected_input": "num = "100", k = 1", + "expected_output": ""010"", + "explanation": "It's ok for the output to have leading zeros, but the input is guaranteed not to have any leading zeros." + }, + { + "example_num": 3, + "expected_input": "num = "36789", k = 1000", + "expected_output": ""36789"", + "explanation": "We can keep the number without any swaps." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720ddd", + "questionid": 786, + "title": "Number of Sub-arrays With Odd Sum", + "slug": "number-of-sub-arrays-with-odd-sum", + "description": "Given an array of integers arr, return the number of subarrays with an odd sum. Since the answer can be very large, return it modulo 109 + 7. ", + "category": [ + "Array", + "Math", + "Dynamic Programming", + "Prefix Sum" + ], + "complexity": "Medium", + "successrate": 43.5, + "totalsubmissions": 52460, + "totalaccepted": 22824, + "likes": 754, + "dislikes": 31, + "hints": "Can we use the accumulative sum to keep track of all the odd-sum sub-arrays ? if the current accu sum is odd, we care only about previous even accu sums and vice versa.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "arr = [1,3,5]", + "expected_output": "4", + "explanation": "All subarrays are [[1],[1,3],[1,3,5],[3],[3,5],[5]]\nAll sub-arrays sum are [1,4,9,3,8,5].\nOdd sums are [1,9,3,5] so the answer is 4." + }, + { + "example_num": 2, + "expected_input": "arr = [2,4,6]", + "expected_output": "0", + "explanation": "All subarrays are [[2],[2,4],[2,4,6],[4],[4,6],[6]]\nAll sub-arrays sum are [2,6,12,4,10,6].\nAll sub-arrays have even sum and the answer is 0." + }, + { + "example_num": 3, + "expected_input": "arr = [1,2,3,4,5,6,7]", + "expected_output": "16", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720dec", + "questionid": 801, + "title": "Minimum Swaps to Arrange a Binary Grid", + "slug": "minimum-swaps-to-arrange-a-binary-grid", + "description": "Given an n x n binary grid, in one step you can choose two adjacent rows of the grid and swap them. A grid is said to be valid if all the cells above the main diagonal are zeros. Return the minimum number of steps needed to make the grid valid, or -1 if the grid cannot be valid. The main diagonal of a grid is the diagonal that starts at cell (1, 1) and ends at cell (n, n). ", + "category": [ + "Array", + "Greedy", + "Matrix" + ], + "complexity": "Medium", + "successrate": 45.8, + "totalsubmissions": 24453, + "totalaccepted": 11191, + "likes": 421, + "dislikes": 59, + "hints": "For each row of the grid calculate the most right 1 in the grid in the array maxRight. To check if there exist answer, sort maxRight and check if maxRight[i] ‰¤ i for all possible i's. If there exist an answer, simulate the swaps.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "grid = [[0,0,1],[1,1,0],[1,0,0]]", + "expected_output": "3", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "grid = [[0,1,1,0],[0,1,1,0],[0,1,1,0],[0,1,1,0]]", + "expected_output": "-1", + "explanation": "All rows are similar, swaps have no effect on the grid." + }, + { + "example_num": 3, + "expected_input": "grid = [[1,0,0],[1,1,0],[1,1,1]]", + "expected_output": "0", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720def", + "questionid": 804, + "title": "Detect Cycles in 2D Grid", + "slug": "detect-cycles-in-2d-grid", + "description": "Given a 2D array of characters grid of size m x n, you need to find if there exists any cycle consisting of the same value in grid. A cycle is a path of length 4 or more in the grid that starts and ends at the same cell. From a given cell, you can move to one of the cells adjacent to it - in one of the four directions (up, down, left, or right), if it has the same value of the current cell. Also, you cannot move to the cell that you visited in your last move. For example, the cycle (1, 1) -> (1, 2) -> (1, 1) is invalid because from (1, 2) we visited (1, 1) which was the last visited cell. Return true if any cycle of the same value exists in grid, otherwise, return false. ", + "category": [ + "Array", + "Depth-First Search", + "Breadth-First Search", + "Union Find", + "Matrix" + ], + "complexity": "Medium", + "successrate": 47.9, + "totalsubmissions": 48472, + "totalaccepted": 23236, + "likes": 609, + "dislikes": 21, + "hints": "Keep track of the parent (previous position) to avoid considering an invalid path. Use DFS or BFS and keep track of visited cells to see if there is a cycle.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "grid = [["a","a","a","a"],["a","b","b","a"],["a","b","b","a"],["a","a","a","a"]]", + "expected_output": "true\nExplanation: There are two valid cycles shown in different colors in the image below:\n\"\"", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "grid = [["c","c","c","a"],["c","d","c","c"],["c","c","e","c"],["f","c","c","c"]]", + "expected_output": "true\nExplanation: There is only one valid cycle highlighted in the image below:\n\"\"", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "grid = [["a","b","b"],["b","z","b"],["b","b","a"]]", + "expected_output": "false", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720df0", + "questionid": 805, + "title": "Find Longest Awesome Substring", + "slug": "find-longest-awesome-substring", + "description": "You are given a string s. An awesome substring is a non-empty substring of s such that we can make any number of swaps in order to make it a palindrome. Return the length of the maximum length awesome substring of s. ", + "category": [ + "Hash Table", + "String", + "Bit Manipulation" + ], + "complexity": "Hard", + "successrate": 40.7, + "totalsubmissions": 21634, + "totalaccepted": 8796, + "likes": 508, + "dislikes": 11, + "hints": "Given the character counts, under what conditions can a palindrome be formed ? From left to right, use bitwise xor-operation to compute for any prefix the number of times modulo 2 of each digit. (mask ^= (1<<(s[i]-'0')). Expected complexity is O(n*A) where A is the alphabet (10).", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "3242415"", + "expected_output": "5", + "explanation": ""24241" is the longest awesome substring, we can form the palindrome "24142" with some swaps." + }, + { + "example_num": 2, + "expected_input": "s = "12345678"", + "expected_output": "1", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "s = "213123"", + "expected_output": "6", + "explanation": ""213123" is the longest awesome substring, we can form the palindrome "231132" with some swaps." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720df4", + "questionid": 809, + "title": "Number of Ways to Split a String", + "slug": "number-of-ways-to-split-a-string", + "description": "Given a binary string s, you can split s into 3 non-empty strings s1, s2, and s3 where s1 + s2 + s3 = s. Return the number of ways s can be split such that the number of ones is the same in s1, s2, and s3. Since the answer may be too large, return it modulo 109 + 7. ", + "category": [ + "Math", + "String" + ], + "complexity": "Medium", + "successrate": 32, + "totalsubmissions": 59777, + "totalaccepted": 19152, + "likes": 445, + "dislikes": 56, + "hints": "There is no way if the sum (number of '1's) is not divisible by the number of splits. So sum%3 should be 0. Preffix s1 , and suffix s3 should have sum/3 characters '1'. Follow up: Can you generalize the problem with numbers between [-10^9, 10^9] such the sum between subarrays s1, s2, s3 are the same?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "10101"", + "expected_output": "4", + "explanation": "There are four ways to split s in 3 parts where each part contain the same number of letters '1'.\n"1|010|1"\n"1|01|01"\n"10|10|1"\n"10|1|01"" + }, + { + "example_num": 2, + "expected_input": "s = "1001"", + "expected_output": "0", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "s = "0000"", + "expected_output": "3", + "explanation": "There are three ways to split s in 3 parts.\n"0|0|00"\n"0|00|0"\n"00|0|0"" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720df8", + "questionid": 813, + "title": "Find Latest Group of Size M", + "slug": "find-latest-group-of-size-m", + "description": "Given an array arr that represents a permutation of numbers from 1 to n. You have a binary string of size n that initially has all its bits set to zero. At each step i (assuming both the binary string and arr are 1-indexed) from 1 to n, the bit at position arr[i] is set to 1. You are also given an integer m. Find the latest step at which there exists a group of ones of length m. A group of ones is a contiguous substring of 1's such that it cannot be extended in either direction. Return the latest step at which there exists a group of ones of length exactly m. If no such group exists, return -1. ", + "category": [ + "Array", + "Binary Search", + "Simulation" + ], + "complexity": "Medium", + "successrate": 40.7, + "totalsubmissions": 30264, + "totalaccepted": 12307, + "likes": 443, + "dislikes": 93, + "hints": "Since the problem asks for the latest step, can you start the searching from the end of arr? Use a map to store the current €œ1€ groups. At each step (going backwards) you need to split one group and update the map.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "arr = [3,5,1,2,4], m = 1", + "expected_output": "4", + "explanation": "Step 1: "00100", groups: ["1"]\nStep 2: "00101", groups: ["1", "1"]\nStep 3: "10101", groups: ["1", "1", "1"]\nStep 4: "11101", groups: ["111", "1"]\nStep 5: "11111", groups: ["11111"]\nThe latest step at which there exists a group of size 1 is step 4." + }, + { + "example_num": 2, + "expected_input": "arr = [3,1,5,4,2], m = 2", + "expected_output": "-1", + "explanation": "Step 1: "00100", groups: ["1"]\nStep 2: "10100", groups: ["1", "1"]\nStep 3: "10101", groups: ["1", "1", "1"]\nStep 4: "10111", groups: ["1", "111"]\nStep 5: "11111", groups: ["11111"]\nNo group of size 2 exists during any step." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720df9", + "questionid": 814, + "title": "Stone Game V", + "slug": "stone-game-v", + "description": "There are several stones arranged in a row, and each stone has an associated value which is an integer given in the array stoneValue. In each round of the game, Alice divides the row into two non-empty rows (i.e. left row and right row), then Bob calculates the value of each row which is the sum of the values of all the stones in this row. Bob throws away the row which has the maximum value, and Alice's score increases by the value of the remaining row. If the value of the two rows are equal, Bob lets Alice decide which row will be thrown away. The next round starts with the remaining row. The game ends when there is only one stone remaining. Alice's is initially zero. Return the maximum score that Alice can obtain. ", + "category": [ + "Array", + "Math", + "Dynamic Programming", + "Game Theory" + ], + "complexity": "Hard", + "successrate": 40.9, + "totalsubmissions": 30952, + "totalaccepted": 12652, + "likes": 355, + "dislikes": 58, + "hints": "We need to try all possible divisions for the current row to get the max score. As calculating all possible divisions will lead us to calculate some sub-problems more than once, we need to think of dynamic programming.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "stoneValue = [6,2,3,4,5,5]", + "expected_output": "18", + "explanation": "In the first round, Alice divides the row to [6,2,3], [4,5,5]. The left row has the value 11 and the right row has value 14. Bob throws away the right row and Alice's score is now 11.\nIn the second round Alice divides the row to [6], [2,3]. This time Bob throws away the left row and Alice's score becomes 16 (11 + 5).\nThe last round Alice has only one choice to divide the row which is [2], [3]. Bob throws away the right row and Alice's score is now 18 (16 + 2). The game ends because only one stone is remaining in the row." + }, + { + "example_num": 2, + "expected_input": "stoneValue = [7,7,7,7,7,7,7]", + "expected_output": "28", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "stoneValue = [4]", + "expected_output": "0", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720dfa", + "questionid": 815, + "title": "Detect Pattern of Length M Repeated K or More Times", + "slug": "detect-pattern-of-length-m-repeated-k-or-more-times", + "description": "Given an array of positive integers arr, find a pattern of length m that is repeated k or more times. A pattern is a subarray (consecutive sub-sequence) that consists of one or more values, repeated multiple times consecutively without overlapping. A pattern is defined by its length and the number of repetitions. Return true if there exists a pattern of length m that is repeated k or more times, otherwise return false. ", + "category": [ + "Array", + "Enumeration" + ], + "complexity": "Easy", + "successrate": 43.5, + "totalsubmissions": 54950, + "totalaccepted": 23898, + "likes": 463, + "dislikes": 83, + "hints": "Use a three-layer loop to check all possible patterns by iterating through all possible starting positions, all indexes less than m, and if the character at the index is repeated k times.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "arr = [1,2,4,4,4,4], m = 1, k = 3", + "expected_output": "true\nExplanation: The pattern (4) of length 1 is repeated 4 consecutive times. Notice that pattern can be repeated k or more times but not less.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "arr = [1,2,1,2,1,1,1,3], m = 2, k = 2", + "expected_output": "true\nExplanation: The pattern (1,2) of length 2 is repeated 2 consecutive times. Another valid pattern (2,1) is also repeated 2 times.", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "arr = [1,2,1,2,1,3], m = 2, k = 3", + "expected_output": "false\nExplanation: The pattern (1,2) is of length 2 but is repeated only 2 times. There is no pattern of length 2 that is repeated 3 or more times.", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e01", + "questionid": 822, + "title": "Replace All ?'s to Avoid Consecutive Repeating Characters", + "slug": "replace-all-s-to-avoid-consecutive-repeating-characters", + "description": "Given a string s containing only lowercase English letters and the '?' character, convert all the '?' characters into lowercase letters such that the final string does not contain any consecutive repeating characters. You cannot modify the non '?' characters. It is guaranteed that there are no consecutive repeating characters in the given string except for '?'. Return the final string after all the conversions (possibly zero) have been made. If there is more than one solution, return any of them. It can be shown that an answer is always possible with the given constraints. ", + "category": [ + "String" + ], + "complexity": "Easy", + "successrate": 49.8, + "totalsubmissions": 87583, + "totalaccepted": 43623, + "likes": 379, + "dislikes": 144, + "hints": "Processing string from left to right, whenever you get a €˜?€™, check left character and right character, and select a character not equal to either of them Do take care to compare with replaced occurrence of €˜?€™ when checking the left character.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "?zs"", + "expected_output": ""azs"", + "explanation": "There are 25 solutions for this problem. From "azs" to "yzs", all are valid. Only "z" is an invalid modification as the string will consist of consecutive repeating characters in "zzs"." + }, + { + "example_num": 2, + "expected_input": "s = "ubv?w"", + "expected_output": ""ubvaw"", + "explanation": "There are 24 solutions for this problem. Only "v" and "w" are invalid modifications as the strings will consist of consecutive repeating characters in "ubvvw" and "ubvww"." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e02", + "questionid": 823, + "title": "Minimum Time to Make Rope Colorful", + "slug": "minimum-time-to-make-rope-colorful", + "description": "Alice has n balloons arranged on a rope. You are given a 0-indexed string colors where colors[i] is the color of the ith balloon. Alice wants the rope to be colorful. She does not want two consecutive balloons to be of the same color, so she asks Bob for help. Bob can remove some balloons from the rope to make it colorful. You are given a 0-indexed integer array neededTime where neededTime[i] is the time (in seconds) that Bob needs to remove the ith balloon from the rope. Return the minimum time Bob needs to make the rope colorful. ", + "category": [ + "Array", + "String", + "Dynamic Programming", + "Greedy" + ], + "complexity": "Medium", + "successrate": 61.2, + "totalsubmissions": 98424, + "totalaccepted": 60218, + "likes": 971, + "dislikes": 40, + "hints": "Maintain the running sum and max value for repeated letters.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "colors = "abaac", neededTime = [1,2,3,4,5]", + "expected_output": "3", + "explanation": "In the above image, 'a' is blue, 'b' is red, and 'c' is green.\nBob can remove the blue balloon at index 2. This takes 3 seconds.\nThere are no longer two consecutive balloons of the same color. Total time = 3." + }, + { + "example_num": 2, + "expected_input": "colors = "abc", neededTime = [1,2,3]", + "expected_output": "0", + "explanation": "The rope is already colorful. Bob does not need to remove any balloons from the rope." + }, + { + "example_num": 3, + "expected_input": "colors = "aabaa", neededTime = [1,2,3,4,1]", + "expected_output": "2", + "explanation": "Bob will remove the balloons at indices 0 and 4. Each balloons takes 1 second to remove.\nThere are no longer two consecutive balloons of the same color. Total time = 1 + 1 = 2." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e05", + "questionid": 826, + "title": "Rearrange Spaces Between Words", + "slug": "rearrange-spaces-between-words", + "description": "You are given a string text of words that are placed among some number of spaces. Each word consists of one or more lowercase English letters and are separated by at least one space. It's guaranteed that text contains at least one word. Rearrange the spaces so that there is an equal number of spaces between every pair of adjacent words and that number is maximized. If you cannot redistribute all the spaces equally, place the extra spaces at the end, meaning the returned string should be the same length as text. Return the string after rearranging the spaces. ", + "category": [ + "String" + ], + "complexity": "Easy", + "successrate": 44, + "totalsubmissions": 78867, + "totalaccepted": 34707, + "likes": 258, + "dislikes": 231, + "hints": "Count the total number of spaces and words. Then use the integer division to determine the numbers of spaces to add between each word and at the end.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "text = " this is a sentence "", + "expected_output": ""this is a sentence"", + "explanation": "There are a total of 9 spaces and 4 words. We can evenly divide the 9 spaces between the words: 9 / (4-1) = 3 spaces." + }, + { + "example_num": 2, + "expected_input": "text = " practice makes perfect"", + "expected_output": ""practice makes perfect "", + "explanation": "There are a total of 7 spaces and 3 words. 7 / (3-1) = 3 spaces plus 1 extra space. We place this extra space at the end of the string." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720dcd", + "questionid": 770, + "title": "Minimum Number of Days to Make m Bouquets", + "slug": "minimum-number-of-days-to-make-m-bouquets", + "description": "You are given an integer array bloomDay, an integer m and an integer k. You want to make m bouquets. To make a bouquet, you need to use k adjacent flowers from the garden. The garden consists of n flowers, the ith flower will bloom in the bloomDay[i] and then can be used in exactly one bouquet. Return the minimum number of days you need to wait to be able to make m bouquets from the garden. If it is impossible to make m bouquets return -1. ", + "category": [ + "Array", + "Binary Search" + ], + "complexity": "Medium", + "successrate": 55.5, + "totalsubmissions": 65353, + "totalaccepted": 36272, + "likes": 1568, + "dislikes": 40, + "hints": "If we can make m or more bouquets at day x, then we can still make m or more bouquets at any day y > x. We can check easily if we can make enough bouquets at day x if we can get group adjacent flowers at day x.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "bloomDay = [1,10,3,10,2], m = 3, k = 1", + "expected_output": "3", + "explanation": "Let us see what happened in the first three days. x means flower bloomed and _ means flower did not bloom in the garden.\nWe need 3 bouquets each should contain 1 flower.\nAfter day 1: [x, _, _, _, _] // we can only make one bouquet.\nAfter day 2: [x, _, _, _, x] // we can only make two bouquets.\nAfter day 3: [x, _, x, _, x] // we can make 3 bouquets. The answer is 3." + }, + { + "example_num": 2, + "expected_input": "bloomDay = [1,10,3,10,2], m = 3, k = 2", + "expected_output": "-1", + "explanation": "We need 3 bouquets each has 2 flowers, that means we need 6 flowers. We only have 5 flowers so it is impossible to get the needed bouquets and we return -1." + }, + { + "example_num": 3, + "expected_input": "bloomDay = [7,7,7,7,12,7,7], m = 2, k = 3", + "expected_output": "12", + "explanation": "We need 2 bouquets each should have 3 flowers.\nHere is the garden after the 7 and 12 days:\nAfter day 7: [x, x, x, x, _, x, x]\nWe can make one bouquet of the first three flowers that bloomed. We cannot make another bouquet from the last three flowers that bloomed because they are not adjacent.\nAfter day 12: [x, x, x, x, x, x, x]\nIt is obvious that we can make two bouquets in different ways." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720dd0", + "questionid": 773, + "title": "Find Critical and Pseudo-Critical Edges in Minimum Spanning Tree", + "slug": "find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree", + "description": "Given a weighted undirected connected graph with n vertices numbered from 0 to n - 1, and an array edges where edges[i] = [ai, bi, weighti] represents a bidirectional and weighted edge between nodes ai and bi. A minimum spanning tree (MST) is a subset of the graph's edges that connects all vertices without cycles and with the minimum possible total edge weight. Find all the critical and pseudo-critical edges in the given graph's minimum spanning tree (MST). An MST edge whose deletion from the graph would cause the MST weight to increase is called a critical edge. On the other hand, a pseudo-critical edge is that which can appear in some MSTs but not all. Note that you can return the indices of the edges in any order. ", + "category": [ + "Union Find", + "Graph", + "Sorting", + "Minimum Spanning Tree", + "Strongly Connected Component" + ], + "complexity": "Hard", + "successrate": 52.9, + "totalsubmissions": 14287, + "totalaccepted": 7559, + "likes": 442, + "dislikes": 43, + "hints": "Use the Kruskal algorithm to find the minimum spanning tree by sorting the edges and picking edges from ones with smaller weights. Use a disjoint set to avoid adding redundant edges that result in a cycle. To find if one edge is critical, delete that edge and re-run the MST algorithm and see if the weight of the new MST increases. To find if one edge is non-critical (in any MST), include that edge to the accepted edge list and continue the MST algorithm, then see if the resulting MST has the same weight of the initial MST of the entire graph.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 5, edges = [[0,1,1],[1,2,1],[2,3,2],[0,3,2],[0,4,3],[3,4,3],[1,4,6]]", + "expected_output": "[[0,1],[2,3,4,5]]", + "explanation": "The figure above describes the graph.\nThe following figure shows all the possible MSTs:\n\"\"\nNotice that the two edges 0 and 1 appear in all MSTs, therefore they are critical edges, so we return them in the first list of the output.\nThe edges 2, 3, 4, and 5 are only part of some MSTs, therefore they are considered pseudo-critical edges. We add them to the second list of the output." + }, + { + "example_num": 2, + "expected_input": "n = 4, edges = [[0,1,1],[1,2,1],[2,3,1],[0,3,1]]", + "expected_output": "[[],[0,1,2,3]]", + "explanation": "We can observe that since all 4 edges have equal weight, choosing any 3 edges from the given 4 will yield an MST. Therefore all 4 edges are pseudo-critical." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720dd3", + "questionid": 776, + "title": "Stone Game IV", + "slug": "stone-game-iv", + "description": "Alice and Bob take turns playing a game, with Alice starting first. Initially, there are n stones in a pile. On each player's turn, that player makes a move consisting of removing any non-zero square number of stones in the pile. Also, if a player cannot make a move, he/she loses the game. Given a positive integer n, return true if and only if Alice wins the game otherwise return false, assuming both players play optimally. ", + "category": [ + "Math", + "Dynamic Programming", + "Game Theory" + ], + "complexity": "Hard", + "successrate": 60.8, + "totalsubmissions": 95502, + "totalaccepted": 58083, + "likes": 1247, + "dislikes": 53, + "hints": "Use dynamic programming to keep track of winning and losing states. Given some number of stones, Alice can win if she can force Bob onto a losing state.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 1", + "expected_output": "true\nExplanation: Alice can remove 1 stone winning the game because Bob doesn't have any moves.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "n = 2", + "expected_output": "false\nExplanation: Alice can only remove 1 stone, after that Bob removes the last one winning the game (2 -> 1 -> 0).", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "n = 4", + "expected_output": "true", + "explanation": "n is already a perfect square, Alice can win with one move, removing 4 stones (4 -> 0)." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720dd4", + "questionid": 777, + "title": "Path Crossing", + "slug": "path-crossing", + "description": "Given a string path, where path[i] = 'N', 'S', 'E' or 'W', each representing moving one unit north, south, east, or west, respectively. You start at the origin (0, 0) on a 2D plane and walk on the path specified by path. Return true if the path crosses itself at any point, that is, if at any time you are on a location you have previously visited. Return false otherwise. ", + "category": [ + "Hash Table", + "String" + ], + "complexity": "Easy", + "successrate": 55.7, + "totalsubmissions": 62878, + "totalaccepted": 35053, + "likes": 473, + "dislikes": 8, + "hints": "Simulate the process while keeping track of visited points. Use a set to store previously visited points.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "path = "NES"", + "expected_output": "false", + "explanation": "Notice that the path doesn't cross any point more than once." + }, + { + "example_num": 2, + "expected_input": "path = "NESWW"", + "expected_output": "true", + "explanation": "Notice that the path visits the origin twice." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720dd5", + "questionid": 778, + "title": "Check If Array Pairs Are Divisible by k", + "slug": "check-if-array-pairs-are-divisible-by-k", + "description": "Given an array of integers arr of even length n and an integer k. We want to divide the array into exactly n / 2 pairs such that the sum of each pair is divisible by k. Return true If you can find a way to do that or false otherwise. ", + "category": [ + "Array", + "Hash Table", + "Counting" + ], + "complexity": "Medium", + "successrate": 40.5, + "totalsubmissions": 75098, + "totalaccepted": 30395, + "likes": 933, + "dislikes": 56, + "hints": "Keep an array of the frequencies of ((x % k) + k) % k for each x in arr. for each i in [0, k - 1] we need to check if freq[k] == freq[k - i] Take care of the case when i == k - i and when i == 0", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "arr = [1,2,3,4,5,10,6,7,8,9], k = 5", + "expected_output": "true", + "explanation": "Pairs are (1,9),(2,8),(3,7),(4,6) and (5,10)." + }, + { + "example_num": 2, + "expected_input": "arr = [1,2,3,4,5,6], k = 7", + "expected_output": "true", + "explanation": "Pairs are (1,6),(2,5) and(3,4)." + }, + { + "example_num": 3, + "expected_input": "arr = [1,2,3,4,5,6], k = 10", + "expected_output": "false", + "explanation": "You can try all possible pairs to see that there is no way to divide arr into 3 pairs each with sum divisible by 10." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720ddc", + "questionid": 785, + "title": "Count Odd Numbers in an Interval Range", + "slug": "count-odd-numbers-in-an-interval-range", + "description": "Given two non-negative integers low and high. Return the count of odd numbers between low and high (inclusive). ", + "category": [ + "Math" + ], + "complexity": "Easy", + "successrate": 48.1, + "totalsubmissions": 146529, + "totalaccepted": 70473, + "likes": 616, + "dislikes": 48, + "hints": "If the range (high - low + 1) is even, the number of even and odd numbers in this range will be the same. If the range (high - low + 1) is odd, the solution will depend on the parity of high and low.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "low = 3, high = 7", + "expected_output": "3\r\nExplanation: The odd numbers between 3 and 7 are [3,5,7].", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "low = 8, high = 10", + "expected_output": "1\r\nExplanation: The odd numbers between 8 and 10 are [9].", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720dde", + "questionid": 787, + "title": "Number of Good Ways to Split a String", + "slug": "number-of-good-ways-to-split-a-string", + "description": "You are given a string s. A split is called good if you can split s into two non-empty strings sleft and sright where their concatenation is equal to s (i.e., sleft + sright = s) and the number of distinct letters in sleft and sright is the same. Return the number of good splits you can make in s. ", + "category": [ + "String", + "Dynamic Programming", + "Bit Manipulation" + ], + "complexity": "Medium", + "successrate": 70.2, + "totalsubmissions": 98161, + "totalaccepted": 68912, + "likes": 1315, + "dislikes": 30, + "hints": "Use two HashMap to store the counts of distinct letters in the left and right substring divided by the current index.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "aacaba"", + "expected_output": "2", + "explanation": "There are 5 ways to split "aacaba" and 2 of them are good. \n("a", "acaba") Left string and right string contains 1 and 3 different letters respectively.\n("aa", "caba") Left string and right string contains 1 and 3 different letters respectively.\n("aac", "aba") Left string and right string contains 2 and 2 different letters respectively (good split).\n("aaca", "ba") Left string and right string contains 2 and 2 different letters respectively (good split).\n("aacab", "a") Left string and right string contains 3 and 1 different letters respectively." + }, + { + "example_num": 2, + "expected_input": "s = "abcd"", + "expected_output": "1", + "explanation": "Split the string as follows ("ab", "cd")." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720de1", + "questionid": 790, + "title": "Number of Substrings With Only 1s", + "slug": "number-of-substrings-with-only-1s", + "description": "Given a binary string s, return the number of substrings with all characters 1's. Since the answer may be too large, return it modulo 109 + 7. ", + "category": [ + "Math", + "String" + ], + "complexity": "Medium", + "successrate": 44.2, + "totalsubmissions": 65615, + "totalaccepted": 28986, + "likes": 508, + "dislikes": 22, + "hints": "Count number of 1s in each consecutive-1 group. For a group with n consecutive 1s, the total contribution of it to the final answer is (n + 1) * n // 2.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "0110111"", + "expected_output": "9", + "explanation": "There are 9 substring in total with only 1's characters.\n"1" -> 5 times.\n"11" -> 3 times.\n"111" -> 1 time." + }, + { + "example_num": 2, + "expected_input": "s = "101"", + "expected_output": "2", + "explanation": "Substring "1" is shown 2 times in s." + }, + { + "example_num": 3, + "expected_input": "s = "111111"", + "expected_output": "21", + "explanation": "Each substring contains only 1's characters." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720de2", + "questionid": 791, + "title": "String Compression II", + "slug": "string-compression-ii", + "description": "Run-length encoding is a string compression method that works by replacing consecutive identical characters (repeated 2 or more times) with the concatenation of the character and the number marking the count of the characters (length of the run). For example, to compress the string \"aabccc\" we replace \"aa\" by \"a2\" and replace \"ccc\" by \"c3\". Thus the compressed string becomes \"a2bc3\". Notice that in this problem, we are not adding '1' after single characters. Given a string s and an integer k. You need to delete at most k characters from s such that the run-length encoded version of s has minimum length. Find the minimum length of the run-length encoded version of s after deleting at most k characters. ", + "category": [ + "String", + "Dynamic Programming" + ], + "complexity": "Hard", + "successrate": 38, + "totalsubmissions": 29095, + "totalaccepted": 11048, + "likes": 459, + "dislikes": 48, + "hints": "Use dynamic programming. The state of the DP can be the current index and the remaining characters to delete. Having a prefix sum for each character can help you determine for a certain character c in some specific range, how many characters you need to delete to merge all occurrences of c in that range.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "aaabcccd", k = 2", + "expected_output": "4\nExplanation: Compressing s without deleting anything will give us "a3bc3d" of length 6. Deleting any of the characters 'a' or 'c' would at most decrease the length of the compressed string to 5, for instance delete 2 'a' then we will have s = "abcccd" which compressed is abc3d. Therefore, the optimal way is to delete 'b' and 'd', then the compressed version of s will be "a3c3" of length 4.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "s = "aabbaa", k = 2", + "expected_output": "2\nExplanation: If we delete both 'b' characters, the resulting compressed string would be "a4" of length 2.", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "s = "aaaaaaaaaaa", k = 0", + "expected_output": "3\nExplanation: Since k is zero, we cannot delete anything. The compressed string is "a11" of length 3.", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720de7", + "questionid": 796, + "title": "Maximum Number of Non-Overlapping Subarrays With Sum Equals Target", + "slug": "maximum-number-of-non-overlapping-subarrays-with-sum-equals-target", + "description": "Given an array nums and an integer target, return the maximum number of non-empty non-overlapping subarrays such that the sum of values in each subarray is equal to target. ", + "category": [ + "Array", + "Hash Table", + "Greedy", + "Prefix Sum" + ], + "complexity": "Medium", + "successrate": 46.4, + "totalsubmissions": 41089, + "totalaccepted": 19048, + "likes": 729, + "dislikes": 15, + "hints": "Keep track of prefix sums to quickly look up what subarray that sums \"target\" can be formed at each step of scanning the input array. It can be proved that greedily forming valid subarrays as soon as one is found is optimal.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,1,1,1,1], target = 2", + "expected_output": "2", + "explanation": "There are 2 non-overlapping subarrays [1,1,1,1,1] with sum equals to target(2)." + }, + { + "example_num": 2, + "expected_input": "nums = [-1,3,5,1,4,2,-9], target = 6", + "expected_output": "2", + "explanation": "There are 3 subarrays with sum equal to 6.\n([5,1], [4,2], [3,5,1,4,2,-9]) but only the first 2 are non-overlapping." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720de9", + "questionid": 798, + "title": "Minimum Suffix Flips", + "slug": "minimum-suffix-flips", + "description": "You are given a 0-indexed binary string target of length n. You have another binary string s of length n that is initially set to all zeros. You want to make s equal to target. In one operation, you can pick an index i where 0 <= i < n and flip all bits in the inclusive range [i, n - 1]. Flip means changing '0' to '1' and '1' to '0'. Return the minimum number of operations needed to make s equal to target. ", + "category": [ + "String", + "Greedy" + ], + "complexity": "Medium", + "successrate": 72.4, + "totalsubmissions": 44336, + "totalaccepted": 32118, + "likes": 636, + "dislikes": 32, + "hints": "Consider a strategy where the choice of bulb with number i is increasing. In such a strategy, you no longer need to worry about bulbs that have been set to the left.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "target = "10111"", + "expected_output": "3", + "explanation": "Initially, s = "00000".\nChoose index i = 2: "00000" -> "00111"\nChoose index i = 0: "00111" -> "11000"\nChoose index i = 1: "11000" -> "10111"\nWe need at least 3 flip operations to form target." + }, + { + "example_num": 2, + "expected_input": "target = "101"", + "expected_output": "3", + "explanation": "Initially, s = "000".\nChoose index i = 0: "000" -> "111"\nChoose index i = 1: "111" -> "100"\nChoose index i = 2: "100" -> "101"\nWe need at least 3 flip operations to form target." + }, + { + "example_num": 3, + "expected_input": "target = "00000"", + "expected_output": "0", + "explanation": "We do not need any operations since the initial s already equals target." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720ded", + "questionid": 802, + "title": "Thousand Separator", + "slug": "thousand-separator", + "description": "Given an integer n, add a dot (\".\") as the thousands separator and return it in string format. ", + "category": [ + "String" + ], + "complexity": "Easy", + "successrate": 55.9, + "totalsubmissions": 58728, + "totalaccepted": 32849, + "likes": 328, + "dislikes": 15, + "hints": "Scan from the back of the integer and use dots to connect blocks with length 3 except the last block.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 987", + "expected_output": ""987"", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "n = 1234", + "expected_output": ""1.234"", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720dee", + "questionid": 803, + "title": "Minimum Number of Vertices to Reach All Nodes", + "slug": "minimum-number-of-vertices-to-reach-all-nodes", + "description": "Given a directed acyclic graph, with n vertices numbered from 0 to n-1, and an array edges where edges[i] = [fromi, toi] represents a directed edge from node fromi to node toi. Find the smallest set of vertices from which all nodes in the graph are reachable. It's guaranteed that a unique solution exists. Notice that you can return the vertices in any order. ", + "category": [ + "Graph" + ], + "complexity": "Medium", + "successrate": 78.6, + "totalsubmissions": 72692, + "totalaccepted": 57103, + "likes": 1369, + "dislikes": 60, + "hints": "A node that does not have any incoming edge can only be reached by itself. Any other node with incoming edges can be reached from some other node. We only have to count the number of nodes with zero incoming edges.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 6, edges = [[0,1],[0,2],[2,5],[3,4],[4,2]]", + "expected_output": "[0,3]\nExplanation: It's not possible to reach all the nodes from a single vertex. From 0 we can reach [0,1,2,5]. From 3 we can reach [3,4,2,5]. So we output [0,3].", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "n = 5, edges = [[0,1],[2,1],[3,1],[1,4],[2,4]]", + "expected_output": "[0,2,3]\nExplanation: Notice that vertices 0, 3 and 2 are not reachable from any other node, so we must include them. Also any of these vertices can reach nodes 1 and 4.", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720df3", + "questionid": 808, + "title": "Matrix Diagonal Sum", + "slug": "matrix-diagonal-sum", + "description": "Given a square matrix mat, return the sum of the matrix diagonals. Only include the sum of all the elements on the primary diagonal and all the elements on the secondary diagonal that are not part of the primary diagonal. ", + "category": [ + "Array", + "Matrix" + ], + "complexity": "Easy", + "successrate": 79.1, + "totalsubmissions": 127163, + "totalaccepted": 100523, + "likes": 1053, + "dislikes": 20, + "hints": "There will be overlap of elements in the primary and secondary diagonals if and only if the length of the matrix is odd, which is at the center.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "mat = [[1,2,3],\n  [4,5,6],\n  [7,8,9]]", + "expected_output": "25\nExplanation: Diagonals sum: 1 + 5 + 9 + 3 + 7 = 25\nNotice that element mat[1][1] = 5 is counted only once.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "mat = [[1,1,1,1],\n  [1,1,1,1],\n  [1,1,1,1],\n  [1,1,1,1]]", + "expected_output": "8", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "mat = [[5]]", + "expected_output": "5", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720dfe", + "questionid": 819, + "title": "Sum of All Odd Length Subarrays", + "slug": "sum-of-all-odd-length-subarrays", + "description": "Given an array of positive integers arr, calculate the sum of all possible odd-length subarrays. A subarray is a contiguous subsequence of the array. Return the sum of all odd-length subarrays of arr. ", + "category": [ + "Array", + "Math", + "Prefix Sum" + ], + "complexity": "Easy", + "successrate": 83.4, + "totalsubmissions": 110599, + "totalaccepted": 92214, + "likes": 1901, + "dislikes": 155, + "hints": "You can brute force €“ try every (i,j) pair, and if the length is odd, go through and add the sum to the answer.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "arr = [1,4,2,5,3]", + "expected_output": "58\nExplanation: The odd-length subarrays of arr and their sums are:\n[1] = 1\n[4] = 4\n[2] = 2\n[5] = 5\n[3] = 3\n[1,4,2] = 7\n[4,2,5] = 11\n[2,5,3] = 10\n[1,4,2,5,3] = 15\nIf we add all these together we get 1 + 4 + 2 + 5 + 3 + 7 + 11 + 10 + 15 = 58", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "arr = [1,2]", + "expected_output": "3\nExplanation: There are only 2 subarrays of odd length, [1] and [2]. Their sum is 3.", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "arr = [10,11,12]", + "expected_output": "66", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720dff", + "questionid": 820, + "title": "Make Sum Divisible by P", + "slug": "make-sum-divisible-by-p", + "description": "Given an array of positive integers nums, remove the smallest subarray (possibly empty) such that the sum of the remaining elements is divisible by p. It is not allowed to remove the whole array. Return the length of the smallest subarray that you need to remove, or -1 if it's impossible. A subarray is defined as a contiguous block of elements in the array. ", + "category": [ + "Array", + "Hash Table", + "Prefix Sum" + ], + "complexity": "Medium", + "successrate": 28.2, + "totalsubmissions": 55868, + "totalaccepted": 15733, + "likes": 878, + "dislikes": 38, + "hints": "Use prefix sums to calculate the subarray sums. Suppose you know the remainder for the sum of the entire array. How does removing a subarray affect that remainder? What remainder does the subarray need to have in order to make the rest of the array sum up to be divisible by k? Use a map to keep track of the rightmost index for every prefix sum % p.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [3,1,4,2], p = 6", + "expected_output": "1", + "explanation": "The sum of the elements in nums is 10, which is not divisible by 6. We can remove the subarray [4], and the sum of the remaining elements is 6, which is divisible by 6." + }, + { + "example_num": 2, + "expected_input": "nums = [6,3,5,2], p = 9", + "expected_output": "2", + "explanation": "We cannot remove a single element to get a sum divisible by 9. The best way is to remove the subarray [5,2], leaving us with [6,3] with sum 9." + }, + { + "example_num": 3, + "expected_input": "nums = [1,2,3], p = 3", + "expected_output": "0", + "explanation": "Here the sum is 6. which is already divisible by 3. Thus we do not need to remove anything." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e00", + "questionid": 821, + "title": "Maximum Sum Obtained of Any Permutation", + "slug": "maximum-sum-obtained-of-any-permutation", + "description": "We have an array of integers, nums, and an array of requests where requests[i] = [starti, endi]. The ith request asks for the sum of nums[starti] + nums[starti + 1] + ... + nums[endi - 1] + nums[endi]. Both starti and endi are 0-indexed. Return the maximum total sum of all requests among all permutations of nums. Since the answer may be too large, return it modulo 109 + 7. ", + "category": [ + "Array", + "Greedy", + "Sorting", + "Prefix Sum" + ], + "complexity": "Medium", + "successrate": 36.2, + "totalsubmissions": 33296, + "totalaccepted": 12069, + "likes": 487, + "dislikes": 26, + "hints": "Indexes with higher frequencies should be bound with larger values", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,2,3,4,5], requests = [[1,3],[0,1]]", + "expected_output": "19", + "explanation": "One permutation of nums is [2,1,3,4,5] with the following result: \nrequests[0] -> nums[1] + nums[2] + nums[3] = 1 + 3 + 4 = 8\nrequests[1] -> nums[0] + nums[1] = 2 + 1 = 3\nTotal sum: 8 + 3 = 11.\nA permutation with a higher total sum is [3,5,4,2,1] with the following result:\nrequests[0] -> nums[1] + nums[2] + nums[3] = 5 + 4 + 2 = 11\nrequests[1] -> nums[0] + nums[1] = 3 + 5 = 8\nTotal sum: 11 + 8 = 19, which is the best that you can do." + }, + { + "example_num": 2, + "expected_input": "nums = [1,2,3,4,5,6], requests = [[0,1]]", + "expected_output": "11", + "explanation": "A permutation with the max total sum is [6,5,4,3,2,1] with request sums [11]." + }, + { + "example_num": 3, + "expected_input": "nums = [1,2,3,4,5,10], requests = [[0,2],[1,3],[1,1]]", + "expected_output": "47", + "explanation": "A permutation with the max total sum is [4,10,5,3,2,1] with request sums [19,18,10]." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e08", + "questionid": 829, + "title": "Minimum Cost to Connect Two Groups of Points", + "slug": "minimum-cost-to-connect-two-groups-of-points", + "description": "You are given two groups of points where the first group has size1 points, the second group has size2 points, and size1 >= size2. The cost of the connection between any two points are given in an size1 x size2 matrix where cost[i][j] is the cost of connecting point i of the first group and point j of the second group. The groups are connected if each point in both groups is connected to one or more points in the opposite group. In other words, each point in the first group must be connected to at least one point in the second group, and each point in the second group must be connected to at least one point in the first group. Return the minimum cost it takes to connect the two groups. ", + "category": [ + "Array", + "Dynamic Programming", + "Bit Manipulation", + "Matrix", + "Bitmask" + ], + "complexity": "Hard", + "successrate": 45.9, + "totalsubmissions": 13535, + "totalaccepted": 6208, + "likes": 322, + "dislikes": 12, + "hints": "Each point on the left would either be connected to exactly point already connected to some left node, or a subset of the nodes on the right which are not connected to any node Use dynamic programming with bitmasking, where the state will be (number of points assigned in first group, bitmask of points assigned in second group).", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "cost = [[15, 96], [36, 2]]", + "expected_output": "17\nExplanation: The optimal way of connecting the groups is:\n1--A\n2--B\nThis results in a total cost of 17.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "cost = [[1, 3, 5], [4, 1, 1], [1, 5, 3]]", + "expected_output": "4\nExplanation: The optimal way of connecting the groups is:\n1--A\n2--B\n2--C\n3--A\nThis results in a total cost of 4.\nNote that there are multiple points connected to point 2 in the first group and point A in the second group. This does not matter as there is no limit to the number of points that can be connected. We only care about the minimum total cost.", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "cost = [[2, 5, 1], [3, 4, 7], [8, 1, 2], [6, 2, 4], [3, 8, 8]]", + "expected_output": "10", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e09", + "questionid": 830, + "title": "Maximum Profit of Operating a Centennial Wheel", + "slug": "maximum-profit-of-operating-a-centennial-wheel", + "description": "You are the operator of a Centennial Wheel that has four gondolas, and each gondola has room for up to four people. You have the ability to rotate the gondolas counterclockwise, which costs you runningCost dollars. You are given an array customers of length n where customers[i] is the number of new customers arriving just before the ith rotation (0-indexed). This means you must rotate the wheel i times before the customers[i] customers arrive. You cannot make customers wait if there is room in the gondola. Each customer pays boardingCost dollars when they board on the gondola closest to the ground and will exit once that gondola reaches the ground again. You can stop the wheel at any time, including before serving all customers. If you decide to stop serving customers, all subsequent rotations are free in order to get all the customers down safely. Note that if there are currently more than four customers waiting at the wheel, only four will board the gondola, and the rest will wait for the next rotation. Return the minimum number of rotations you need to perform to maximize your profit. If there is no scenario where the profit is positive, return -1. ", + "category": [ + "Array", + "Simulation" + ], + "complexity": "Medium", + "successrate": 43.9, + "totalsubmissions": 21987, + "totalaccepted": 9658, + "likes": 67, + "dislikes": 207, + "hints": "Think simulation Note that the number of turns will never be more than 50 / 4 * n", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "customers = [8,3], boardingCost = 5, runningCost = 6", + "expected_output": "3", + "explanation": "The numbers written on the gondolas are the number of people currently there.\n1. 8 customers arrive, 4 board and 4 wait for the next gondola, the wheel rotates. Current profit is 4 * $5 - 1 * $6 = $14.\n2. 3 customers arrive, the 4 waiting board the wheel and the other 3 wait, the wheel rotates. Current profit is 8 * $5 - 2 * $6 = $28.\n3. The final 3 customers board the gondola, the wheel rotates. Current profit is 11 * $5 - 3 * $6 = $37.\nThe highest profit was $37 after rotating the wheel 3 times." + }, + { + "example_num": 2, + "expected_input": "customers = [10,9,6], boardingCost = 6, runningCost = 4", + "expected_output": "7", + "explanation": "1. 10 customers arrive, 4 board and 6 wait for the next gondola, the wheel rotates. Current profit is 4 * $6 - 1 * $4 = $20.\n2. 9 customers arrive, 4 board and 11 wait (2 originally waiting, 9 newly waiting), the wheel rotates. Current profit is 8 * $6 - 2 * $4 = $40.\n3. The final 6 customers arrive, 4 board and 13 wait, the wheel rotates. Current profit is 12 * $6 - 3 * $4 = $60.\n4. 4 board and 9 wait, the wheel rotates. Current profit is 16 * $6 - 4 * $4 = $80.\n5. 4 board and 5 wait, the wheel rotates. Current profit is 20 * $6 - 5 * $4 = $100.\n6. 4 board and 1 waits, the wheel rotates. Current profit is 24 * $6 - 6 * $4 = $120.\n7. 1 boards, the wheel rotates. Current profit is 25 * $6 - 7 * $4 = $122.\nThe highest profit was $122 after rotating the wheel 7 times." + }, + { + "example_num": 3, + "expected_input": "customers = [3,4,0,5,1], boardingCost = 1, runningCost = 92", + "expected_output": "-1", + "explanation": "1. 3 customers arrive, 3 board and 0 wait, the wheel rotates. Current profit is 3 * $1 - 1 * $92 = -$89.\n2. 4 customers arrive, 4 board and 0 wait, the wheel rotates. Current profit is 7 * $1 - 2 * $92 = -$177.\n3. 0 customers arrive, 0 board and 0 wait, the wheel rotates. Current profit is 7 * $1 - 3 * $92 = -$269.\n4. 5 customers arrive, 4 board and 1 waits, the wheel rotates. Current profit is 11 * $1 - 4 * $92 = -$357.\n5. 1 customer arrives, 2 board and 0 wait, the wheel rotates. Current profit is 13 * $1 - 5 * $92 = -$447.\nThe profit was never positive, so return -1." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e0d", + "questionid": 834, + "title": "Maximum Number of Visible Points", + "slug": "maximum-number-of-visible-points", + "description": "You are given an array points, an integer angle, and your location, where location = [posx, posy] and points[i] = [xi, yi] both denote integral coordinates on the X-Y plane. Initially, you are facing directly east from your position. You cannot move from your position, but you can rotate. In other words, posx and posy cannot be changed. Your field of view in degrees is represented by angle, determining how wide you can see from any given view direction. Let d be the amount in degrees that you rotate counterclockwise. Then, your field of view is the inclusive range of angles [d - angle/2, d + angle/2]. Your browser does not support the video tag or this video format. You can see some set of points if, for each point, the angle formed by the point, your position, and the immediate east direction from your position is in your field of view. There can be multiple points at one coordinate. There may be points at your location, and you can always see these points regardless of your rotation. Points do not obstruct your vision to other points. Return the maximum number of points you can see. ", + "category": [ + "Array", + "Math", + "Geometry", + "Sliding Window", + "Sorting" + ], + "complexity": "Hard", + "successrate": 36.6, + "totalsubmissions": 69650, + "totalaccepted": 25473, + "likes": 373, + "dislikes": 506, + "hints": "Sort the points by polar angle with the original position. Now only a consecutive collection of points would be visible from any coordinate. We can use two pointers to keep track of visible points for each start point For handling the cyclic condition, it€™d be helpful to append the point list to itself after sorting.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "points = [[2,1],[2,2],[3,3]], angle = 90, location = [1,1]", + "expected_output": "3", + "explanation": "The shaded region represents your field of view. All points can be made visible in your field of view, including [3,3] even though [2,2] is in front and in the same line of sight." + }, + { + "example_num": 2, + "expected_input": "points = [[2,1],[2,2],[3,4],[1,1]], angle = 90, location = [1,1]", + "expected_output": "4", + "explanation": "All points can be made visible in your field of view, including the one at your location." + }, + { + "example_num": 3, + "expected_input": "points = [[1,0],[2,1]], angle = 13, location = [1,1]", + "expected_output": "1", + "explanation": "You can only see one of the two points, as shown above." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e0c", + "questionid": 833, + "title": "Special Array With X Elements Greater Than or Equal X", + "slug": "special-array-with-x-elements-greater-than-or-equal-x", + "description": "You are given an array nums of non-negative integers. nums is considered special if there exists a number x such that there are exactly x numbers in nums that are greater than or equal to x. Notice that x does not have to be an element in nums. Return x if the array is special, otherwise, return -1. It can be proven that if nums is special, the value for x is unique. ", + "category": [ + "Array", + "Binary Search", + "Sorting" + ], + "complexity": "Easy", + "successrate": 60.5, + "totalsubmissions": 59654, + "totalaccepted": 36114, + "likes": 732, + "dislikes": 117, + "hints": "Count the number of elements greater than or equal to x for each x in the range [0, nums.length]. If for any x, the condition satisfies, return that x. Otherwise, there is no answer.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [3,5]", + "expected_output": "2", + "explanation": "There are 2 values (3 and 5) that are greater than or equal to 2." + }, + { + "example_num": 2, + "expected_input": "nums = [0,0]", + "expected_output": "-1", + "explanation": "No numbers fit the criteria for x.\nIf x = 0, there should be 0 numbers >= x, but there are 2.\nIf x = 1, there should be 1 number >= x, but there are 0.\nIf x = 2, there should be 2 numbers >= x, but there are 0.\nx cannot be greater since there are only 2 numbers in nums." + }, + { + "example_num": 3, + "expected_input": "nums = [0,4,3,0,4]", + "expected_output": "3", + "explanation": "There are 3 values that are greater than or equal to 3." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e0f", + "questionid": 836, + "title": "Count Subtrees With Max Distance Between Cities", + "slug": "count-subtrees-with-max-distance-between-cities", + "description": "There are n cities numbered from 1 to n. You are given an array edges of size n-1, where edges[i] = [ui, vi] represents a bidirectional edge between cities ui and vi. There exists a unique path between each pair of cities. In other words, the cities form a tree. A subtree is a subset of cities where every city is reachable from every other city in the subset, where the path between each pair passes through only the cities from the subset. Two subtrees are different if there is a city in one subtree that is not present in the other. For each d from 1 to n-1, find the number of subtrees in which the maximum distance between any two cities in the subtree is equal to d. Return an array of size n-1 where the dth element (1-indexed) is the number of subtrees in which the maximum distance between any two cities is equal to d. Notice that the distance between the two cities is the number of edges in the path between them. ", + "category": [ + "Dynamic Programming", + "Bit Manipulation", + "Tree", + "Enumeration", + "Bitmask" + ], + "complexity": "Hard", + "successrate": 65.3, + "totalsubmissions": 9323, + "totalaccepted": 6088, + "likes": 295, + "dislikes": 28, + "hints": "Iterate through every possible subtree by doing a bitmask on which vertices to include. How can you determine if a subtree is valid (all vertices are connected)? To determine connectivity, count the number of reachable vertices starting from any included vertex and only traveling on edges connecting 2 vertices in the subtree. The count should be the same as the number of 1s in the bitmask. The diameter is basically the maximum distance between any two nodes. Root the tree at a vertex. The answer is the max of the heights of the two largest subtrees or the longest diameter in any of the subtrees.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 4, edges = [[1,2],[2,3],[2,4]]", + "expected_output": "[3,4,0]\r\nExplanation:\r\nThe subtrees with subsets {1,2}, {2,3} and {2,4} have a max distance of 1.\r\nThe subtrees with subsets {1,2,3}, {1,2,4}, {2,3,4} and {1,2,3,4} have a max distance of 2.\r\nNo subtree has two nodes where the max distance between them is 3.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "n = 2, edges = [[1,2]]", + "expected_output": "[1]", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "n = 3, edges = [[1,2],[2,3]]", + "expected_output": "[2,1]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e13", + "questionid": 840, + "title": "Largest Substring Between Two Equal Characters", + "slug": "largest-substring-between-two-equal-characters", + "description": "Given a string s, return the length of the longest substring between two equal characters, excluding the two characters. If there is no such substring return -1. A substring is a contiguous sequence of characters within a string. ", + "category": [ + "Hash Table", + "String" + ], + "complexity": "Easy", + "successrate": 59.2, + "totalsubmissions": 53135, + "totalaccepted": 31464, + "likes": 377, + "dislikes": 24, + "hints": "Try saving the first and last position of each character Try finding every pair of indexes with equal characters", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "aa"", + "expected_output": "0", + "explanation": "The optimal substring here is an empty substring between the two 'a's." + }, + { + "example_num": 2, + "expected_input": "s = "abca"", + "expected_output": "2", + "explanation": "The optimal substring here is "bc"." + }, + { + "example_num": 3, + "expected_input": "s = "cbzxy"", + "expected_output": "-1", + "explanation": "There are no characters that appear twice in s." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e16", + "questionid": 843, + "title": "Path With Minimum Effort", + "slug": "path-with-minimum-effort", + "description": "You are a hiker preparing for an upcoming hike. You are given heights, a 2D array of size rows x columns, where heights[row][col] represents the height of cell (row, col). You are situated in the top-left cell, (0, 0), and you hope to travel to the bottom-right cell, (rows-1, columns-1) (i.e., 0-indexed). You can move up, down, left, or right, and you wish to find a route that requires the minimum effort. A route's effort is the maximum absolute difference in heights between two consecutive cells of the route. Return the minimum effort required to travel from the top-left cell to the bottom-right cell. ", + "category": [ + "Array", + "Binary Search", + "Depth-First Search", + "Breadth-First Search", + "Union Find", + "Heap (Priority Queue)", + "Matrix" + ], + "complexity": "Medium", + "successrate": 52, + "totalsubmissions": 142763, + "totalaccepted": 74173, + "likes": 2084, + "dislikes": 98, + "hints": "Consider the grid as a graph, where adjacent cells have an edge with cost of the difference between the cells. If you are given threshold k, check if it is possible to go from (0, 0) to (n-1, m-1) using only edges of ‰¤ k cost. Binary search the k value.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "heights = [[1,2,2],[3,8,2],[5,3,5]]", + "expected_output": "2", + "explanation": "The route of [1,3,5,3,5] has a maximum absolute difference of 2 in consecutive cells.\nThis is better than the route of [1,2,2,2,5], where the maximum absolute difference is 3." + }, + { + "example_num": 2, + "expected_input": "heights = [[1,2,3],[3,8,4],[5,3,5]]", + "expected_output": "1", + "explanation": "The route of [1,2,3,4,5] has a maximum absolute difference of 1 in consecutive cells, which is better than route [1,3,5,3,5]." + }, + { + "example_num": 3, + "expected_input": "heights = [[1,2,1,1,1],[1,2,1,2,1],[1,2,1,2,1],[1,2,1,2,1],[1,1,1,2,1]]", + "expected_output": "0", + "explanation": "This route does not require any effort." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e1a", + "questionid": 847, + "title": "Count Sorted Vowel Strings", + "slug": "count-sorted-vowel-strings", + "description": "Given an integer n, return the number of strings of length n that consist only of vowels (a, e, i, o, u) and are lexicographically sorted. A string s is lexicographically sorted if for all valid i, s[i] is the same as or comes before s[i+1] in the alphabet. ", + "category": [ + "Dynamic Programming" + ], + "complexity": "Medium", + "successrate": 74.9, + "totalsubmissions": 110393, + "totalaccepted": 82665, + "likes": 1763, + "dislikes": 38, + "hints": "For each character, its possible values will depend on the value of its previous character, because it needs to be not smaller than it. Think backtracking. Build a recursive function count(n, last_character) that counts the number of valid strings of length n and whose first characters are not less than last_character. In this recursive function, iterate on the possible characters for the first character, which will be all the vowels not less than last_character, and for each possible value c, increase the answer by count(n-1, c).", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 1", + "expected_output": "5", + "explanation": "The 5 sorted strings that consist of vowels only are ["a","e","i","o","u"]." + }, + { + "example_num": 2, + "expected_input": "n = 2", + "expected_output": "15", + "explanation": "The 15 sorted strings that consist of vowels only are\n["aa","ae","ai","ao","au","ee","ei","eo","eu","ii","io","iu","oo","ou","uu"].\nNote that "ea" is not a valid string since 'e' comes after 'a' in the alphabet." + }, + { + "example_num": 3, + "expected_input": "n = 33", + "expected_output": "66045", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e1e", + "questionid": 851, + "title": "Sell Diminishing-Valued Colored Balls", + "slug": "sell-diminishing-valued-colored-balls", + "description": "You have an inventory of different colored balls, and there is a customer that wants orders balls of any color. The customer weirdly values the colored balls. Each colored ball's value is the number of balls of that color you currently have in your inventory. For example, if you own 6 yellow balls, the customer would pay 6 for the first yellow ball. After the transaction, there are only 5 yellow balls left, so the next yellow ball is then valued at 5 (i.e., the value of the balls decreases as you sell more to the customer). You are given an integer array, inventory, where inventory[i] represents the number of balls of the ith color that you initially own. You are also given an integer orders, which represents the total number of balls that the customer wants. You can sell the balls in any order. Return the maximum total value that you can attain after selling orders colored balls. As the answer may be too large, return it modulo 109 + 7. ", + "category": [ + "Array", + "Math", + "Binary Search", + "Greedy", + "Sorting", + "Heap (Priority Queue)" + ], + "complexity": "Medium", + "successrate": 30.6, + "totalsubmissions": 90962, + "totalaccepted": 27814, + "likes": 718, + "dislikes": 273, + "hints": "Greedily sell the most expensive ball. There is some value k where all balls of value > k are sold, and some, (maybe 0) of balls of value k are sold. Use binary search to find this value k, and use maths to find the total sum.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "inventory = [2,5], orders = 4", + "expected_output": "14", + "explanation": "Sell the 1st color 1 time (2) and the 2nd color 3 times (5 + 4 + 3).\nThe maximum total value is 2 + 5 + 4 + 3 = 14." + }, + { + "example_num": 2, + "expected_input": "inventory = [3,5], orders = 6", + "expected_output": "19\nExplanation: Sell the 1st color 2 times (3 + 2) and the 2nd color 4 times (5 + 4 + 3 + 2).\nThe maximum total value is 3 + 2 + 5 + 4 + 3 + 2 = 19.", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e24", + "questionid": 857, + "title": "Richest Customer Wealth", + "slug": "richest-customer-wealth", + "description": "You are given an m x n integer grid accounts where accounts[i][j] is the amount of money the i​​​​​​​​​​​th​​​​ customer has in the j​​​​​​​​​​​th bank. Return the wealth that the richest customer has. A customer's wealth is the amount of money they have in all their bank accounts. The richest customer is the customer that has the maximum wealth. ", + "category": [ + "Array", + "Matrix" + ], + "complexity": "Easy", + "successrate": 89.3, + "totalsubmissions": 310405, + "totalaccepted": 277200, + "likes": 1770, + "dislikes": 256, + "hints": "Calculate the wealth of each customer Find the maximum element in array.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "accounts = [[1,2,3],[3,2,1]]", + "expected_output": "6\nExplanation:\n1st customer has wealth = 1 + 2 + 3 = 6\n2nd customer has wealth = 3 + 2 + 1 = 6\nBoth customers are considered the richest with a wealth of 6 each, so return 6.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "accounts = [[1,5],[7,3],[3,5]]", + "expected_output": "10\nExplanation: \n1st customer has wealth = 6\n2nd customer has wealth = 10 \n3rd customer has wealth = 8\nThe 2nd customer is the richest with a wealth of 10.", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "accounts = [[2,8,7],[7,1,3],[1,9,5]]", + "expected_output": "17", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e2c", + "questionid": 865, + "title": "Partitioning Into Minimum Number Of Deci-Binary Numbers", + "slug": "partitioning-into-minimum-number-of-deci-binary-numbers", + "description": "A decimal number is called deci-binary if each of its digits is either 0 or 1 without any leading zeros. For example, 101 and 1100 are deci-binary, while 112 and 3001 are not. Given a string n that represents a positive decimal integer, return the minimum number of positive deci-binary numbers needed so that they sum up to n. ", + "category": [ + "String", + "Greedy" + ], + "complexity": "Medium", + "successrate": 87.8, + "totalsubmissions": 86815, + "totalaccepted": 76222, + "likes": 789, + "dislikes": 559, + "hints": "Think about if the input was only one digit. Then you need to add up as many ones as the value of this digit. If the input has multiple digits, then you can solve for each digit independently, and merge the answers to form numbers that add up to that input. Thus the answer is equal to the max digit.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = "32"", + "expected_output": "3", + "explanation": "10 + 11 + 11 = 32" + }, + { + "example_num": 2, + "expected_input": "n = "82734"", + "expected_output": "8", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "n = "27346209830709182346"", + "expected_output": "9", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e34", + "questionid": 873, + "title": "Maximum Number of Eaten Apples", + "slug": "maximum-number-of-eaten-apples", + "description": "There is a special kind of apple tree that grows apples every day for n days. On the ith day, the tree grows apples[i] apples that will rot after days[i] days, that is on day i + days[i] the apples will be rotten and cannot be eaten. On some days, the apple tree does not grow any apples, which are denoted by apples[i] == 0 and days[i] == 0. You decided to eat at most one apple a day (to keep the doctors away). Note that you can keep eating after the first n days. Given two integer arrays days and apples of length n, return the maximum number of apples you can eat. ", + "category": [ + "Array", + "Greedy", + "Heap (Priority Queue)" + ], + "complexity": "Medium", + "successrate": 36.4, + "totalsubmissions": 38800, + "totalaccepted": 14118, + "likes": 489, + "dislikes": 145, + "hints": "It's optimal to finish the apples that will rot first before those that will rot last You need a structure to keep the apples sorted by their finish time", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "apples = [1,2,3,5,2], days = [3,2,1,4,2]", + "expected_output": "7", + "explanation": "You can eat 7 apples:\n- On the first day, you eat an apple that grew on the first day.\n- On the second day, you eat an apple that grew on the second day.\n- On the third day, you eat an apple that grew on the second day. After this day, the apples that grew on the third day rot.\n- On the fourth to the seventh days, you eat apples that grew on the fourth day." + }, + { + "example_num": 2, + "expected_input": "apples = [3,0,0,0,0,2], days = [3,0,0,0,0,2]", + "expected_output": "5", + "explanation": "You can eat 5 apples:\n- On the first to the third day you eat apples that grew on the first day.\n- Do nothing on the fouth and fifth days.\n- On the sixth and seventh days you eat apples that grew on the sixth day." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e3d", + "questionid": 882, + "title": "Minimize Hamming Distance After Swap Operations", + "slug": "minimize-hamming-distance-after-swap-operations", + "description": "You are given two integer arrays, source and target, both of length n. You are also given an array allowedSwaps where each allowedSwaps[i] = [ai, bi] indicates that you are allowed to swap the elements at index ai and index bi (0-indexed) of array source. Note that you can swap elements at a specific pair of indices multiple times and in any order. The Hamming distance of two arrays of the same length, source and target, is the number of positions where the elements are different. Formally, it is the number of indices i for 0 <= i <= n-1 where source[i] != target[i] (0-indexed). Return the minimum Hamming distance of source and target after performing any amount of swap operations on array source. ", + "category": [ + "Array", + "Depth-First Search", + "Union Find" + ], + "complexity": "Medium", + "successrate": 47.9, + "totalsubmissions": 25012, + "totalaccepted": 11985, + "likes": 567, + "dislikes": 17, + "hints": "The source array can be imagined as a graph where each index is a node and each allowedSwaps[i] is an edge. Nodes within the same component can be freely swapped with each other. For each component, find the number of common elements. The elements that are not in common will contribute to the total Hamming distance.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "source = [1,2,3,4], target = [2,1,4,5], allowedSwaps = [[0,1],[2,3]]", + "expected_output": "1", + "explanation": "source can be transformed the following way:\n- Swap indices 0 and 1: source = [2,1,3,4]\n- Swap indices 2 and 3: source = [2,1,4,3]\nThe Hamming distance of source and target is 1 as they differ in 1 position: index 3." + }, + { + "example_num": 2, + "expected_input": "source = [1,2,3,4], target = [1,3,2,4], allowedSwaps = []", + "expected_output": "2", + "explanation": "There are no allowed swaps.\nThe Hamming distance of source and target is 2 as they differ in 2 positions: index 1 and index 2." + }, + { + "example_num": 3, + "expected_input": "source = [5,1,2,4,3], target = [1,5,4,2,3], allowedSwaps = [[0,4],[4,2],[1,3],[1,4]]", + "expected_output": "0", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e3e", + "questionid": 883, + "title": "Number Of Rectangles That Can Form The Largest Square", + "slug": "number-of-rectangles-that-can-form-the-largest-square", + "description": "You are given an array rectangles where rectangles[i] = [li, wi] represents the ith rectangle of length li and width wi. You can cut the ith rectangle to form a square with a side length of k if both k <= li and k <= wi. For example, if you have a rectangle [4,6], you can cut it to get a square with a side length of at most 4. Let maxLen be the side length of the largest square you can obtain from any of the given rectangles. Return the number of rectangles that can make a square with a side length of maxLen. ", + "category": [ + "Array" + ], + "complexity": "Easy", + "successrate": 78.8, + "totalsubmissions": 51652, + "totalaccepted": 40686, + "likes": 333, + "dislikes": 40, + "hints": "What is the length of the largest square the can be cut out of some rectangle? It'll be equal to min(rectangle.length, rectangle.width). Replace each rectangle with this value. Calculate maxSize by iterating over the given rectangles and maximizing the answer with their values denoted in the first hint. Then iterate again on the rectangles and calculate the number whose values = maxSize.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "rectangles = [[5,8],[3,9],[5,12],[16,5]]", + "expected_output": "3", + "explanation": "The largest squares you can get from each rectangle are of lengths [5,3,5,5].\r\nThe largest possible square is of length 5, and you can get it out of 3 rectangles." + }, + { + "example_num": 2, + "expected_input": "rectangles = [[2,3],[3,7],[4,3],[3,7]]", + "expected_output": "3", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e46", + "questionid": 891, + "title": "Form Array by Concatenating Subarrays of Another Array", + "slug": "form-array-by-concatenating-subarrays-of-another-array", + "description": "You are given a 2D integer array groups of length n. You are also given an integer array nums. You are asked if you can choose n disjoint subarrays from the array nums such that the ith subarray is equal to groups[i] (0-indexed), and if i > 0, the (i-1)th subarray appears before the ith subarray in nums (i.e. the subarrays must be in the same order as groups). Return true if you can do this task, and false otherwise. Note that the subarrays are disjoint if and only if there is no index k such that nums[k] belongs to more than one subarray. A subarray is a contiguous sequence of elements within an array. ", + "category": [ + "Array", + "Greedy", + "String Matching" + ], + "complexity": "Medium", + "successrate": 53, + "totalsubmissions": 19359, + "totalaccepted": 10259, + "likes": 202, + "dislikes": 21, + "hints": "When we use a subarray, the room for the next subarrays will be the suffix after the used subarray. If we can match a group with multiple subarrays, we should choose the first one, as this will just leave the largest room for the next subarrays.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "groups = [[1,-1,-1],[3,-2,0]], nums = [1,-1,0,1,-1,-1,3,-2,0]", + "expected_output": "true", + "explanation": "You can choose the 0th subarray as [1,-1,0,1,-1,-1,3,-2,0] and the 1st one as [1,-1,0,1,-1,-1,3,-2,0].\nThese subarrays are disjoint as they share no common nums[k] element." + }, + { + "example_num": 2, + "expected_input": "groups = [[10,-2],[1,2,3,4]], nums = [1,2,3,4,10,-2]", + "expected_output": "false\nExplanation: Note that choosing the subarrays [1,2,3,4,10,-2] and [1,2,3,4,10,-2] is incorrect because they are not in the same order as in groups.\n[10,-2] must come before [1,2,3,4].", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "groups = [[1,2,3],[3,4]], nums = [7,7,1,2,3,4,7,7]", + "expected_output": "false\nExplanation: Note that choosing the subarrays [7,7,1,2,3,4,7,7] and [7,7,1,2,3,4,7,7] is invalid because they are not disjoint.\nThey share a common elements nums[4] (0-indexed).", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e48", + "questionid": 893, + "title": "Maximum Score From Removing Stones", + "slug": "maximum-score-from-removing-stones", + "description": "You are playing a solitaire game with three piles of stones of sizes a, b, and c respectively. Each turn you choose two different non-empty piles, take one stone from each, and add 1 point to your score. The game stops when there are fewer than two non-empty piles (meaning there are no more available moves). Given three integers a, b, and c, return the maximum score you can get. ", + "category": [ + "Math", + "Greedy", + "Heap (Priority Queue)" + ], + "complexity": "Medium", + "successrate": 65.2, + "totalsubmissions": 32426, + "totalaccepted": 21143, + "likes": 485, + "dislikes": 34, + "hints": "It's optimal to always remove one stone from the biggest 2 piles Note that the limits are small enough for simulation", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "a = 2, b = 4, c = 6", + "expected_output": "6", + "explanation": "The starting state is (2, 4, 6). One optimal set of moves is:\n- Take from 1st and 3rd piles, state is now (1, 4, 5)\n- Take from 1st and 3rd piles, state is now (0, 4, 4)\n- Take from 2nd and 3rd piles, state is now (0, 3, 3)\n- Take from 2nd and 3rd piles, state is now (0, 2, 2)\n- Take from 2nd and 3rd piles, state is now (0, 1, 1)\n- Take from 2nd and 3rd piles, state is now (0, 0, 0)\nThere are fewer than two non-empty piles, so the game ends. Total: 6 points." + }, + { + "example_num": 2, + "expected_input": "a = 4, b = 4, c = 6", + "expected_output": "7", + "explanation": "The starting state is (4, 4, 6). One optimal set of moves is:\n- Take from 1st and 2nd piles, state is now (3, 3, 6)\n- Take from 1st and 3rd piles, state is now (2, 3, 5)\n- Take from 1st and 3rd piles, state is now (1, 3, 4)\n- Take from 1st and 3rd piles, state is now (0, 3, 3)\n- Take from 2nd and 3rd piles, state is now (0, 2, 2)\n- Take from 2nd and 3rd piles, state is now (0, 1, 1)\n- Take from 2nd and 3rd piles, state is now (0, 0, 0)\nThere are fewer than two non-empty piles, so the game ends. Total: 7 points." + }, + { + "example_num": 3, + "expected_input": "a = 1, b = 8, c = 8", + "expected_output": "8", + "explanation": "One optimal set of moves is to take from the 2nd and 3rd piles for 8 turns until they are empty.\nAfter that, there are fewer than two non-empty piles, so the game ends." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e11", + "questionid": 838, + "title": "Widest Vertical Area Between Two Points Containing No Points", + "slug": "widest-vertical-area-between-two-points-containing-no-points", + "description": "Given n points on a 2D plane where points[i] = [xi, yi], Return the widest vertical area between two points such that no points are inside the area. A vertical area is an area of fixed-width extending infinitely along the y-axis (i.e., infinite height). The widest vertical area is the one with the maximum width. Note that points on the edge of a vertical area are not considered included in the area. ", + "category": [ + "Array", + "Sorting" + ], + "complexity": "Medium", + "successrate": 84, + "totalsubmissions": 33632, + "totalaccepted": 28243, + "likes": 170, + "dislikes": 494, + "hints": "Try sorting the points Think is the y-axis of a point relevant", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "points = [[8,7],[9,9],[7,4],[9,7]]", + "expected_output": "1", + "explanation": "Both the red and the blue area are optimal." + }, + { + "example_num": 2, + "expected_input": "points = [[3,1],[9,0],[1,0],[1,4],[5,3],[8,8]]", + "expected_output": "3", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e18", + "questionid": 845, + "title": "Minimum Deletions to Make String Balanced", + "slug": "minimum-deletions-to-make-string-balanced", + "description": "You are given a string s consisting only of characters 'a' and 'b'. You can delete any number of characters in s to make s balanced. s is balanced if there is no pair of indices (i,j) such that i < j and s[i] = 'b' and s[j]= 'a'. Return the minimum number of deletions needed to make s balanced. ", + "category": [ + "String", + "Dynamic Programming", + "Stack" + ], + "complexity": "Medium", + "successrate": 56, + "totalsubmissions": 33672, + "totalaccepted": 18869, + "likes": 682, + "dislikes": 19, + "hints": "You need to find for every index the number of Bs before it and the number of A's after it You can speed up the finding of A's and B's in suffix and prefix using preprocessing", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "aababbab"", + "expected_output": "2", + "explanation": "You can either:\nDelete the characters at 0-indexed positions 2 and 6 ("aababbab" -> "aaabbb"), or\nDelete the characters at 0-indexed positions 3 and 6 ("aababbab" -> "aabbbb")." + }, + { + "example_num": 2, + "expected_input": "s = "bbaaaaabb"", + "expected_output": "2", + "explanation": "The only solution is to delete the first two characters." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e19", + "questionid": 846, + "title": "Check Array Formation Through Concatenation", + "slug": "check-array-formation-through-concatenation", + "description": "You are given an array of distinct integers arr and an array of integer arrays pieces, where the integers in pieces are distinct. Your goal is to form arr by concatenating the arrays in pieces in any order. However, you are not allowed to reorder the integers in each array pieces[i]. Return true if it is possible to form the array arr from pieces. Otherwise, return false. ", + "category": [ + "Array", + "Hash Table" + ], + "complexity": "Easy", + "successrate": 55.8, + "totalsubmissions": 119597, + "totalaccepted": 66766, + "likes": 671, + "dislikes": 112, + "hints": "Note that the distinct part means that every position in the array belongs to only one piece Note that you can get the piece every position belongs to naively", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "arr = [15,88], pieces = [[88],[15]]", + "expected_output": "true", + "explanation": "Concatenate [15] then [88]" + }, + { + "example_num": 2, + "expected_input": "arr = [49,18,16], pieces = [[16,18,49]]", + "expected_output": "false", + "explanation": "Even though the numbers match, we cannot reorder pieces[0]." + }, + { + "example_num": 3, + "expected_input": "arr = [91,4,64,78], pieces = [[78],[4,64],[91]]", + "expected_output": "true", + "explanation": "Concatenate [91] then [4,64] then [78]" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e1d", + "questionid": 850, + "title": "Minimum Deletions to Make Character Frequencies Unique", + "slug": "minimum-deletions-to-make-character-frequencies-unique", + "description": "A string s is called good if there are no two different characters in s that have the same frequency. Given a string s, return the minimum number of characters you need to delete to make s good. The frequency of a character in a string is the number of times it appears in the string. For example, in the string \"aab\", the frequency of 'a' is 2, while the frequency of 'b' is 1. ", + "category": [ + "String", + "Greedy", + "Sorting" + ], + "complexity": "Medium", + "successrate": 56.4, + "totalsubmissions": 143838, + "totalaccepted": 81115, + "likes": 1266, + "dislikes": 27, + "hints": "As we can only delete characters, if we have multiple characters having the same frequency, we must decrease all the frequencies of them, except one. Sort the alphabet characters by their frequencies non-increasingly. Iterate on the alphabet characters, keep decreasing the frequency of the current character until it reaches a value that has not appeared before.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "aab"", + "expected_output": "0", + "explanation": "s is already good." + }, + { + "example_num": 2, + "expected_input": "s = "aaabbbcc"", + "expected_output": "2", + "explanation": "You can delete two 'b's resulting in the good string "aaabcc".\nAnother way it to delete one 'b' and one 'c' resulting in the good string "aaabbc"." + }, + { + "example_num": 3, + "expected_input": "s = "ceabaacb"", + "expected_output": "2", + "explanation": "You can delete both 'c's resulting in the good string "eabaab".\nNote that we only care about characters that are still in the string at the end (i.e. frequency of 0 is ignored)." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e21", + "questionid": 854, + "title": "Smallest String With A Given Numeric Value", + "slug": "smallest-string-with-a-given-numeric-value", + "description": "The numeric value of a lowercase character is defined as its position (1-indexed) in the alphabet, so the numeric value of a is 1, the numeric value of b is 2, the numeric value of c is 3, and so on. The numeric value of a string consisting of lowercase characters is defined as the sum of its characters' numeric values. For example, the numeric value of the string \"abe\" is equal to 1 + 2 + 5 = 8. You are given two integers n and k. Return the lexicographically smallest string with length equal to n and numeric value equal to k. Note that a string x is lexicographically smaller than string y if x comes before y in dictionary order, that is, either x is a prefix of y, or if i is the first position such that x[i] != y[i], then x[i] comes before y[i] in alphabetic order. ", + "category": [ + "String", + "Greedy" + ], + "complexity": "Medium", + "successrate": 67, + "totalsubmissions": 118160, + "totalaccepted": 79194, + "likes": 1523, + "dislikes": 50, + "hints": "Think greedily. If you build the string from the end to the beginning, it will always be optimal to put the highest possible character at the current index.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 3, k = 27", + "expected_output": ""aay"", + "explanation": "The numeric value of the string is 1 + 1 + 25 = 27, and it is the smallest string with such a value and length equal to 3." + }, + { + "example_num": 2, + "expected_input": "n = 5, k = 73", + "expected_output": ""aaszz"", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e22", + "questionid": 855, + "title": "Count the Number of Consistent Strings", + "slug": "count-the-number-of-consistent-strings", + "description": "You are given a string allowed consisting of distinct characters and an array of strings words. A string is consistent if all characters in the string appear in the string allowed. Return the number of consistent strings in the array words. ", + "category": [ + "Array", + "Hash Table", + "String", + "Bit Manipulation" + ], + "complexity": "Easy", + "successrate": 81.9, + "totalsubmissions": 102721, + "totalaccepted": 84109, + "likes": 818, + "dislikes": 39, + "hints": "A string is incorrect if it contains a character that is not allowed Constraints are small enough for brute force", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "allowed = "ab", words = ["ad","bd","aaab","baa","badab"]", + "expected_output": "2", + "explanation": "Strings "aaab" and "baa" are consistent since they only contain characters 'a' and 'b'." + }, + { + "example_num": 2, + "expected_input": "allowed = "abc", words = ["a","b","c","ab","ac","bc","abc"]", + "expected_output": "7", + "explanation": "All strings are consistent." + }, + { + "example_num": 3, + "expected_input": "allowed = "cad", words = ["cc","acd","b","ba","bac","bad","ac","d"]", + "expected_output": "4", + "explanation": "Strings "cc", "acd", "ac", and "d" are consistent." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e26", + "questionid": 859, + "title": "Minimum Moves to Make Array Complementary", + "slug": "minimum-moves-to-make-array-complementary", + "description": "You are given an integer array nums of even length n and an integer limit. In one move, you can replace any integer from nums with another integer between 1 and limit, inclusive. The array nums is complementary if for all indices i (0-indexed), nums[i] + nums[n - 1 - i] equals the same number. For example, the array [1,2,3,4] is complementary because for all indices i, nums[i] + nums[n - 1 - i] = 5. Return the minimum number of moves required to make nums complementary. ", + "category": [ + "Array", + "Hash Table", + "Prefix Sum" + ], + "complexity": "Medium", + "successrate": 37.3, + "totalsubmissions": 15487, + "totalaccepted": 5772, + "likes": 437, + "dislikes": 54, + "hints": "Given a target sum x, each pair of nums[i] and nums[n-1-i] would either need 0, 1, or 2 modifications. Can you find the optimal target sum x value such that the sum of modifications is minimized? Create a difference array to efficiently sum all the modifications.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,2,4,3], limit = 4", + "expected_output": "1", + "explanation": "In 1 move, you can change nums to [1,2,2,3] (underlined elements are changed).\nnums[0] + nums[3] = 1 + 3 = 4.\nnums[1] + nums[2] = 2 + 2 = 4.\nnums[2] + nums[1] = 2 + 2 = 4.\nnums[3] + nums[0] = 3 + 1 = 4.\nTherefore, nums[i] + nums[n-1-i] = 4 for every i, so nums is complementary." + }, + { + "example_num": 2, + "expected_input": "nums = [1,2,2,1], limit = 2", + "expected_output": "2", + "explanation": "In 2 moves, you can change nums to [2,2,2,2]. You cannot change any number to 3 since 3 > limit." + }, + { + "example_num": 3, + "expected_input": "nums = [1,2,1,2], limit = 2", + "expected_output": "0", + "explanation": "nums is already complementary." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e2e", + "questionid": 867, + "title": "Maximum Erasure Value", + "slug": "maximum-erasure-value", + "description": "You are given an array of positive integers nums and want to erase a subarray containing unique elements. The score you get by erasing the subarray is equal to the sum of its elements. Return the maximum score you can get by erasing exactly one subarray. An array b is called to be a subarray of a if it forms a contiguous subsequence of a, that is, if it is equal to a[l],a[l+1],...,a[r] for some (l,r). ", + "category": [ + "Array", + "Hash Table", + "Sliding Window" + ], + "complexity": "Medium", + "successrate": 52.4, + "totalsubmissions": 78337, + "totalaccepted": 41076, + "likes": 823, + "dislikes": 14, + "hints": "The main point here is for the subarray to contain unique elements for each index. Only the first subarrays starting from that index have unique elements. This can be solved using the two pointers technique", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [4,2,4,5,6]", + "expected_output": "17", + "explanation": "The optimal subarray here is [2,4,5,6]." + }, + { + "example_num": 2, + "expected_input": "nums = [5,2,1,2,5,2,1,2,5]", + "expected_output": "8", + "explanation": "The optimal subarray here is [5,2,1] or [1,2,5]." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e2f", + "questionid": 868, + "title": "Jump Game VI", + "slug": "jump-game-vi", + "description": "You are given a 0-indexed integer array nums and an integer k. You are initially standing at index 0. In one move, you can jump at most k steps forward without going outside the boundaries of the array. That is, you can jump from index i to any index in the range [i + 1, min(n - 1, i + k)] inclusive. You want to reach the last index of the array (index n - 1). Your score is the sum of all nums[j] for each index j you visited in the array. Return the maximum score you can get. ", + "category": [ + "Array", + "Dynamic Programming", + "Queue", + "Sliding Window", + "Heap (Priority Queue)", + "Monotonic Queue" + ], + "complexity": "Medium", + "successrate": 42.7, + "totalsubmissions": 99365, + "totalaccepted": 42467, + "likes": 1287, + "dislikes": 51, + "hints": "Let dp[i] be \"the maximum score to reach the end starting at index i\". The answer for dp[i] is nums[i] + max{dp[i+j]} for 1 <= j <= k. That gives an O(n*k) solution. Instead of checking every j for every i, keep track of the largest dp[i] values in a heap and calculate dp[i] from right to left. When the largest value in the heap is out of bounds of the current index, remove it and keep checking.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,-1,-2,4,-7,3], k = 2", + "expected_output": "7", + "explanation": "You can choose your jumps forming the subsequence [1,-1,4,3] (underlined above). The sum is 7." + }, + { + "example_num": 2, + "expected_input": "nums = [10,-5,-2,4,0,3], k = 3", + "expected_output": "17", + "explanation": "You can choose your jumps forming the subsequence [10,4,3] (underlined above). The sum is 17." + }, + { + "example_num": 3, + "expected_input": "nums = [1,-5,-20,4,-1,3,-6,-3], k = 2", + "expected_output": "0", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e31", + "questionid": 870, + "title": "Calculate Money in Leetcode Bank", + "slug": "calculate-money-in-leetcode-bank", + "description": "Hercy wants to save money for his first car. He puts money in the Leetcode bank every day. He starts by putting in $1 on Monday, the first day. Every day from Tuesday to Sunday, he will put in $1 more than the day before. On every subsequent Monday, he will put in $1 more than the previous Monday. Given n, return the total amount of money he will have in the Leetcode bank at the end of the nth day. ", + "category": [ + "Math" + ], + "complexity": "Easy", + "successrate": 64.9, + "totalsubmissions": 44970, + "totalaccepted": 29166, + "likes": 433, + "dislikes": 14, + "hints": "Simulate the process by keeping track of how much money John is putting in and which day of the week it is, and use this information to deduce how much money John will put in the next day.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 4", + "expected_output": "10", + "explanation": " After the 4th day, the total is 1 + 2 + 3 + 4 = 10." + }, + { + "example_num": 2, + "expected_input": "n = 10", + "expected_output": "37", + "explanation": " After the 10th day, the total is (1 + 2 + 3 + 4 + 5 + 6 + 7) + (2 + 3 + 4) = 37. Notice that on the 2nd Monday, Hercy only puts in $2." + }, + { + "example_num": 3, + "expected_input": "n = 20", + "expected_output": "96", + "explanation": " After the 20th day, the total is (1 + 2 + 3 + 4 + 5 + 6 + 7) + (2 + 3 + 4 + 5 + 6 + 7 + 8) + (3 + 4 + 5 + 6 + 7 + 8) = 96." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e36", + "questionid": 875, + "title": "Maximum XOR With an Element From Array", + "slug": "maximum-xor-with-an-element-from-array", + "description": "You are given an array nums consisting of non-negative integers. You are also given a queries array, where queries[i] = [xi, mi]. The answer to the ith query is the maximum bitwise XOR value of xi and any element of nums that does not exceed mi. In other words, the answer is max(nums[j] XOR xi) for all j such that nums[j] <= mi. If all elements in nums are larger than mi, then the answer is -1. Return an integer array answer where answer.length == queries.length and answer[i] is the answer to the ith query. ", + "category": [ + "Array", + "Bit Manipulation", + "Trie" + ], + "complexity": "Hard", + "successrate": 43.2, + "totalsubmissions": 19885, + "totalaccepted": 8589, + "likes": 489, + "dislikes": 15, + "hints": "In problems involving bitwise operations, we often think on the bits level. In this problem, we can think that to maximize the result of an xor operation, we need to maximize the most significant bit, then the next one, and so on. If there's some number in the array that is less than m and whose the most significant bit is different than that of x, then xoring with this number maximizes the most significant bit, so I know this bit in the answer is 1. To check the existence of such numbers and narrow your scope for further bits based on your choice, you can use trie. You can sort the array and the queries, and maintain the trie such that in each query the trie consists exactly of the valid elements.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [0,1,2,3,4], queries = [[3,1],[1,3],[5,6]]", + "expected_output": "[3,3,7]", + "explanation": "1) 0 and 1 are the only two integers not greater than 1. 0 XOR 3 = 3 and 1 XOR 3 = 2. The larger of the two is 3.\n2) 1 XOR 2 = 3.\n3) 5 XOR 2 = 7." + }, + { + "example_num": 2, + "expected_input": "nums = [5,2,4,6,6,3], queries = [[12,4],[8,1],[6,3]]", + "expected_output": "[15,-1,5]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e37", + "questionid": 876, + "title": "Count Good Meals", + "slug": "count-good-meals", + "description": "A good meal is a meal that contains exactly two different food items with a sum of deliciousness equal to a power of two. You can pick any two different foods to make a good meal. Given an array of integers deliciousness where deliciousness[i] is the deliciousness of the ith item of food, return the number of different good meals you can make from this list modulo 109 + 7. Note that items with different indices are considered different even if they have the same deliciousness value. ", + "category": [ + "Array", + "Hash Table" + ], + "complexity": "Medium", + "successrate": 28.2, + "totalsubmissions": 82974, + "totalaccepted": 23396, + "likes": 519, + "dislikes": 188, + "hints": "Note that the number of powers of 2 is at most 21 so this turns the problem to a classic find the number of pairs that sum to a certain value but for 21 values You need to use something fasters than the NlogN approach since there is already the log of iterating over the powers so one idea is two pointers", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "deliciousness = [1,3,5,7,9]", + "expected_output": "4\nExplanation: The good meals are (1,3), (1,7), (3,5) and, (7,9).\nTheir respective sums are 4, 8, 8, and 16, all of which are powers of 2.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "deliciousness = [1,1,1,3,3,3,7]", + "expected_output": "15\nExplanation: The good meals are (1,1) with 3 ways, (1,3) with 9 ways, and (1,7) with 3 ways.", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e38", + "questionid": 877, + "title": "Minimum Operations to Make a Subsequence", + "slug": "minimum-operations-to-make-a-subsequence", + "description": "You are given an array target that consists of distinct integers and another integer array arr that can have duplicates. In one operation, you can insert any integer at any position in arr. For example, if arr = [1,4,1,2], you can add 3 in the middle and make it [1,4,3,1,2]. Note that you can insert the integer at the very beginning or end of the array. Return the minimum number of operations needed to make target a subsequence of arr. A subsequence of an array is a new array generated from the original array by deleting some elements (possibly none) without changing the remaining elements' relative order. For example, [2,7,4] is a subsequence of [4,2,3,7,2,1,4] (the underlined elements), while [2,4,2] is not. ", + "category": [ + "Array", + "Hash Table", + "Binary Search", + "Greedy" + ], + "complexity": "Hard", + "successrate": 48.8, + "totalsubmissions": 14511, + "totalaccepted": 7085, + "likes": 410, + "dislikes": 8, + "hints": "The problem can be reduced to computing Longest Common Subsequence between both arrays. Since one of the arrays has distinct elements, we can consider that these elements describe an arrangement of numbers, and we can replace each element in the other array with the index it appeared at in the first array. Then the problem is converted to finding Longest Increasing Subsequence in the second array, which can be done in O(n log n).", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "target = [5,1,3], arr = [9,4,2,3,4]", + "expected_output": "2", + "explanation": "You can add 5 and 1 in such a way that makes arr = [5,9,4,1,2,3,4], then target will be a subsequence of arr." + }, + { + "example_num": 2, + "expected_input": "target = [6,4,8,1,3,2], arr = [4,7,6,2,3,8,6,1]", + "expected_output": "3", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e3a", + "questionid": 879, + "title": "Decode XORed Permutation", + "slug": "decode-xored-permutation", + "description": "There is an integer array perm that is a permutation of the first n positive integers, where n is always odd. It was encoded into another integer array encoded of length n - 1, such that encoded[i] = perm[i] XOR perm[i + 1]. For example, if perm = [1,3,2], then encoded = [2,1]. Given the encoded array, return the original array perm. It is guaranteed that the answer exists and is unique. ", + "category": [ + "Array", + "Bit Manipulation" + ], + "complexity": "Medium", + "successrate": 60.7, + "totalsubmissions": 14967, + "totalaccepted": 9090, + "likes": 485, + "dislikes": 18, + "hints": "Compute the XOR of the numbers between 1 and n, and think about how it can be used. Let it be x. Think why n is odd. perm[0] = x XOR encoded[1] XOR encoded[3] XOR encoded[5] ... perm[i] = perm[i-1] XOR encoded[i-1]", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "encoded = [3,1]", + "expected_output": "[1,2,3]", + "explanation": "If perm = [1,2,3], then encoded = [1 XOR 2,2 XOR 3] = [3,1]" + }, + { + "example_num": 2, + "expected_input": "encoded = [6,5,4,6]", + "expected_output": "[2,4,1,5,3]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e3b", + "questionid": 880, + "title": "Count Ways to Make Array With Product", + "slug": "count-ways-to-make-array-with-product", + "description": "You are given a 2D integer array, queries. For each queries[i], where queries[i] = [ni, ki], find the number of different ways you can place positive integers into an array of size ni such that the product of the integers is ki. As the number of ways may be too large, the answer to the ith query is the number of ways modulo 109 + 7. Return an integer array answer where answer.length == queries.length, and answer[i] is the answer to the ith query. ", + "category": [ + "Array", + "Math", + "Dynamic Programming" + ], + "complexity": "Hard", + "successrate": 49.5, + "totalsubmissions": 6382, + "totalaccepted": 3160, + "likes": 154, + "dislikes": 25, + "hints": "Prime-factorize ki and count how many ways you can distribute the primes among the ni positions. After prime factorizing ki, suppose there are x amount of prime factor. There are (x + n - 1) choose (n - 1) ways to distribute the x prime factors into k positions, allowing repetitions.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "queries = [[2,6],[5,1],[73,660]]", + "expected_output": "[4,1,50734910]", + "explanation": " Each query is independent.\n[2,6]: There are 4 ways to fill an array of size 2 that multiply to 6: [1,6], [2,3], [3,2], [6,1].\n[5,1]: There is 1 way to fill an array of size 5 that multiply to 1: [1,1,1,1,1].\n[73,660]: There are 1050734917 ways to fill an array of size 73 that multiply to 660. 1050734917 modulo 109 + 7 = 50734910." + }, + { + "example_num": 2, + "expected_input": "queries = [[1,1],[2,2],[3,3],[4,4],[5,5]]", + "expected_output": "[1,2,3,10,5]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e3f", + "questionid": 884, + "title": "Maximum Number of Balls in a Box", + "slug": "maximum-number-of-balls-in-a-box", + "description": "You are working in a ball factory where you have n balls numbered from lowLimit up to highLimit inclusive (i.e., n == highLimit - lowLimit + 1), and an infinite number of boxes numbered from 1 to infinity. Your job at this factory is to put each ball in the box with a number equal to the sum of digits of the ball's number. For example, the ball number 321 will be put in the box number 3 + 2 + 1 = 6 and the ball number 10 will be put in the box number 1 + 0 = 1. Given two integers lowLimit and highLimit, return the number of balls in the box with the most balls. ", + "category": [ + "Hash Table", + "Math", + "Counting" + ], + "complexity": "Easy", + "successrate": 73.7, + "totalsubmissions": 51413, + "totalaccepted": 37887, + "likes": 362, + "dislikes": 85, + "hints": "Note that both lowLimit and highLimit are of small constraints so you can iterate on all nubmer between them You can simulate the boxes by counting for each box the number of balls with digit sum equal to that box number", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "lowLimit = 1, highLimit = 10", + "expected_output": "2", + "explanation": "Box Number: 1 2 3 4 5 6 7 8 9 10 11 ...\nBall Count: 2 1 1 1 1 1 1 1 1 0 0 ...\nBox 1 has the most number of balls with 2 balls." + }, + { + "example_num": 2, + "expected_input": "lowLimit = 5, highLimit = 15", + "expected_output": "2", + "explanation": "Box Number: 1 2 3 4 5 6 7 8 9 10 11 ...\nBall Count: 1 1 1 1 2 2 1 1 1 0 0 ...\nBoxes 5 and 6 have the most number of balls with 2 balls in each." + }, + { + "example_num": 3, + "expected_input": "lowLimit = 19, highLimit = 28", + "expected_output": "2", + "explanation": "Box Number: 1 2 3 4 5 6 7 8 9 10 11 12 ...\nBall Count: 0 1 1 1 1 1 1 1 1 2 0 0 ...\nBox 10 has the most number of balls with 2 balls." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e44", + "questionid": 889, + "title": "Palindrome Partitioning IV", + "slug": "palindrome-partitioning-iv", + "description": "Given a string s, return true if it is possible to split the string s into three non-empty palindromic substrings. Otherwise, return false. A string is said to be palindrome if it the same string when reversed. ", + "category": [ + "String", + "Dynamic Programming" + ], + "complexity": "Hard", + "successrate": 49, + "totalsubmissions": 29581, + "totalaccepted": 14483, + "likes": 485, + "dislikes": 14, + "hints": "Preprocess checking palindromes in O(1) Note that one string is a prefix and another one is a suffix you can try brute forcing the rest", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "abcbdd"", + "expected_output": "true\nExplanation: "abcbdd" = "a" + "bcb" + "dd", and all three substrings are palindromes.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "s = "bcbddxy"", + "expected_output": "false\nExplanation: s cannot be split into 3 palindromes.", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e4a", + "questionid": 895, + "title": "Minimum Changes To Make Alternating Binary String", + "slug": "minimum-changes-to-make-alternating-binary-string", + "description": "You are given a string s consisting only of the characters '0' and '1'. In one operation, you can change any '0' to '1' or vice versa. The string is called alternating if no two adjacent characters are equal. For example, the string \"010\" is alternating, while the string \"0100\" is not. Return the minimum number of operations needed to make s alternating. ", + "category": [ + "String" + ], + "complexity": "Easy", + "successrate": 59.1, + "totalsubmissions": 45138, + "totalaccepted": 26699, + "likes": 397, + "dislikes": 14, + "hints": "Think about how the final string will look like. It will either start with a '0' and be like '010101010..' or with a '1' and be like '10101010..' Try both ways, and check for each way, the number of changes needed to reach it from the given string. The answer is the minimum of both ways.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "0100"", + "expected_output": "1", + "explanation": "If you change the last character to '1', s will be "0101", which is alternating." + }, + { + "example_num": 2, + "expected_input": "s = "10"", + "expected_output": "0", + "explanation": "s is already alternating." + }, + { + "example_num": 3, + "expected_input": "s = "1111"", + "expected_output": "2", + "explanation": "You need two operations to reach "0101" or "1010"." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e10", + "questionid": 837, + "title": "Sort Array by Increasing Frequency", + "slug": "sort-array-by-increasing-frequency", + "description": "Given an array of integers nums, sort the array in increasing order based on the frequency of the values. If multiple values have the same frequency, sort them in decreasing order. Return the sorted array. ", + "category": [ + "Array", + "Hash Table", + "Sorting" + ], + "complexity": "Easy", + "successrate": 68.4, + "totalsubmissions": 84701, + "totalaccepted": 57909, + "likes": 1308, + "dislikes": 50, + "hints": "Count the frequency of each value. Use a custom comparator to compare values by their frequency. If two values have the same frequency, compare their values.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,1,2,2,2,3]", + "expected_output": "[3,1,1,2,2,2]", + "explanation": "'3' has a frequency of 1, '1' has a frequency of 2, and '2' has a frequency of 3." + }, + { + "example_num": 2, + "expected_input": "nums = [2,3,1,3,2]", + "expected_output": "[1,3,3,2,2]", + "explanation": "'2' and '3' both have a frequency of 2, so they are sorted in decreasing order." + }, + { + "example_num": 3, + "expected_input": "nums = [-1,1,-6,4,5,-6,1,4,1]", + "expected_output": "[5,-1,4,4,-6,-6,1,1,1]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e12", + "questionid": 839, + "title": "Count Substrings That Differ by One Character", + "slug": "count-substrings-that-differ-by-one-character", + "description": "Given two strings s and t, find the number of ways you can choose a non-empty substring of s and replace a single character by a different character such that the resulting substring is a substring of t. In other words, find the number of substrings in s that differ from some substring in t by exactly one character. For example, the underlined substrings in \"computer\" and \"computation\" only differ by the 'e'/'a', so this is a valid way. Return the number of substrings that satisfy the condition above. A substring is a contiguous sequence of characters within a string. ", + "category": [ + "Hash Table", + "String", + "Dynamic Programming" + ], + "complexity": "Medium", + "successrate": 71.9, + "totalsubmissions": 23756, + "totalaccepted": 17088, + "likes": 653, + "dislikes": 244, + "hints": "Take every substring of s, change a character, and see how many substrings of t match that substring. Use a Trie to store all substrings of t as a dictionary.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "aba", t = "baba"", + "expected_output": "6", + "explanation": "The following are the pairs of substrings from s and t that differ by exactly 1 character:\n("aba", "baba")\n("aba", "baba")\n("aba", "baba")\n("aba", "baba")\n("aba", "baba")\n("aba", "baba")\nThe underlined portions are the substrings that are chosen from s and t." + }, + { + "example_num": 2, + "expected_input": "s = "ab", t = "bb"", + "expected_output": "3", + "explanation": "The following are the pairs of substrings from s and t that differ by 1 character:\n("ab", "bb")\n("ab", "bb")\n("ab", "bb")\n​​​​The underlined portions are the substrings that are chosen from s and t." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e14", + "questionid": 841, + "title": "Best Team With No Conflicts", + "slug": "best-team-with-no-conflicts", + "description": "You are the manager of a basketball team. For the upcoming tournament, you want to choose the team with the highest overall score. The score of the team is the sum of scores of all the players in the team. However, the basketball team is not allowed to have conflicts. A conflict exists if a younger player has a strictly higher score than an older player. A conflict does not occur between players of the same age. Given two lists, scores and ages, where each scores[i] and ages[i] represents the score and age of the ith player, respectively, return the highest overall score of all possible basketball teams. ", + "category": [ + "Array", + "Dynamic Programming", + "Sorting" + ], + "complexity": "Medium", + "successrate": 40.7, + "totalsubmissions": 44467, + "totalaccepted": 18099, + "likes": 791, + "dislikes": 28, + "hints": "First, sort players by age and break ties by their score. You can now consider the players from left to right. If you choose to include a player, you must only choose players with at least that score later on.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "scores = [1,3,5,10,15], ages = [1,2,3,4,5]", + "expected_output": "34", + "explanation": " You can choose all the players." + }, + { + "example_num": 2, + "expected_input": "scores = [4,5,6,5], ages = [2,1,2,1]", + "expected_output": "16", + "explanation": " It is best to choose the last 3 players. Notice that you are allowed to choose multiple people of the same age." + }, + { + "example_num": 3, + "expected_input": "scores = [1,2,3,5], ages = [8,9,10,1]", + "expected_output": "6", + "explanation": " It is best to choose the first 3 players." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e15", + "questionid": 842, + "title": "Slowest Key", + "slug": "slowest-key", + "description": "A newly designed keypad was tested, where a tester pressed a sequence of n keys, one at a time. You are given a string keysPressed of length n, where keysPressed[i] was the ith key pressed in the testing sequence, and a sorted list releaseTimes, where releaseTimes[i] was the time the ith key was released. Both arrays are 0-indexed. The 0th key was pressed at the time 0, and every subsequent key was pressed at the exact time the previous key was released. The tester wants to know the key of the keypress that had the longest duration. The ith keypress had a duration of releaseTimes[i] - releaseTimes[i - 1], and the 0th keypress had a duration of releaseTimes[0]. Note that the same key could have been pressed multiple times during the test, and these multiple presses of the same key may not have had the same duration. Return the key of the keypress that had the longest duration. If there are multiple such keypresses, return the lexicographically largest key of the keypresses. ", + "category": [ + "Array", + "String" + ], + "complexity": "Easy", + "successrate": 59.6, + "totalsubmissions": 126419, + "totalaccepted": 75374, + "likes": 521, + "dislikes": 85, + "hints": "Get for each press its key and amount of time taken. Iterate on the presses, maintaining the answer so far. The current press will change the answer if and only if its amount of time taken is longer than that of the previous answer, or they are equal but the key is larger than that of the previous answer.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "releaseTimes = [9,29,49,50], keysPressed = "cbcd"", + "expected_output": ""c"", + "explanation": "The keypresses were as follows:\nKeypress for 'c' had a duration of 9 (pressed at time 0 and released at time 9).\nKeypress for 'b' had a duration of 29 - 9 = 20 (pressed at time 9 right after the release of the previous character and released at time 29).\nKeypress for 'c' had a duration of 49 - 29 = 20 (pressed at time 29 right after the release of the previous character and released at time 49).\nKeypress for 'd' had a duration of 50 - 49 = 1 (pressed at time 49 right after the release of the previous character and released at time 50).\nThe longest of these was the keypress for 'b' and the second keypress for 'c', both with duration 20.\n'c' is lexicographically larger than 'b', so the answer is 'c'." + }, + { + "example_num": 2, + "expected_input": "releaseTimes = [12,23,36,46,62], keysPressed = "spuda"", + "expected_output": ""a"", + "explanation": "The keypresses were as follows:\nKeypress for 's' had a duration of 12.\nKeypress for 'p' had a duration of 23 - 12 = 11.\nKeypress for 'u' had a duration of 36 - 23 = 13.\nKeypress for 'd' had a duration of 46 - 36 = 10.\nKeypress for 'a' had a duration of 62 - 46 = 16.\nThe longest of these was the keypress for 'a' with duration 16." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e17", + "questionid": 844, + "title": "Defuse the Bomb", + "slug": "defuse-the-bomb", + "description": "You have a bomb to defuse, and your time is running out! Your informer will provide you with a circular array code of length of n and a key k. To decrypt the code, you must replace every number. All the numbers are replaced simultaneously. As code is circular, the next element of code[n-1] is code[0], and the previous element of code[0] is code[n-1]. Given the circular array code and an integer key k, return the decrypted code to defuse the bomb! ", + "category": [ + "Array" + ], + "complexity": "Easy", + "successrate": 60.8, + "totalsubmissions": 37170, + "totalaccepted": 22582, + "likes": 414, + "dislikes": 45, + "hints": "As the array is circular, use modulo to find the correct index. The constraints are low enough for a brute-force solution.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "code = [5,7,1,4], k = 3", + "expected_output": "[12,10,16,13]", + "explanation": "Each number is replaced by the sum of the next 3 numbers. The decrypted code is [7+1+4, 1+4+5, 4+5+7, 5+7+1]. Notice that the numbers wrap around." + }, + { + "example_num": 2, + "expected_input": "code = [1,2,3,4], k = 0", + "expected_output": "[0,0,0,0]", + "explanation": "When k is zero, the numbers are replaced by 0." + }, + { + "example_num": 3, + "expected_input": "code = [2,4,9,3], k = -2", + "expected_output": "[12,5,6,13]", + "explanation": "The decrypted code is [3+9, 2+3, 4+2, 9+4]. Notice that the numbers wrap around again. If k is negative, the sum is of the previous numbers." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e1f", + "questionid": 852, + "title": "Minimum Operations to Reduce X to Zero", + "slug": "minimum-operations-to-reduce-x-to-zero", + "description": "You are given an integer array nums and an integer x. In one operation, you can either remove the leftmost or the rightmost element from the array nums and subtract its value from x. Note that this modifies the array for future operations. Return the minimum number of operations to reduce x to exactly 0 if it is possible, otherwise, return -1. ", + "category": [ + "Array", + "Hash Table", + "Binary Search", + "Sliding Window", + "Prefix Sum" + ], + "complexity": "Medium", + "successrate": 33.5, + "totalsubmissions": 136320, + "totalaccepted": 45728, + "likes": 1552, + "dislikes": 28, + "hints": "Think in reverse; instead of finding the minimum prefix + suffix, find the maximum subarray. Finding the maximum subarray is standard and can be done greedily.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,1,4,2,3], x = 5", + "expected_output": "2", + "explanation": "The optimal solution is to remove the last two elements to reduce x to zero." + }, + { + "example_num": 2, + "expected_input": "nums = [5,6,7,8,9], x = 4", + "expected_output": "-1", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "nums = [3,2,20,1,1,3], x = 10", + "expected_output": "5", + "explanation": "The optimal solution is to remove the last three elements and the first two elements (5 operations in total) to reduce x to zero." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e20", + "questionid": 853, + "title": "Check If Two String Arrays are Equivalent", + "slug": "check-if-two-string-arrays-are-equivalent", + "description": "Given two string arrays word1 and word2, return true if the two arrays represent the same string, and false otherwise. A string is represented by an array if the array elements concatenated in order forms the string. ", + "category": [ + "Array", + "String" + ], + "complexity": "Easy", + "successrate": 82, + "totalsubmissions": 169765, + "totalaccepted": 139123, + "likes": 764, + "dislikes": 109, + "hints": "Concatenate all strings in the first array into a single string in the given order, the same for the second array. Both arrays represent the same string if and only if the generated strings are the same.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "word1 = ["ab", "c"], word2 = ["a", "bc"]", + "expected_output": "true", + "explanation": "word1 represents string "ab" + "c" -> "abc"\nword2 represents string "a" + "bc" -> "abc"\nThe strings are the same, so return true." + }, + { + "example_num": 2, + "expected_input": "word1 = ["a", "cb"], word2 = ["ab", "c"]", + "expected_output": "false", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "word1 = ["abc", "d", "defg"], word2 = ["abcddefg"]", + "expected_output": "true", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e28", + "questionid": 861, + "title": "Max Number of K-Sum Pairs", + "slug": "max-number-of-k-sum-pairs", + "description": "You are given an integer array nums and an integer k. In one operation, you can pick two numbers from the array whose sum equals k and remove them from the array. Return the maximum number of operations you can perform on the array. ", + "category": [ + "Array", + "Hash Table", + "Two Pointers", + "Sorting" + ], + "complexity": "Medium", + "successrate": 53.6, + "totalsubmissions": 95121, + "totalaccepted": 50972, + "likes": 689, + "dislikes": 25, + "hints": "The abstract problem asks to count the number of disjoint pairs with a given sum k. For each possible value x, it can be paired up with k - x. The number of such pairs equals to min(count(x), count(k-x)), unless that x = k / 2, where the number of such pairs will be floor(count(x) / 2).", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,2,3,4], k = 5", + "expected_output": "2", + "explanation": "Starting with nums = [1,2,3,4]:\n- Remove numbers 1 and 4, then nums = [2,3]\n- Remove numbers 2 and 3, then nums = []\nThere are no more pairs that sum up to 5, hence a total of 2 operations." + }, + { + "example_num": 2, + "expected_input": "nums = [3,1,3,4,3], k = 6", + "expected_output": "1", + "explanation": "Starting with nums = [3,1,3,4,3]:\n- Remove the first two 3's, then nums = [1,4,3]\nThere are no more pairs that sum up to 6, hence a total of 1 operation." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e29", + "questionid": 862, + "title": "Minimum Incompatibility", + "slug": "minimum-incompatibility", + "description": "You are given an integer array nums and an integer k. You are asked to distribute this array into k subsets of equal size such that there are no two equal elements in the same subset. A subset's incompatibility is the difference between the maximum and minimum elements in that array. Return the minimum possible sum of incompatibilities of the k subsets after distributing the array optimally, or return -1 if it is not possible. A subset is a group integers that appear in the array with no particular order. ", + "category": [ + "Array", + "Dynamic Programming", + "Bit Manipulation", + "Bitmask" + ], + "complexity": "Hard", + "successrate": 37, + "totalsubmissions": 15608, + "totalaccepted": 5769, + "likes": 177, + "dislikes": 81, + "hints": "The constraints are small enough for a backtrack solution but not any backtrack solution If we use a naive n^k don't you think it can be optimized", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,2,1,4], k = 2", + "expected_output": "4", + "explanation": "The optimal distribution of subsets is [1,2] and [1,4].\nThe incompatibility is (2-1) + (4-1) = 4.\nNote that [1,1] and [2,4] would result in a smaller sum, but the first subset contains 2 equal elements." + }, + { + "example_num": 2, + "expected_input": "nums = [6,3,8,1,3,1,2,2], k = 4", + "expected_output": "6", + "explanation": "The optimal distribution of subsets is [1,2], [2,3], [6,8], and [1,3].\nThe incompatibility is (2-1) + (3-2) + (8-6) + (3-1) = 6." + }, + { + "example_num": 3, + "expected_input": "nums = [5,3,3,6,3,3], k = 3", + "expected_output": "-1", + "explanation": "It is impossible to distribute nums into 3 subsets where no two elements are equal in the same subset." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e2b", + "questionid": 864, + "title": "Minimum Adjacent Swaps for K Consecutive Ones", + "slug": "minimum-adjacent-swaps-for-k-consecutive-ones", + "description": "You are given an integer array, nums, and an integer k. nums comprises of only 0's and 1's. In one move, you can choose two adjacent indices and swap their values. Return the minimum number of moves required so that nums has k consecutive 1's. ", + "category": [ + "Array", + "Greedy", + "Sliding Window", + "Prefix Sum" + ], + "complexity": "Hard", + "successrate": 40.7, + "totalsubmissions": 14315, + "totalaccepted": 5824, + "likes": 419, + "dislikes": 16, + "hints": "Choose k 1s and determine how many steps are required to move them into 1 group. Maintain a sliding window of k 1s, and maintain the steps required to group them. When you slide the window across, should you move the group to the right? Once you move the group to the right, it will never need to slide to the left again.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,0,0,1,0,1], k = 2", + "expected_output": "1", + "explanation": "In 1 move, nums could be [1,0,0,0,1,1] and have 2 consecutive 1's." + }, + { + "example_num": 2, + "expected_input": "nums = [1,0,0,0,0,0,1,1], k = 3", + "expected_output": "5", + "explanation": "In 5 moves, the leftmost 1 can be shifted right until nums = [0,0,0,0,0,1,1,1]." + }, + { + "example_num": 3, + "expected_input": "nums = [1,1,0,1], k = 2", + "expected_output": "0", + "explanation": "nums already has 2 consecutive 1's." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e2d", + "questionid": 866, + "title": "Stone Game VII", + "slug": "stone-game-vii", + "description": "Alice and Bob take turns playing a game, with Alice starting first. There are n stones arranged in a row. On each player's turn, they can remove either the leftmost stone or the rightmost stone from the row and receive points equal to the sum of the remaining stones' values in the row. The winner is the one with the higher score when there are no stones left to remove. Bob found that he will always lose this game (poor Bob, he always loses), so he decided to minimize the score's difference. Alice's goal is to maximize the difference in the score. Given an array of integers stones where stones[i] represents the value of the ith stone from the left, return the difference in Alice and Bob's score if they both play optimally. ", + "category": [ + "Array", + "Math", + "Dynamic Programming", + "Game Theory" + ], + "complexity": "Medium", + "successrate": 58.7, + "totalsubmissions": 44395, + "totalaccepted": 26039, + "likes": 651, + "dislikes": 124, + "hints": "The constraints are small enough for an N^2 solution. Try using dynamic programming.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "stones = [5,3,1,4,2]", + "expected_output": "6", + "explanation": "- Alice removes 2 and gets 5 + 3 + 1 + 4 = 13 points. Alice = 13, Bob = 0, stones = [5,3,1,4].\n- Bob removes 5 and gets 3 + 1 + 4 = 8 points. Alice = 13, Bob = 8, stones = [3,1,4].\n- Alice removes 3 and gets 1 + 4 = 5 points. Alice = 18, Bob = 8, stones = [1,4].\n- Bob removes 1 and gets 4 points. Alice = 18, Bob = 12, stones = [4].\n- Alice removes 4 and gets 0 points. Alice = 18, Bob = 12, stones = [].\nThe score difference is 18 - 12 = 6." + }, + { + "example_num": 2, + "expected_input": "stones = [7,90,5,1,100,10,10,2]", + "expected_output": "122", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e41", + "questionid": 886, + "title": "Sum of Unique Elements", + "slug": "sum-of-unique-elements", + "description": "You are given an integer array nums. The unique elements of an array are the elements that appear exactly once in the array. Return the sum of all the unique elements of nums. ", + "category": [ + "Array", + "Hash Table", + "Counting" + ], + "complexity": "Easy", + "successrate": 75.5, + "totalsubmissions": 96539, + "totalaccepted": 72919, + "likes": 721, + "dislikes": 17, + "hints": "Use a dictionary to count the frequency of each number.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,2,3,2]", + "expected_output": "4", + "explanation": "The unique elements are [1,3], and the sum is 4." + }, + { + "example_num": 2, + "expected_input": "nums = [1,1,1,1,1]", + "expected_output": "0", + "explanation": "There are no unique elements, and the sum is 0." + }, + { + "example_num": 3, + "expected_input": "nums = [1,2,3,4,5]", + "expected_output": "15", + "explanation": "The unique elements are [1,2,3,4,5], and the sum is 15." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e45", + "questionid": 890, + "title": "Longest Nice Substring", + "slug": "longest-nice-substring", + "description": "A string s is nice if, for every letter of the alphabet that s contains, it appears both in uppercase and lowercase. For example, \"abABB\" is nice because 'A' and 'a' appear, and 'B' and 'b' appear. However, \"abA\" is not because 'b' appears, but 'B' does not. Given a string s, return the longest substring of s that is nice. If there are multiple, return the substring of the earliest occurrence. If there are none, return an empty string. ", + "category": [ + "Hash Table", + "String", + "Bit Manipulation", + "Sliding Window" + ], + "complexity": "Easy", + "successrate": 61.9, + "totalsubmissions": 36825, + "totalaccepted": 22808, + "likes": 561, + "dislikes": 432, + "hints": "Brute force and check each substring to see if it is nice.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "YazaAay"", + "expected_output": ""aAa"\nExplanation: "aAa" is a nice string because 'A/a' is the only letter of the alphabet in s, and both 'A' and 'a' appear.\n"aAa" is the longest nice substring.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "s = "Bb"", + "expected_output": ""Bb"", + "explanation": ""Bb" is a nice string because both 'B' and 'b' appear. The whole string is a substring." + }, + { + "example_num": 3, + "expected_input": "s = "c"", + "expected_output": """", + "explanation": "There are no nice substrings." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e49", + "questionid": 894, + "title": "Closest Subsequence Sum", + "slug": "closest-subsequence-sum", + "description": "You are given an integer array nums and an integer goal. You want to choose a subsequence of nums such that the sum of its elements is the closest possible to goal. That is, if the sum of the subsequence's elements is sum, then you want to minimize the absolute difference abs(sum - goal). Return the minimum possible value of abs(sum - goal). Note that a subsequence of an array is an array formed by removing some elements (possibly all or none) of the original array. ", + "category": [ + "Array", + "Two Pointers", + "Dynamic Programming", + "Bit Manipulation", + "Bitmask" + ], + "complexity": "Hard", + "successrate": 36.3, + "totalsubmissions": 23471, + "totalaccepted": 8525, + "likes": 436, + "dislikes": 58, + "hints": "The naive solution is to check all possible subsequences. This works in O(2^n). Divide the array into two parts of nearly is equal size. Consider all subsets of one part and make a list of all possible subset sums and sort this list. Consider all subsets of the other part, and for each one, let its sum = x, do binary search to get the nearest possible value to goal - x in the first part.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [5,-7,3,5], goal = 6", + "expected_output": "0", + "explanation": "Choose the whole array as a subsequence, with a sum of 6.\nThis is equal to the goal, so the absolute difference is 0." + }, + { + "example_num": 2, + "expected_input": "nums = [7,-9,15,-2], goal = -5", + "expected_output": "1", + "explanation": "Choose the subsequence [7,-9,-2], with a sum of -4.\nThe absolute difference is abs(-4 - (-5)) = abs(1) = 1, which is the minimum." + }, + { + "example_num": 3, + "expected_input": "nums = [1,2,3], goal = -7", + "expected_output": "7", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e0e", + "questionid": 835, + "title": "Maximal Network Rank", + "slug": "maximal-network-rank", + "description": "There is an infrastructure of n cities with some number of roads connecting these cities. Each roads[i] = [ai, bi] indicates that there is a bidirectional road between cities ai and bi. The network rank of two different cities is defined as the total number of directly connected roads to either city. If a road is directly connected to both cities, it is only counted once. The maximal network rank of the infrastructure is the maximum network rank of all pairs of different cities. Given the integer n and the array roads, return the maximal network rank of the entire infrastructure. ", + "category": [ + "Graph" + ], + "complexity": "Medium", + "successrate": 56.8, + "totalsubmissions": 66604, + "totalaccepted": 37798, + "likes": 645, + "dislikes": 123, + "hints": "Try every pair of different cities and calculate its network rank. The network rank of two vertices is almost the sum of their degrees. How can you efficiently check if there is a road connecting two different cities?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 4, roads = [[0,1],[0,3],[1,2],[1,3]]", + "expected_output": "4", + "explanation": "The network rank of cities 0 and 1 is 4 as there are 4 roads that are connected to either 0 or 1. The road between 0 and 1 is only counted once." + }, + { + "example_num": 2, + "expected_input": "n = 5, roads = [[0,1],[0,3],[1,2],[1,3],[2,3],[2,4]]", + "expected_output": "5", + "explanation": "There are 5 roads that are connected to cities 1 or 2." + }, + { + "example_num": 3, + "expected_input": "n = 8, roads = [[0,1],[1,2],[2,3],[2,4],[5,6],[5,7]]", + "expected_output": "5", + "explanation": "The network rank of 2 and 5 is 5. Notice that all the cities do not have to be connected." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e1b", + "questionid": 848, + "title": "Furthest Building You Can Reach", + "slug": "furthest-building-you-can-reach", + "description": "You are given an integer array heights representing the heights of buildings, some bricks, and some ladders. You start your journey from building 0 and move to the next building by possibly using bricks or ladders. While moving from building i to building i+1 (0-indexed), Return the furthest building index (0-indexed) you can reach if you use the given ladders and bricks optimally. ", + "category": [ + "Array", + "Greedy", + "Heap (Priority Queue)" + ], + "complexity": "Medium", + "successrate": 45, + "totalsubmissions": 104786, + "totalaccepted": 47206, + "likes": 1634, + "dislikes": 49, + "hints": "Assume the problem is to check whether you can reach the last building or not. You'll have to do a set of jumps, and choose for each one whether to do it using a ladder or bricks. It's always optimal to use ladders in the largest jumps. Iterate on the buildings, maintaining the largest r jumps and the sum of the remaining ones so far, and stop whenever this sum exceeds b.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "heights = [4,2,7,6,9,14,12], bricks = 5, ladders = 1", + "expected_output": "4", + "explanation": "Starting at building 0, you can follow these steps:\n- Go to building 1 without using ladders nor bricks since 4 >= 2.\n- Go to building 2 using 5 bricks. You must use either bricks or ladders because 2 < 7.\n- Go to building 3 without using ladders nor bricks since 7 >= 6.\n- Go to building 4 using your only ladder. You must use either bricks or ladders because 6 < 9.\nIt is impossible to go beyond building 4 because you do not have any more bricks or ladders." + }, + { + "example_num": 2, + "expected_input": "heights = [4,12,2,7,3,18,20,3,19], bricks = 10, ladders = 2", + "expected_output": "7", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "heights = [14,3,19,3], bricks = 17, ladders = 0", + "expected_output": "3", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e1c", + "questionid": 849, + "title": "Maximum Repeating Substring", + "slug": "maximum-repeating-substring", + "description": "For a string sequence, a string word is k-repeating if word concatenated k times is a substring of sequence. The word's maximum k-repeating value is the highest value k where word is k-repeating in sequence. If word is not a substring of sequence, word's maximum k-repeating value is 0. Given strings sequence and word, return the maximum k-repeating value of word in sequence. ", + "category": [ + "String", + "String Matching" + ], + "complexity": "Easy", + "successrate": 39.6, + "totalsubmissions": 59819, + "totalaccepted": 23687, + "likes": 368, + "dislikes": 125, + "hints": "The constraints are low enough for a brute force approach. Try every k value from 0 upwards until word is no longer k-repeating.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "sequence = "ababc", word = "ab"", + "expected_output": "2\nExplanation: "abab" is a substring in "ababc".", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "sequence = "ababc", word = "ba"", + "expected_output": "1\nExplanation: "ba" is a substring in "ababc". "baba" is not a substring in "ababc".", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "sequence = "ababc", word = "ac"", + "expected_output": "0\nExplanation: "ac" is not a substring in "ababc".", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e23", + "questionid": 856, + "title": "Sum of Absolute Differences in a Sorted Array", + "slug": "sum-of-absolute-differences-in-a-sorted-array", + "description": "You are given an integer array nums sorted in non-decreasing order. Build and return an integer array result with the same length as nums such that result[i] is equal to the summation of absolute differences between nums[i] and all the other elements in the array. In other words, result[i] is equal to sum(|nums[i]-nums[j]|) where 0 <= j < nums.length and j != i (0-indexed). ", + "category": [ + "Array", + "Math", + "Prefix Sum" + ], + "complexity": "Medium", + "successrate": 65.6, + "totalsubmissions": 29678, + "totalaccepted": 19461, + "likes": 673, + "dislikes": 22, + "hints": "Absolute difference is the same as max(a, b) - min(a, b). How can you use this fact with the fact that the array is sorted? For nums[i], the answer is (nums[i] - nums[0]) + (nums[i] - nums[1]) + ... + (nums[i] - nums[i-1]) + (nums[i+1] - nums[i]) + (nums[i+2] - nums[i]) + ... + (nums[n-1] - nums[i]). It can be simplified to (nums[i] * i - (nums[0] + nums[1] + ... + nums[i-1])) + ((nums[i+1] + nums[i+2] + ... + nums[n-1]) - nums[i] * (n-i-1)). One can build prefix and suffix sums to compute this quickly.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [2,3,5]", + "expected_output": "[4,3,5]", + "explanation": "Assuming the arrays are 0-indexed, then\nresult[0] = |2-2| + |2-3| + |2-5| = 0 + 1 + 3 = 4,\nresult[1] = |3-2| + |3-3| + |3-5| = 1 + 0 + 2 = 3,\nresult[2] = |5-2| + |5-3| + |5-5| = 3 + 2 + 0 = 5." + }, + { + "example_num": 2, + "expected_input": "nums = [1,4,6,8,10]", + "expected_output": "[24,15,13,15,21]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e25", + "questionid": 858, + "title": "Find the Most Competitive Subsequence", + "slug": "find-the-most-competitive-subsequence", + "description": "Given an integer array nums and a positive integer k, return the most competitive subsequence of nums of size k. An array's subsequence is a resulting sequence obtained by erasing some (possibly zero) elements from the array. We define that a subsequence a is more competitive than a subsequence b (of the same length) if in the first position where a and b differ, subsequence a has a number less than the corresponding number in b. For example, [1,3,4] is more competitive than [1,3,5] because the first position they differ is at the final number, and 4 is less than 5. ", + "category": [ + "Array", + "Stack", + "Greedy", + "Monotonic Stack" + ], + "complexity": "Medium", + "successrate": 48.4, + "totalsubmissions": 86550, + "totalaccepted": 41852, + "likes": 1258, + "dislikes": 59, + "hints": "In lexicographical order, the elements to the left have higher priority than those that come after. Can you think of a strategy that incrementally builds the answer from left to right?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [3,5,2,6], k = 2", + "expected_output": "[2,6]", + "explanation": "Among the set of every possible subsequence: {[3,5], [3,2], [3,6], [5,2], [5,6], [2,6]}, [2,6] is the most competitive." + }, + { + "example_num": 2, + "expected_input": "nums = [2,4,3,3,5,4,9,6], k = 4", + "expected_output": "[2,3,3,4]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e27", + "questionid": 860, + "title": "Goal Parser Interpretation", + "slug": "goal-parser-interpretation", + "description": "You own a Goal Parser that can interpret a string command. The command consists of an alphabet of \"G\", \"()\" and/or \"(al)\" in some order. The Goal Parser will interpret \"G\" as the string \"G\", \"()\" as the string \"o\", and \"(al)\" as the string \"al\". The interpreted strings are then concatenated in the original order. Given the string command, return the Goal Parser's interpretation of command. ", + "category": [ + "String" + ], + "complexity": "Easy", + "successrate": 85.7, + "totalsubmissions": 120299, + "totalaccepted": 103140, + "likes": 676, + "dislikes": 61, + "hints": "You need to check at most 2 characters to determine which character comes next.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "command = "G()(al)"", + "expected_output": ""Goal"", + "explanation": " The Goal Parser interprets the command as follows:\nG -> G\n() -> o\n(al) -> al\nThe final concatenated result is "Goal"." + }, + { + "example_num": 2, + "expected_input": "command = "G()()()()(al)"", + "expected_output": ""Gooooal"", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "command = "(al)G(al)()()G"", + "expected_output": ""alGalooG"", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e2a", + "questionid": 863, + "title": "Concatenation of Consecutive Binary Numbers", + "slug": "concatenation-of-consecutive-binary-numbers", + "description": "Given an integer n, return the decimal value of the binary string formed by concatenating the binary representations of 1 to n in order, modulo 109 + 7. ", + "category": [ + "Math", + "Bit Manipulation", + "Simulation" + ], + "complexity": "Medium", + "successrate": 52.6, + "totalsubmissions": 64004, + "totalaccepted": 33637, + "likes": 338, + "dislikes": 206, + "hints": "Express the nth number value in a recursion formula and think about how we can do a fast evaluation.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 1", + "expected_output": "1\nExplanation: "1" in binary corresponds to the decimal value 1.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "n = 3", + "expected_output": "27\nExplanation: In binary, 1, 2, and 3 corresponds to "1", "10", and "11".\nAfter concatenating them, we have "11011", which corresponds to the decimal value 27.", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "n = 12", + "expected_output": "505379714\nExplanation: The concatenation results in "1101110010111011110001001101010111100".\nThe decimal value of that is 118505380540.\nAfter modulo 109 + 7, the result is 505379714.", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e30", + "questionid": 869, + "title": "Checking Existence of Edge Length Limited Paths", + "slug": "checking-existence-of-edge-length-limited-paths", + "description": "An undirected graph of n nodes is defined by edgeList, where edgeList[i] = [ui, vi, disi] denotes an edge between nodes ui and vi with distance disi. Note that there may be multiple edges between two nodes. Given an array queries, where queries[j] = [pj, qj, limitj], your task is to determine for each queries[j] whether there is a path between pj and qj such that each edge on the path has a distance strictly less than limitj . Return a boolean array answer, where answer.length == queries.length and the jth value of answer is true if there is a path for queries[j] is true, and false otherwise. ", + "category": [ + "Array", + "Union Find", + "Graph", + "Sorting" + ], + "complexity": "Hard", + "successrate": 48.7, + "totalsubmissions": 15985, + "totalaccepted": 7788, + "likes": 444, + "dislikes": 9, + "hints": "All the queries are given in advance. Is there a way you can reorder the queries to avoid repeated computations?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 3, edgeList = [[0,1,2],[1,2,4],[2,0,8],[1,0,16]], queries = [[0,1,2],[0,2,5]]", + "expected_output": "[false,true]", + "explanation": "The above figure shows the given graph. Note that there are two overlapping edges between 0 and 1 with distances 2 and 16.\nFor the first query, between 0 and 1 there is no path where each distance is less than 2, thus we return false for this query.\nFor the second query, there is a path (0 -> 1 -> 2) of two edges with distances less than 5, thus we return true for this query." + }, + { + "example_num": 2, + "expected_input": "n = 5, edgeList = [[0,1,10],[1,2,5],[2,3,9],[3,4,13]], queries = [[0,4,14],[1,4,13]]", + "expected_output": "[true,false]", + "explanation": "The above figure shows the given graph." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e32", + "questionid": 871, + "title": "Maximum Score From Removing Substrings", + "slug": "maximum-score-from-removing-substrings", + "description": "You are given a string s and two integers x and y. You can perform two types of operations any number of times. Return the maximum points you can gain after applying the above operations on s. ", + "category": [ + "String", + "Stack", + "Greedy" + ], + "complexity": "Medium", + "successrate": 44.9, + "totalsubmissions": 20889, + "totalaccepted": 9371, + "likes": 394, + "dislikes": 18, + "hints": "Note that it is always more optimal to take one type of substring before another You can use a stack to handle erasures", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "cdbcbbaaabab", x = 4, y = 5", + "expected_output": "19", + "explanation": "- Remove the "ba" underlined in "cdbcbbaaabab". Now, s = "cdbcbbaaab" and 5 points are added to the score.\n- Remove the "ab" underlined in "cdbcbbaaab". Now, s = "cdbcbbaa" and 4 points are added to the score.\n- Remove the "ba" underlined in "cdbcbbaa". Now, s = "cdbcba" and 5 points are added to the score.\n- Remove the "ba" underlined in "cdbcba". Now, s = "cdbc" and 5 points are added to the score.\nTotal score = 5 + 4 + 5 + 5 = 19." + }, + { + "example_num": 2, + "expected_input": "s = "aabbaaxybbaabb", x = 5, y = 4", + "expected_output": "20", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e33", + "questionid": 872, + "title": "Determine if String Halves Are Alike", + "slug": "determine-if-string-halves-are-alike", + "description": "You are given a string s of even length. Split this string into two halves of equal lengths, and let a be the first half and b be the second half. Two strings are alike if they have the same number of vowels ('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'). Notice that s contains uppercase and lowercase letters. Return true if a and b are alike. Otherwise, return false. ", + "category": [ + "String", + "Counting" + ], + "complexity": "Easy", + "successrate": 78.1, + "totalsubmissions": 106734, + "totalaccepted": 83321, + "likes": 509, + "dislikes": 35, + "hints": "Create a function that checks if a character is a vowel, either uppercase or lowercase.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "book"", + "expected_output": "true", + "explanation": "a = "bo" and b = "ok". a has 1 vowel and b has 1 vowel. Therefore, they are alike." + }, + { + "example_num": 2, + "expected_input": "s = "textbook"", + "expected_output": "false", + "explanation": "a = "text" and b = "book". a has 1 vowel whereas b has 2. Therefore, they are not alike.\nNotice that the vowel o is counted twice." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e35", + "questionid": 874, + "title": "Find Minimum Time to Finish All Jobs", + "slug": "find-minimum-time-to-finish-all-jobs", + "description": "You are given an integer array jobs, where jobs[i] is the amount of time it takes to complete the ith job. There are k workers that you can assign jobs to. Each job should be assigned to exactly one worker. The working time of a worker is the sum of the time it takes to complete all jobs assigned to them. Your goal is to devise an optimal assignment such that the maximum working time of any worker is minimized. Return the minimum possible maximum working time of any assignment. ", + "category": [ + "Array", + "Dynamic Programming", + "Backtracking", + "Bit Manipulation", + "Bitmask" + ], + "complexity": "Hard", + "successrate": 42.9, + "totalsubmissions": 32104, + "totalaccepted": 13776, + "likes": 491, + "dislikes": 14, + "hints": "We can select a subset of tasks and assign it to a worker then solve the subproblem on the remaining tasks", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "jobs = [3,2,3], k = 3", + "expected_output": "3", + "explanation": "By assigning each person one job, the maximum time is 3." + }, + { + "example_num": 2, + "expected_input": "jobs = [1,2,4,7,8], k = 2", + "expected_output": "11", + "explanation": "Assign the jobs the following way:\nWorker 1: 1, 2, 8 (working time = 1 + 2 + 8 = 11)\nWorker 2: 4, 7 (working time = 4 + 7 = 11)\nThe maximum working time is 11." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e39", + "questionid": 878, + "title": "Find the Highest Altitude", + "slug": "find-the-highest-altitude", + "description": "There is a biker going on a road trip. The road trip consists of n + 1 points at different altitudes. The biker starts his trip on point 0 with altitude equal 0. You are given an integer array gain of length n where gain[i] is the net gain in altitude between points i and i + 1 for all (0 <= i < n). Return the highest altitude of a point. ", + "category": [ + "Array", + "Prefix Sum" + ], + "complexity": "Easy", + "successrate": 78.9, + "totalsubmissions": 88185, + "totalaccepted": 69592, + "likes": 762, + "dislikes": 78, + "hints": "Let's note that the altitude of an element is the sum of gains of all the elements behind it Getting the altitudes can be done by getting the prefix sum array of the given array", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "gain = [-5,1,5,0,-7]", + "expected_output": "1", + "explanation": "The altitudes are [0,-5,-4,1,1,-6]. The highest is 1." + }, + { + "example_num": 2, + "expected_input": "gain = [-4,-3,-2,-1,4,3,2]", + "expected_output": "0", + "explanation": "The altitudes are [0,-4,-7,-9,-10,-6,-3,-1]. The highest is 0." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e3c", + "questionid": 881, + "title": "Decode XORed Array", + "slug": "decode-xored-array", + "description": "There is a hidden integer array arr that consists of n non-negative integers. It was encoded into another integer array encoded of length n - 1, such that encoded[i] = arr[i] XOR arr[i + 1]. For example, if arr = [1,0,2,1], then encoded = [1,2,3]. You are given the encoded array. You are also given an integer first, that is the first element of arr, i.e. arr[0]. Return the original array arr. It can be proved that the answer exists and is unique. ", + "category": [ + "Array", + "Bit Manipulation" + ], + "complexity": "Easy", + "successrate": 85.9, + "totalsubmissions": 79325, + "totalaccepted": 68161, + "likes": 723, + "dislikes": 134, + "hints": "Since that encoded[i] = arr[i] XOR arr[i+1], then arr[i+1] = encoded[i] XOR arr[i]. Iterate on i from beginning to end, and set arr[i+1] = encoded[i] XOR arr[i].", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "encoded = [1,2,3], first = 1", + "expected_output": "[1,0,2,1]", + "explanation": "If arr = [1,0,2,1], then first = 1 and encoded = [1 XOR 0, 0 XOR 2, 2 XOR 1] = [1,2,3]" + }, + { + "example_num": 2, + "expected_input": "encoded = [6,2,7,3], first = 4", + "expected_output": "[4,2,0,7,4]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e40", + "questionid": 885, + "title": "Largest Submatrix With Rearrangements", + "slug": "largest-submatrix-with-rearrangements", + "description": "You are given a binary matrix matrix of size m x n, and you are allowed to rearrange the columns of the matrix in any order. Return the area of the largest submatrix within matrix where every element of the submatrix is 1 after reordering the columns optimally. ", + "category": [ + "Array", + "Greedy", + "Sorting", + "Matrix" + ], + "complexity": "Medium", + "successrate": 60.4, + "totalsubmissions": 19339, + "totalaccepted": 11682, + "likes": 641, + "dislikes": 16, + "hints": "For each column, find the number of consecutive ones ending at each position. For each row, sort the cumulative ones in non-increasing order and \"fit\" the largest submatrix.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "matrix = [[0,0,1],[1,1,1],[1,0,1]]", + "expected_output": "4", + "explanation": "You can rearrange the columns as shown above.\nThe largest submatrix of 1s, in bold, has an area of 4." + }, + { + "example_num": 2, + "expected_input": "matrix = [[1,0,1,0,1]]", + "expected_output": "3", + "explanation": "You can rearrange the columns as shown above.\nThe largest submatrix of 1s, in bold, has an area of 3." + }, + { + "example_num": 3, + "expected_input": "matrix = [[1,1,0],[1,0,1]]", + "expected_output": "2", + "explanation": "Notice that you must rearrange entire columns, and there is no way to make a submatrix of 1s larger than an area of 2." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e42", + "questionid": 887, + "title": "Find Kth Largest XOR Coordinate Value", + "slug": "find-kth-largest-xor-coordinate-value", + "description": "You are given a 2D matrix of size m x n, consisting of non-negative integers. You are also given an integer k. The value of coordinate (a, b) of the matrix is the XOR of all matrix[i][j] where 0 <= i <= a < m and 0 <= j <= b < n (0-indexed). Find the kth largest value (1-indexed) of all the coordinates of matrix. ", + "category": [ + "Array", + "Divide and Conquer", + "Bit Manipulation", + "Heap (Priority Queue)", + "Matrix", + "Prefix Sum", + "Quickselect" + ], + "complexity": "Medium", + "successrate": 62.1, + "totalsubmissions": 22787, + "totalaccepted": 14142, + "likes": 306, + "dislikes": 45, + "hints": "Use a 2D prefix sum to precalculate the xor-sum of the upper left submatrix.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "matrix = [[5,2],[1,6]], k = 1", + "expected_output": "7", + "explanation": "The value of coordinate (0,1) is 5 XOR 2 = 7, which is the largest value." + }, + { + "example_num": 2, + "expected_input": "matrix = [[5,2],[1,6]], k = 2", + "expected_output": "5", + "explanation": "The value of coordinate (0,0) is 5 = 5, which is the 2nd largest value." + }, + { + "example_num": 3, + "expected_input": "matrix = [[5,2],[1,6]], k = 3", + "expected_output": "4", + "explanation": "The value of coordinate (1,0) is 5 XOR 1 = 4, which is the 3rd largest value." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e43", + "questionid": 888, + "title": "Restore the Array From Adjacent Pairs", + "slug": "restore-the-array-from-adjacent-pairs", + "description": "There is an integer array nums that consists of n unique elements, but you have forgotten it. However, you do remember every pair of adjacent elements in nums. You are given a 2D integer array adjacentPairs of size n - 1 where each adjacentPairs[i] = [ui, vi] indicates that the elements ui and vi are adjacent in nums. It is guaranteed that every adjacent pair of elements nums[i] and nums[i+1] will exist in adjacentPairs, either as [nums[i], nums[i+1]] or [nums[i+1], nums[i]]. The pairs can appear in any order. Return the original array nums. If there are multiple solutions, return any of them. ", + "category": [ + "Array", + "Hash Table" + ], + "complexity": "Medium", + "successrate": 68.1, + "totalsubmissions": 36826, + "totalaccepted": 25075, + "likes": 624, + "dislikes": 11, + "hints": "Find the first element of nums - it will only appear once in adjacentPairs. The adjacent pairs are like edges of a graph. Perform a depth-first search from the first element.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "adjacentPairs = [[2,1],[3,4],[3,2]]", + "expected_output": "[1,2,3,4]", + "explanation": "This array has all its adjacent pairs in adjacentPairs.\nNotice that adjacentPairs[i] may not be in left-to-right order." + }, + { + "example_num": 2, + "expected_input": "adjacentPairs = [[4,-2],[1,4],[-3,1]]", + "expected_output": "[-2,4,1,-3]", + "explanation": "There can be negative numbers.\nAnother solution is [-3,1,4,-2], which would also be accepted." + }, + { + "example_num": 3, + "expected_input": "adjacentPairs = [[100000,-100000]]", + "expected_output": "[100000,-100000]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e47", + "questionid": 892, + "title": "Tree of Coprimes", + "slug": "tree-of-coprimes", + "description": "There is a tree (i.e., a connected, undirected graph that has no cycles) consisting of n nodes numbered from 0 to n - 1 and exactly n - 1 edges. Each node has a value associated with it, and the root of the tree is node 0. To represent this tree, you are given an integer array nums and a 2D array edges. Each nums[i] represents the ith node's value, and each edges[j] = [uj, vj] represents an edge between nodes uj and vj in the tree. Two values x and y are coprime if gcd(x, y) == 1 where gcd(x, y) is the greatest common divisor of x and y. An ancestor of a node i is any other node on the shortest path from node i to the root. A node is not considered an ancestor of itself. Return an array ans of size n, where ans[i] is the closest ancestor to node i such that nums[i] and nums[ans[i]] are coprime, or -1 if there is no such ancestor. ", + "category": [ + "Math", + "Tree", + "Depth-First Search", + "Breadth-First Search" + ], + "complexity": "Hard", + "successrate": 38.3, + "totalsubmissions": 14330, + "totalaccepted": 5486, + "likes": 224, + "dislikes": 17, + "hints": "Note that for a node, it's not optimal to consider two nodes with the same value. Note that the values are small enough for you to iterate over them instead of iterating over the parent nodes.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [2,3,3,2], edges = [[0,1],[1,2],[1,3]]", + "expected_output": "[-1,0,0,1]", + "explanation": "In the above figure, each node's value is in parentheses.\n- Node 0 has no coprime ancestors.\n- Node 1 has only one ancestor, node 0. Their values are coprime (gcd(2,3) == 1).\n- Node 2 has two ancestors, nodes 1 and 0. Node 1's value is not coprime (gcd(3,3) == 3), but node 0's\n value is (gcd(2,3) == 1), so node 0 is the closest valid ancestor.\n- Node 3 has two ancestors, nodes 1 and 0. It is coprime with node 1 (gcd(3,2) == 1), so node 1 is its\n closest valid ancestor." + }, + { + "example_num": 2, + "expected_input": "nums = [5,6,10,2,3,6,15], edges = [[0,1],[0,2],[1,3],[1,4],[2,5],[2,6]]", + "expected_output": "[-1,0,-1,0,0,0,-1]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e4b", + "questionid": 896, + "title": "Count Number of Homogenous Substrings", + "slug": "count-number-of-homogenous-substrings", + "description": "Given a string s, return the number of homogenous substrings of s. Since the answer may be too large, return it modulo 109 + 7. A string is homogenous if all the characters of the string are the same. A substring is a contiguous sequence of characters within a string. ", + "category": [ + "Math", + "String" + ], + "complexity": "Medium", + "successrate": 46.4, + "totalsubmissions": 38800, + "totalaccepted": 18005, + "likes": 376, + "dislikes": 38, + "hints": "A string of only 'a's of length k contains k choose 2 homogenous substrings. Split the string into substrings where each substring contains only one letter, and apply the formula on each substring's length.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "abbcccaa"", + "expected_output": "13", + "explanation": "The homogenous substrings are listed as below:\n"a" appears 3 times.\n"aa" appears 1 time.\n"b" appears 2 times.\n"bb" appears 1 time.\n"c" appears 3 times.\n"cc" appears 2 times.\n"ccc" appears 1 time.\n3 + 1 + 2 + 1 + 3 + 2 + 1 = 13." + }, + { + "example_num": 2, + "expected_input": "s = "xy"", + "expected_output": "2", + "explanation": "The homogenous substrings are "x" and "y"." + }, + { + "example_num": 3, + "expected_input": "s = "zzzzz"", + "expected_output": "15", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e5a", + "questionid": 911, + "title": "Maximum Score of a Good Subarray", + "slug": "maximum-score-of-a-good-subarray", + "description": "You are given an array of integers nums (0-indexed) and an integer k. The score of a subarray (i, j) is defined as min(nums[i], nums[i+1], ..., nums[j]) * (j - i + 1). A good subarray is a subarray where i <= k <= j. Return the maximum possible score of a good subarray. ", + "category": [ + "Array", + "Two Pointers", + "Binary Search", + "Stack", + "Monotonic Stack" + ], + "complexity": "Hard", + "successrate": 51.5, + "totalsubmissions": 25890, + "totalaccepted": 13338, + "likes": 580, + "dislikes": 24, + "hints": "Try thinking about the prefix before index k and the suffix after index k as two separate arrays. Using two pointers or binary search, we can find the maximum prefix of each array where the numbers are less than or equal to a certain value", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,4,3,7,4,5], k = 3", + "expected_output": "15", + "explanation": "The optimal subarray is (1, 5) with a score of min(4,3,7,4,5) * (5-1+1) = 3 * 5 = 15." + }, + { + "example_num": 2, + "expected_input": "nums = [5,5,4,5,4,1,1,1], k = 0", + "expected_output": "20", + "explanation": "The optimal subarray is (0, 4) with a score of min(5,5,4,5,4) * (4-0+1) = 4 * 5 = 20." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e4c", + "questionid": 897, + "title": "Minimum Degree of a Connected Trio in a Graph", + "slug": "minimum-degree-of-a-connected-trio-in-a-graph", + "description": "You are given an undirected graph. You are given an integer n which is the number of nodes in the graph and an array edges, where each edges[i] = [ui, vi] indicates that there is an undirected edge between ui and vi. A connected trio is a set of three nodes where there is an edge between every pair of them. The degree of a connected trio is the number of edges where one endpoint is in the trio, and the other is not. Return the minimum degree of a connected trio in the graph, or -1 if the graph has no connected trios. ", + "category": [ + "Graph" + ], + "complexity": "Hard", + "successrate": 41.4, + "totalsubmissions": 36422, + "totalaccepted": 15094, + "likes": 189, + "dislikes": 208, + "hints": "Consider a trio with nodes u, v, and w. The degree of the trio is just degree(u) + degree(v) + degree(w) - 6. The -6 comes from subtracting the edges u-v, u-w, and v-w, which are counted twice each in the vertex degree calculation. To get the trios (u,v,w), you can iterate on u, then iterate on each w,v such that w and v are neighbors of u and are neighbors of each other.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 6, edges = [[1,2],[1,3],[3,2],[4,1],[5,2],[3,6]]", + "expected_output": "3", + "explanation": "There is exactly one trio, which is [1,2,3]. The edges that form its degree are bolded in the figure above." + }, + { + "example_num": 2, + "expected_input": "n = 7, edges = [[1,3],[4,1],[4,3],[2,5],[5,6],[6,7],[7,5],[2,6]]", + "expected_output": "0", + "explanation": "There are exactly three trios:\n1) [1,4,3] with degree 0.\n2) [2,5,6] with degree 2.\n3) [5,6,7] with degree 2." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e5e", + "questionid": 915, + "title": "Maximum Ascending Subarray Sum", + "slug": "maximum-ascending-subarray-sum", + "description": "Given an array of positive integers nums, return the maximum possible sum of an ascending subarray in nums. A subarray is defined as a contiguous sequence of numbers in an array. A subarray [numsl, numsl+1, ..., numsr-1, numsr] is ascending if for all i where l <= i < r, numsi < numsi+1. Note that a subarray of size 1 is ascending. ", + "category": [ + "Array" + ], + "complexity": "Easy", + "successrate": 64.4, + "totalsubmissions": 45315, + "totalaccepted": 29180, + "likes": 374, + "dislikes": 13, + "hints": "It is fast enough to check all possible subarrays The end of each ascending subarray will be the start of the next", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [10,20,30,5,10,50]", + "expected_output": "65\nExplanation: [5,10,50] is the ascending subarray with the maximum sum of 65.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "nums = [10,20,30,40,50]", + "expected_output": "150\nExplanation: [10,20,30,40,50] is the ascending subarray with the maximum sum of 150.", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "nums = [12,17,15,13,10,11,12]", + "expected_output": "33\nExplanation: [10,11,12] is the ascending subarray with the maximum sum of 33.", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e5f", + "questionid": 916, + "title": "Maximum Number of Consecutive Values You Can Make", + "slug": "maximum-number-of-consecutive-values-you-can-make", + "description": "You are given an integer array coins of length n which represents the n coins that you own. The value of the ith coin is coins[i]. You can make some value x if you can choose some of your n coins such that their values sum up to x. Return the maximum number of consecutive integer values that you can make with your coins starting from and including 0. Note that you may have multiple coins of the same value. ", + "category": [ + "Array", + "Greedy" + ], + "complexity": "Medium", + "successrate": 51.7, + "totalsubmissions": 18646, + "totalaccepted": 9633, + "likes": 468, + "dislikes": 36, + "hints": "If you can make the first x values and you have a value v, then you can make all the values ‰¤ v + x Sort the array of coins. You can always make the value 0 so you can start with x = 0. Process the values starting from the smallest and stop when there is a value that cannot be achieved with the current x.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "coins = [1,3]", + "expected_output": "2\nExplanation: You can make the following values:\n- 0: take []\n- 1: take [1]\nYou can make 2 consecutive integer values starting from 0.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "coins = [1,1,1,4]", + "expected_output": "8\nExplanation: You can make the following values:\n- 0: take []\n- 1: take [1]\n- 2: take [1,1]\n- 3: take [1,1,1]\n- 4: take [4]\n- 5: take [4,1]\n- 6: take [4,1,1]\n- 7: take [4,1,1,1]\nYou can make 8 consecutive integer values starting from 0.", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "coins = [1,4,10,3,1]", + "expected_output": "20", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e64", + "questionid": 921, + "title": "Number of Different Subsequences GCDs", + "slug": "number-of-different-subsequences-gcds", + "description": "You are given an array nums that consists of positive integers. The GCD of a sequence of numbers is defined as the greatest integer that divides all the numbers in the sequence evenly. A subsequence of an array is a sequence that can be formed by removing some elements (possibly none) of the array. Return the number of different GCDs among all non-empty subsequences of nums. ", + "category": [ + "Array", + "Math", + "Counting", + "Number Theory" + ], + "complexity": "Hard", + "successrate": 37, + "totalsubmissions": 15129, + "totalaccepted": 5600, + "likes": 253, + "dislikes": 33, + "hints": "Think of how to check if a number x is a gcd of a subsequence. If there is such subsequence, then all of it will be divisible by x. Moreover, if you divide each number in the subsequence by x , then the gcd of the resulting numbers will be 1. Adding a number to a subsequence cannot increase its gcd. So, if there is a valid subsequence for x , then the subsequence that contains all multiples of x is a valid one too. Iterate on all possiblex from 1 to 10^5, and check if there is a valid subsequence for x.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [6,10,3]", + "expected_output": "5", + "explanation": "The figure shows all the non-empty subsequences and their GCDs.\nThe different GCDs are 6, 10, 3, 2, and 1." + }, + { + "example_num": 2, + "expected_input": "nums = [5,15,40,5,6]", + "expected_output": "7", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e6a", + "questionid": 927, + "title": "Sorting the Sentence", + "slug": "sorting-the-sentence", + "description": "A sentence is a list of words that are separated by a single space with no leading or trailing spaces. Each word consists of lowercase and uppercase English letters. A sentence can be shuffled by appending the 1-indexed word position to each word then rearranging the words in the sentence. Given a shuffled sentence s containing no more than 9 words, reconstruct and return the original sentence. ", + "category": [ + "String", + "Sorting" + ], + "complexity": "Easy", + "successrate": 84.5, + "totalsubmissions": 72587, + "totalaccepted": 61324, + "likes": 907, + "dislikes": 26, + "hints": "Divide the string into the words as an array of strings Sort the words by removing the last character from each word and sorting according to it", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "is2 sentence4 This1 a3"", + "expected_output": ""This is a sentence"", + "explanation": "Sort the words in s to their original positions "This1 is2 a3 sentence4", then remove the numbers." + }, + { + "example_num": 2, + "expected_input": "s = "Myself2 Me1 I4 and3"", + "expected_output": ""Me Myself and I"", + "explanation": "Sort the words in s to their original positions "Me1 Myself2 and3 I4", then remove the numbers." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e73", + "questionid": 936, + "title": "Largest Color Value in a Directed Graph", + "slug": "largest-color-value-in-a-directed-graph", + "description": "There is a directed graph of n colored nodes and m edges. The nodes are numbered from 0 to n - 1. You are given a string colors where colors[i] is a lowercase English letter representing the color of the ith node in this graph (0-indexed). You are also given a 2D array edges where edges[j] = [aj, bj] indicates that there is a directed edge from node aj to node bj. A valid path in the graph is a sequence of nodes x1 -> x2 -> x3 -> ... -> xk such that there is a directed edge from xi to xi+1 for every 1 <= i < k. The color value of the path is the number of nodes that are colored the most frequently occurring color along that path. Return the largest color value of any valid path in the given graph, or -1 if the graph contains a cycle. ", + "category": [ + "Hash Table", + "Dynamic Programming", + "Graph", + "Topological Sort", + "Memoization", + "Counting" + ], + "complexity": "Hard", + "successrate": 39.8, + "totalsubmissions": 27398, + "totalaccepted": 10897, + "likes": 436, + "dislikes": 16, + "hints": "Use topological sort. let dp[u][c] := the maximum count of vertices with color c of any path starting from vertex u. (by JerryJin2905)", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "colors = "abaca", edges = [[0,1],[0,2],[2,3],[3,4]]", + "expected_output": "3", + "explanation": "The path 0 -> 2 -> 3 -> 4 contains 3 nodes that are colored "a" (red in the above image)." + }, + { + "example_num": 2, + "expected_input": "colors = "a", edges = [[0,0]]", + "expected_output": "-1", + "explanation": "There is a cycle from 0 to 0." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e80", + "questionid": 949, + "title": "Determine Whether Matrix Can Be Obtained By Rotation", + "slug": "determine-whether-matrix-can-be-obtained-by-rotation", + "description": "Given two n x n binary matrices mat and target, return true if it is possible to make mat equal to target by rotating mat in 90-degree increments, or false otherwise. ", + "category": [ + "Array", + "Matrix" + ], + "complexity": "Easy", + "successrate": 55.2, + "totalsubmissions": 52447, + "totalaccepted": 28970, + "likes": 571, + "dislikes": 52, + "hints": "What is the maximum number of rotations you have to check? Is there a formula you can use to rotate a matrix 90 degrees?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "mat = [[0,1],[1,0]], target = [[1,0],[0,1]]", + "expected_output": "true\nExplanation: We can rotate mat 90 degrees clockwise to make mat equal target.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "mat = [[0,1],[1,1]], target = [[1,0],[0,1]]", + "expected_output": "false", + "explanation": "It is impossible to make mat equal to target by rotating mat." + }, + { + "example_num": 3, + "expected_input": "mat = [[0,0,0],[0,1,0],[1,1,1]], target = [[1,1,1],[0,1,0],[0,0,0]]", + "expected_output": "true\nExplanation: We can rotate mat 90 degrees clockwise two times to make mat equal target.", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e84", + "questionid": 953, + "title": "Redistribute Characters to Make All Strings Equal", + "slug": "redistribute-characters-to-make-all-strings-equal", + "description": "You are given an array of strings words (0-indexed). In one operation, pick two distinct indices i and j, where words[i] is a non-empty string, and move any character from words[i] to any position in words[j]. Return true if you can make every string in words equal using any number of operations, and false otherwise. ", + "category": [ + "Hash Table", + "String", + "Counting" + ], + "complexity": "Easy", + "successrate": 60.1, + "totalsubmissions": 35911, + "totalaccepted": 21568, + "likes": 256, + "dislikes": 32, + "hints": "Characters are independent€”only the frequency of characters matters. It is possible to distribute characters if all characters can be divided equally among all strings.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "words = ["abc","aabc","bc"]", + "expected_output": "true", + "explanation": "Move the first 'a' in words[1] to the front of words[2],\nto make words[1] = "abc" and words[2] = "abc".\nAll the strings are now equal to "abc", so return true." + }, + { + "example_num": 2, + "expected_input": "words = ["ab","a"]", + "expected_output": "false", + "explanation": "It is impossible to make all the strings equal using the operation." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e85", + "questionid": 954, + "title": "Maximum Number of Removable Characters", + "slug": "maximum-number-of-removable-characters", + "description": "You are given two strings s and p where p is a subsequence of s. You are also given a distinct 0-indexed integer array removable containing a subset of indices of s (s is also 0-indexed). You want to choose an integer k (0 <= k <= removable.length) such that, after removing k characters from s using the first k indices in removable, p is still a subsequence of s. More formally, you will mark the character at s[removable[i]] for each 0 <= i < k, then remove all marked characters and check if p is still a subsequence. Return the maximum k you can choose such that p is still a subsequence of s after the removals. A subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters. ", + "category": [ + "Array", + "String", + "Binary Search" + ], + "complexity": "Medium", + "successrate": 35.9, + "totalsubmissions": 34885, + "totalaccepted": 12511, + "likes": 544, + "dislikes": 63, + "hints": "First, we need to think about solving an easier problem, If we remove a set of indices from the string does P exist in S as a subsequence We can binary search the K and check by solving the above problem.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "abcacb", p = "ab", removable = [3,1,0]", + "expected_output": "2\nExplanation: After removing the characters at indices 3 and 1, "abcacb" becomes "accb".\n"ab" is a subsequence of "accb".\nIf we remove the characters at indices 3, 1, and 0, "abcacb" becomes "ccb", and "ab" is no longer a subsequence.\nHence, the maximum k is 2.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "s = "abcbddddd", p = "abcd", removable = [3,2,1,4,5,6]", + "expected_output": "1\nExplanation: After removing the character at index 3, "abcbddddd" becomes "abcddddd".\n"abcd" is a subsequence of "abcddddd".", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "s = "abcab", p = "abc", removable = [0,1,2,3,4]", + "expected_output": "0\nExplanation: If you remove the first index in the array removable, "abc" is no longer a subsequence.", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e86", + "questionid": 955, + "title": "The Earliest and Latest Rounds Where Players Compete", + "slug": "the-earliest-and-latest-rounds-where-players-compete", + "description": "There is a tournament where n players are participating. The players are standing in a single row and are numbered from 1 to n based on their initial standing position (player 1 is the first player in the row, player 2 is the second player in the row, etc.). The tournament consists of multiple rounds (starting from round number 1). In each round, the ith player from the front of the row competes against the ith player from the end of the row, and the winner advances to the next round. When the number of players is odd for the current round, the player in the middle automatically advances to the next round. After each round is over, the winners are lined back up in the row based on the original ordering assigned to them initially (ascending order). The players numbered firstPlayer and secondPlayer are the best in the tournament. They can win against any other player before they compete against each other. If any two other players compete against each other, either of them might win, and thus you may choose the outcome of this round. Given the integers n, firstPlayer, and secondPlayer, return an integer array containing two values, the earliest possible round number and the latest possible round number in which these two players will compete against each other, respectively. ", + "category": [ + "Dynamic Programming", + "Memoization" + ], + "complexity": "Hard", + "successrate": 51.6, + "totalsubmissions": 7437, + "totalaccepted": 3834, + "likes": 162, + "dislikes": 15, + "hints": "Brute force using bitmasks and simulate the rounds. Calculate each state one time and save its solution.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 11, firstPlayer = 2, secondPlayer = 4", + "expected_output": "[3,4]", + "explanation": "One possible scenario which leads to the earliest round number:\nFirst round: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11\nSecond round: 2, 3, 4, 5, 6, 11\nThird round: 2, 3, 4\nOne possible scenario which leads to the latest round number:\nFirst round: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11\nSecond round: 1, 2, 3, 4, 5, 6\nThird round: 1, 2, 4\nFourth round: 2, 4" + }, + { + "example_num": 2, + "expected_input": "n = 5, firstPlayer = 1, secondPlayer = 5", + "expected_output": "[1,1]", + "explanation": "The players numbered 1 and 5 compete in the first round.\nThere is no way to make them compete in any other round." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e87", + "questionid": 956, + "title": "Egg Drop With 2 Eggs and N Floors", + "slug": "egg-drop-with-2-eggs-and-n-floors", + "description": "You are given two identical eggs and you have access to a building with n floors labeled from 1 to n. You know that there exists a floor f where 0 <= f <= n such that any egg dropped at a floor higher than f will break, and any egg dropped at or below floor f will not break. In each move, you may take an unbroken egg and drop it from any floor x (where 1 <= x <= n). If the egg breaks, you can no longer use it. However, if the egg does not break, you may reuse it in future moves. Return the minimum number of moves that you need to determine with certainty what the value of f is. ", + "category": [ + "Math", + "Dynamic Programming" + ], + "complexity": "Medium", + "successrate": 70.3, + "totalsubmissions": 27756, + "totalaccepted": 19517, + "likes": 694, + "dislikes": 61, + "hints": "Is it really optimal to always drop the egg on the middle floor for each move? Can we create states based on the number of unbroken eggs and floors to build our solution?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 2", + "expected_output": "2", + "explanation": "We can drop the first egg from floor 1 and the second egg from floor 2.\nIf the first egg breaks, we know that f = 0.\nIf the second egg breaks but the first egg didn't, we know that f = 1.\nOtherwise, if both eggs survive, we know that f = 2." + }, + { + "example_num": 2, + "expected_input": "n = 100", + "expected_output": "14", + "explanation": "One optimal strategy is:\n- Drop the 1st egg at floor 9. If it breaks, we know f is between 0 and 8. Drop the 2nd egg starting from floor 1 and going up one at a time to find f within 8 more drops. Total drops is 1 + 8 = 9.\n- If the 1st egg does not break, drop the 1st egg again at floor 22. If it breaks, we know f is between 9 and 21. Drop the 2nd egg starting from floor 10 and going up one at a time to find f within 12 more drops. Total drops is 2 + 12 = 14.\n- If the 1st egg does not break again, follow a similar process dropping the 1st egg from floors 34, 45, 55, 64, 72, 79, 85, 90, 94, 97, 99, and 100.\nRegardless of the outcome, it takes at most 14 drops to determine f." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e8a", + "questionid": 959, + "title": "Count Square Sum Triples", + "slug": "count-square-sum-triples", + "description": "A square triple (a,b,c) is a triple where a, b, and c are integers and a2 + b2 = c2. Given an integer n, return the number of square triples such that 1 <= a, b, c <= n. ", + "category": [ + "Math", + "Enumeration" + ], + "complexity": "Easy", + "successrate": 67.4, + "totalsubmissions": 30768, + "totalaccepted": 20742, + "likes": 179, + "dislikes": 19, + "hints": "Iterate over all possible pairs (a,b) and check that the square root of a * a + b * b is an integers less than or equal n You can check that the square root of an integer is an integer using binary seach or a builtin function like sqrt", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 5", + "expected_output": "2\nExplanation: The square triples are (3,4,5) and (4,3,5).", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "n = 10", + "expected_output": "4\nExplanation: The square triples are (3,4,5), (4,3,5), (6,8,10), and (8,6,10).", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e8b", + "questionid": 960, + "title": "Nearest Exit from Entrance in Maze", + "slug": "nearest-exit-from-entrance-in-maze", + "description": "You are given an m x n matrix maze (0-indexed) with empty cells (represented as '.') and walls (represented as '+'). You are also given the entrance of the maze, where entrance = [entrancerow, entrancecol] denotes the row and column of the cell you are initially standing at. In one step, you can move one cell up, down, left, or right. You cannot step into a cell with a wall, and you cannot step outside the maze. Your goal is to find the nearest exit from the entrance. An exit is defined as an empty cell that is at the border of the maze. The entrance does not count as an exit. Return the number of steps in the shortest path from the entrance to the nearest exit, or -1 if no such path exists. ", + "category": [ + "Array", + "Breadth-First Search", + "Matrix" + ], + "complexity": "Medium", + "successrate": 40.1, + "totalsubmissions": 43797, + "totalaccepted": 17564, + "likes": 450, + "dislikes": 19, + "hints": "Which type of traversal lets you find the distance from a point? Try using a Breadth First Search.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "maze = [["+","+",".","+"],[".",".",".","+"],["+","+","+","."]], entrance = [1,2]", + "expected_output": "1", + "explanation": "There are 3 exits in this maze at [1,0], [0,2], and [2,3].\nInitially, you are at the entrance cell [1,2].\n- You can reach [1,0] by moving 2 steps left.\n- You can reach [0,2] by moving 1 step up.\nIt is impossible to reach [2,3] from the entrance.\nThus, the nearest exit is [0,2], which is 1 step away." + }, + { + "example_num": 2, + "expected_input": "maze = [["+","+","+"],[".",".","."],["+","+","+"]], entrance = [1,0]", + "expected_output": "2", + "explanation": "There is 1 exit in this maze at [1,2].\n[1,0] does not count as an exit since it is the entrance cell.\nInitially, you are at the entrance cell [1,0].\n- You can reach [1,2] by moving 2 steps right.\nThus, the nearest exit is [1,2], which is 2 steps away." + }, + { + "example_num": 3, + "expected_input": "maze = [[".","+"]], entrance = [0,0]", + "expected_output": "-1", + "explanation": "There are no exits in this maze." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e4e", + "questionid": 899, + "title": "Sum of Beauty of All Substrings", + "slug": "sum-of-beauty-of-all-substrings", + "description": "The beauty of a string is the difference in frequencies between the most frequent and least frequent characters. Given a string s, return the sum of beauty of all of its substrings. ", + "category": [ + "Hash Table", + "String", + "Counting" + ], + "complexity": "Medium", + "successrate": 59.9, + "totalsubmissions": 21629, + "totalaccepted": 12952, + "likes": 306, + "dislikes": 83, + "hints": "Maintain a prefix sum for the frequencies of characters. You can iterate over all substring then iterate over the alphabet and find which character appears most and which appears least using the prefix sum array", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "aabcb"", + "expected_output": "5\nExplanation: The substrings with non-zero beauty are ["aab","aabc","aabcb","abcb","bcb"], each with beauty equal to 1.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "s = "aabcbaa"", + "expected_output": "17", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e57", + "questionid": 908, + "title": "Check if One String Swap Can Make Strings Equal", + "slug": "check-if-one-string-swap-can-make-strings-equal", + "description": "You are given two strings s1 and s2 of equal length. A string swap is an operation where you choose two indices in a string (not necessarily different) and swap the characters at these indices. Return true if it is possible to make both strings equal by performing at most one string swap on exactly one of the strings. Otherwise, return false. ", + "category": [ + "Hash Table", + "String", + "Counting" + ], + "complexity": "Easy", + "successrate": 45.9, + "totalsubmissions": 84230, + "totalaccepted": 38673, + "likes": 452, + "dislikes": 18, + "hints": "The answer is false if the number of nonequal positions in the strings is not equal to 0 or 2. Check that these positions have the same set of characters.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s1 = "bank", s2 = "kanb"", + "expected_output": "true", + "explanation": "For example, swap the first character with the last character of s2 to make "bank"." + }, + { + "example_num": 2, + "expected_input": "s1 = "attack", s2 = "defend"", + "expected_output": "false", + "explanation": "It is impossible to make them equal with one string swap." + }, + { + "example_num": 3, + "expected_input": "s1 = "kelb", s2 = "kelb"", + "expected_output": "true", + "explanation": "The two strings are already equal, so no string swap operation is required." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e5c", + "questionid": 913, + "title": "Sentence Similarity III", + "slug": "sentence-similarity-iii", + "description": "A sentence is a list of words that are separated by a single space with no leading or trailing spaces. For example, \"Hello World\", \"HELLO\", \"hello world hello world\" are all sentences. Words consist of only uppercase and lowercase English letters. Two sentences sentence1 and sentence2 are similar if it is possible to insert an arbitrary sentence (possibly empty) inside one of these sentences such that the two sentences become equal. For example, sentence1 = \"Hello my name is Jane\" and sentence2 = \"Hello Jane\" can be made equal by inserting \"my name is\" between \"Hello\" and \"Jane\" in sentence2. Given two sentences sentence1 and sentence2, return true if sentence1 and sentence2 are similar. Otherwise, return false. ", + "category": [ + "Array", + "Two Pointers", + "String" + ], + "complexity": "Medium", + "successrate": 32.4, + "totalsubmissions": 29402, + "totalaccepted": 9519, + "likes": 213, + "dislikes": 39, + "hints": "One way to look at it is to find one sentence as a concatenation of a prefix and suffix from the other sentence. Get the longest common prefix between them and the longest common suffix.", + "deleted": false, + "examples": [] + }, + { + "_id": "66f925ddfdfb8e1665720e65", + "questionid": 922, + "title": "Replace All Digits with Characters", + "slug": "replace-all-digits-with-characters", + "description": "You are given a 0-indexed string s that has lowercase English letters in its even indices and digits in its odd indices. There is a function shift(c, x), where c is a character and x is a digit, that returns the xth character after c. For every odd index i, you want to replace the digit s[i] with shift(s[i-1], s[i]). Return s after replacing all digits. It is guaranteed that shift(s[i-1], s[i]) will never exceed 'z'. ", + "category": [ + "String" + ], + "complexity": "Easy", + "successrate": 80.1, + "totalsubmissions": 48332, + "totalaccepted": 38693, + "likes": 377, + "dislikes": 46, + "hints": "We just need to replace every even positioned character with the character s[i] positions ahead of the character preceding it Get the position of the preceeding character in alphabet then advance it s[i] positions and get the character at that position", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "a1c1e1"", + "expected_output": ""abcdef"\nExplanation: The digits are replaced as follows:\n- s[1] -> shift('a',1) = 'b'\n- s[3] -> shift('c',1) = 'd'\n- s[5] -> shift('e',1) = 'f'", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "s = "a1b2c3d4e"", + "expected_output": ""abbdcfdhe"\nExplanation: The digits are replaced as follows:\n- s[1] -> shift('a',1) = 'b'\n- s[3] -> shift('b',2) = 'd'\n- s[5] -> shift('c',3) = 'f'\n- s[7] -> shift('d',4) = 'h'", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e66", + "questionid": 923, + "title": "Check if the Sentence Is Pangram", + "slug": "check-if-the-sentence-is-pangram", + "description": "A pangram is a sentence where every letter of the English alphabet appears at least once. Given a string sentence containing only lowercase English letters, return true if sentence is a pangram, or false otherwise. ", + "category": [ + "Hash Table", + "String" + ], + "complexity": "Easy", + "successrate": 81.4, + "totalsubmissions": 98831, + "totalaccepted": 80461, + "likes": 707, + "dislikes": 18, + "hints": "Iterate over the string and mark each character as found (using a boolean array, bitmask, or any other similar way). Check if the number of found characters equals the alphabet length.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "sentence = "thequickbrownfoxjumpsoverthelazydog"", + "expected_output": "true", + "explanation": "sentence contains at least one of every letter of the English alphabet." + }, + { + "example_num": 2, + "expected_input": "sentence = "leetcode"", + "expected_output": "false", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e6d", + "questionid": 930, + "title": "Splitting a String Into Descending Consecutive Values", + "slug": "splitting-a-string-into-descending-consecutive-values", + "description": "You are given a string s that consists of only digits. Check if we can split s into two or more non-empty substrings such that the numerical values of the substrings are in descending order and the difference between numerical values of every two adjacent substrings is equal to 1. Return true if it is possible to split s as described above, or false otherwise. A substring is a contiguous sequence of characters in a string. ", + "category": [ + "String", + "Backtracking" + ], + "complexity": "Medium", + "successrate": 31.2, + "totalsubmissions": 45020, + "totalaccepted": 14056, + "likes": 309, + "dislikes": 82, + "hints": "One solution is to try all possible splits using backtrack Look out for trailing zeros in string", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "1234"", + "expected_output": "false", + "explanation": "There is no valid way to split s." + }, + { + "example_num": 2, + "expected_input": "s = "050043"", + "expected_output": "true", + "explanation": "s can be split into ["05", "004", "3"] with numerical values [5,4,3].\nThe values are in descending order with adjacent values differing by 1." + }, + { + "example_num": 3, + "expected_input": "s = "9080701"", + "expected_output": "false", + "explanation": "There is no valid way to split s." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e76", + "questionid": 939, + "title": "Minimum Number of Swaps to Make the Binary String Alternating", + "slug": "minimum-number-of-swaps-to-make-the-binary-string-alternating", + "description": "Given a binary string s, return the minimum number of character swaps to make it alternating, or -1 if it is impossible. The string is called alternating if no two adjacent characters are equal. For example, the strings \"010\" and \"1010\" are alternating, while the string \"0100\" is not. Any two characters may be swapped, even if they are not adjacent. ", + "category": [ + "String", + "Greedy" + ], + "complexity": "Medium", + "successrate": 38.8, + "totalsubmissions": 33785, + "totalaccepted": 13095, + "likes": 298, + "dislikes": 22, + "hints": "Think about all valid strings of length n. Try to count the mismatched positions with each valid string of length n.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "111000"", + "expected_output": "1", + "explanation": "Swap positions 1 and 4: "111000" -> "101010"\nThe string is now alternating." + }, + { + "example_num": 2, + "expected_input": "s = "010"", + "expected_output": "0", + "explanation": "The string is already alternating, no swaps are needed." + }, + { + "example_num": 3, + "expected_input": "s = "1110"", + "expected_output": "-1", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e82", + "questionid": 951, + "title": "Remove One Element to Make the Array Strictly Increasing", + "slug": "remove-one-element-to-make-the-array-strictly-increasing", + "description": "Given a 0-indexed integer array nums, return true if it can be made strictly increasing after removing exactly one element, or false otherwise. If the array is already strictly increasing, return true. The array nums is strictly increasing if nums[i - 1] < nums[i] for each index (1 <= i < nums.length). ", + "category": [ + "Array" + ], + "complexity": "Easy", + "successrate": 27.3, + "totalsubmissions": 92517, + "totalaccepted": 25295, + "likes": 484, + "dislikes": 195, + "hints": "For each index i in nums remove this index. If the array becomes sorted return true, otherwise revert to the original array and try different index.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,2,10,5,7]", + "expected_output": "true", + "explanation": "By removing 10 at index 2 from nums, it becomes [1,2,5,7].\n[1,2,5,7] is strictly increasing, so return true." + }, + { + "example_num": 2, + "expected_input": "nums = [2,3,1,2]", + "expected_output": "false", + "explanation": "[3,1,2] is the result of removing the element at index 0.\n[2,1,2] is the result of removing the element at index 1.\n[2,3,2] is the result of removing the element at index 2.\n[2,3,1] is the result of removing the element at index 3.\nNo resulting array is strictly increasing, so return false." + }, + { + "example_num": 3, + "expected_input": "nums = [1,1,1]", + "expected_output": "false", + "explanation": "The result of removing any element is [1,1].\n[1,1] is not strictly increasing, so return false." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e88", + "questionid": 957, + "title": "Largest Odd Number in String", + "slug": "largest-odd-number-in-string", + "description": "You are given a string num, representing a large integer. Return the largest-valued odd integer (as a string) that is a non-empty substring of num, or an empty string \"\" if no odd integer exists. A substring is a contiguous sequence of characters within a string. ", + "category": [ + "Math", + "String", + "Greedy" + ], + "complexity": "Easy", + "successrate": 56.9, + "totalsubmissions": 54918, + "totalaccepted": 31242, + "likes": 353, + "dislikes": 29, + "hints": "In what order should you iterate through the digits? If an odd number exists, where must the number start from?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "num = "52"", + "expected_output": ""5"", + "explanation": "The only non-empty substrings are "5", "2", and "52". "5" is the only odd number." + }, + { + "example_num": 2, + "expected_input": "num = "4206"", + "expected_output": """", + "explanation": "There are no odd numbers in "4206"." + }, + { + "example_num": 3, + "expected_input": "num = "35427"", + "expected_output": ""35427"", + "explanation": ""35427" is already an odd number." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e89", + "questionid": 958, + "title": "Count Sub Islands", + "slug": "count-sub-islands", + "description": "You are given two m x n binary matrices grid1 and grid2 containing only 0's (representing water) and 1's (representing land). An island is a group of 1's connected 4-directionally (horizontal or vertical). Any cells outside of the grid are considered water cells. An island in grid2 is considered a sub-island if there is an island in grid1 that contains all the cells that make up this island in grid2. Return the number of islands in grid2 that are considered sub-islands. ", + "category": [ + "Array", + "Depth-First Search", + "Breadth-First Search", + "Union Find", + "Matrix" + ], + "complexity": "Medium", + "successrate": 65.7, + "totalsubmissions": 45218, + "totalaccepted": 29705, + "likes": 876, + "dislikes": 27, + "hints": "Let's use floodfill to iterate over the islands of the second grid Let's note that if all the cells in an island in the second grid if they are represented by land in the first grid then they are connected hence making that island a sub-island", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "grid1 = [[1,1,1,0,0],[0,1,1,1,1],[0,0,0,0,0],[1,0,0,0,0],[1,1,0,1,1]], grid2 = [[1,1,1,0,0],[0,0,1,1,1],[0,1,0,0,0],[1,0,1,1,0],[0,1,0,1,0]]", + "expected_output": "3\nExplanation: In the picture above, the grid on the left is grid1 and the grid on the right is grid2.\nThe 1s colored red in grid2 are those considered to be part of a sub-island. There are three sub-islands.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "grid1 = [[1,0,1,0,1],[1,1,1,1,1],[0,0,0,0,0],[1,1,1,1,1],[1,0,1,0,1]], grid2 = [[0,0,0,0,0],[1,1,1,1,1],[0,1,0,1,0],[0,1,0,1,0],[1,0,0,0,1]]", + "expected_output": "2 \nExplanation: In the picture above, the grid on the left is grid1 and the grid on the right is grid2.\nThe 1s colored red in grid2 are those considered to be part of a sub-island. There are two sub-islands.", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e4d", + "questionid": 898, + "title": "Check if Number is a Sum of Powers of Three", + "slug": "check-if-number-is-a-sum-of-powers-of-three", + "description": "Given an integer n, return true if it is possible to represent n as the sum of distinct powers of three. Otherwise, return false. An integer y is a power of three if there exists an integer x such that y == 3x. ", + "category": [ + "Math" + ], + "complexity": "Medium", + "successrate": 64.7, + "totalsubmissions": 32597, + "totalaccepted": 21101, + "likes": 505, + "dislikes": 18, + "hints": "Let's note that the maximum power of 3 you'll use in your soln is 3^16 The number can not be represented as a sum of powers of 3 if it's ternary presentation has a 2 in it", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 12", + "expected_output": "true", + "explanation": "12 = 31 + 32" + }, + { + "example_num": 2, + "expected_input": "n = 91", + "expected_output": "true", + "explanation": "91 = 30 + 32 + 34" + }, + { + "example_num": 3, + "expected_input": "n = 21", + "expected_output": "false", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e4f", + "questionid": 900, + "title": "Merge Strings Alternately", + "slug": "merge-strings-alternately", + "description": "You are given two strings word1 and word2. Merge the strings by adding letters in alternating order, starting with word1. If a string is longer than the other, append the additional letters onto the end of the merged string. Return the merged string. ", + "category": [ + "Two Pointers", + "String" + ], + "complexity": "Easy", + "successrate": 75.5, + "totalsubmissions": 71706, + "totalaccepted": 54156, + "likes": 544, + "dislikes": 8, + "hints": "Use two pointers, one pointer for each string. Alternately choose the character from each pointer, and move the pointer upwards.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "word1 = "abc", word2 = "pqr"", + "expected_output": ""apbqcr"", + "explanation": " The merged string will be merged as so:\r\nword1: a b c\r\nword2: p q r\r\nmerged: a p b q c r" + }, + { + "example_num": 2, + "expected_input": "word1 = "ab", word2 = "pqrs"", + "expected_output": ""apbqrs"", + "explanation": " Notice that as word2 is longer, "rs" is appended to the end.\r\nword1: a b \r\nword2: p q r s\r\nmerged: a p b q r s" + }, + { + "example_num": 3, + "expected_input": "word1 = "abcd", word2 = "pq"", + "expected_output": ""apbqcd"", + "explanation": " Notice that as word1 is longer, "cd" is appended to the end.\r\nword1: a b c d\r\nword2: p q \r\nmerged: a p b q c d" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e51", + "questionid": 902, + "title": "Equal Sum Arrays With Minimum Number of Operations", + "slug": "equal-sum-arrays-with-minimum-number-of-operations", + "description": "You are given two arrays of integers nums1 and nums2, possibly of different lengths. The values in the arrays are between 1 and 6, inclusive. In one operation, you can change any integer's value in any of the arrays to any value between 1 and 6, inclusive. Return the minimum number of operations required to make the sum of values in nums1 equal to the sum of values in nums2. Return -1 if it is not possible to make the sum of the two arrays equal. ", + "category": [ + "Array", + "Hash Table", + "Greedy", + "Counting" + ], + "complexity": "Medium", + "successrate": 51.4, + "totalsubmissions": 28446, + "totalaccepted": 14621, + "likes": 494, + "dislikes": 16, + "hints": "Let's note that we want to either decrease the sum of the array with a larger sum or increase the array's sum with the smaller sum. You can maintain the largest increase or decrease you can make in a binary search tree and each time get the maximum one.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums1 = [1,2,3,4,5,6], nums2 = [1,1,2,2,2,2]", + "expected_output": "3", + "explanation": "You can make the sums of nums1 and nums2 equal with 3 operations. All indices are 0-indexed.\n- Change nums2[0] to 6. nums1 = [1,2,3,4,5,6], nums2 = [6,1,2,2,2,2].\n- Change nums1[5] to 1. nums1 = [1,2,3,4,5,1], nums2 = [6,1,2,2,2,2].\n- Change nums1[2] to 2. nums1 = [1,2,2,4,5,1], nums2 = [6,1,2,2,2,2]." + }, + { + "example_num": 2, + "expected_input": "nums1 = [1,1,1,1,1,1,1], nums2 = [6]", + "expected_output": "-1", + "explanation": "There is no way to decrease the sum of nums1 or to increase the sum of nums2 to make them equal." + }, + { + "example_num": 3, + "expected_input": "nums1 = [6,6], nums2 = [1]", + "expected_output": "3", + "explanation": "You can make the sums of nums1 and nums2 equal with 3 operations. All indices are 0-indexed. \n- Change nums1[0] to 2. nums1 = [2,6], nums2 = [1].\n- Change nums1[1] to 2. nums1 = [2,2], nums2 = [1].\n- Change nums2[0] to 4. nums1 = [2,2], nums2 = [4]." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e52", + "questionid": 903, + "title": "Second Largest Digit in a String", + "slug": "second-largest-digit-in-a-string", + "description": "Given an alphanumeric string s, return the second largest numerical digit that appears in s, or -1 if it does not exist. An alphanumeric string is a string consisting of lowercase English letters and digits. ", + "category": [ + "Hash Table", + "String" + ], + "complexity": "Easy", + "successrate": 49, + "totalsubmissions": 50676, + "totalaccepted": 24842, + "likes": 245, + "dislikes": 70, + "hints": "First of all, get the distinct characters since we are only interested in those Let's note that there might not be any digits.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "dfa12321afd"", + "expected_output": "2", + "explanation": "The digits that appear in s are [1, 2, 3]. The second largest digit is 2." + }, + { + "example_num": 2, + "expected_input": "s = "abc1111"", + "expected_output": "-1", + "explanation": "The digits that appear in s are [1]. There is no second largest digit." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e54", + "questionid": 905, + "title": "Check if Binary String Has at Most One Segment of Ones", + "slug": "check-if-binary-string-has-at-most-one-segment-of-ones", + "description": "Given a binary string s without leading zeros, return true if s contains at most one contiguous segment of ones. Otherwise, return false. ", + "category": [ + "String" + ], + "complexity": "Easy", + "successrate": 40.8, + "totalsubmissions": 57619, + "totalaccepted": 23535, + "likes": 163, + "dislikes": 520, + "hints": "It's guaranteed to have at least one segment The string size is small so you can count all segments of ones with no that have no adjacent ones.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "1001"", + "expected_output": "false\nExplanation: The ones do not form a contiguous segment.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "s = "110"", + "expected_output": "true", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e56", + "questionid": 907, + "title": "Number of Restricted Paths From First to Last Node", + "slug": "number-of-restricted-paths-from-first-to-last-node", + "description": "There is an undirected weighted connected graph. You are given a positive integer n which denotes that the graph has n nodes labeled from 1 to n, and an array edges where each edges[i] = [ui, vi, weighti] denotes that there is an edge between nodes ui and vi with weight equal to weighti. A path from node start to node end is a sequence of nodes [z0, z1, z2, ..., zk] such that z0 = start and zk = end and there is an edge between zi and zi+1 where 0 <= i <= k-1. The distance of a path is the sum of the weights on the edges of the path. Let distanceToLastNode(x) denote the shortest distance of a path between node n and node x. A restricted path is a path that also satisfies that distanceToLastNode(zi) > distanceToLastNode(zi+1) where 0 <= i <= k-1. Return the number of restricted paths from node 1 to node n. Since that number may be too large, return it modulo 109 + 7. ", + "category": [ + "Dynamic Programming", + "Graph", + "Topological Sort", + "Heap (Priority Queue)", + "Shortest Path" + ], + "complexity": "Medium", + "successrate": 38.6, + "totalsubmissions": 32401, + "totalaccepted": 12491, + "likes": 579, + "dislikes": 101, + "hints": "Run a Dijkstra from node numbered n to compute distance from the last node. Consider all edges [u, v] one by one and direct them such that distance of u to n > distance of v to n. If both u and v are at the same distance from n, discard this edge. Now this problem reduces to computing the number of paths from 1 to n in a DAG, a standard DP problem.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 5, edges = [[1,2,3],[1,3,3],[2,3,1],[1,4,2],[5,2,2],[3,5,1],[5,4,10]]", + "expected_output": "3", + "explanation": "Each circle contains the node number in black and its distanceToLastNode value in blue. The three restricted paths are:\n1) 1 --> 2 --> 5\n2) 1 --> 2 --> 3 --> 5\n3) 1 --> 3 --> 5" + }, + { + "example_num": 2, + "expected_input": "n = 7, edges = [[1,3,1],[4,1,2],[7,3,4],[2,5,3],[5,6,1],[6,7,2],[7,5,3],[2,6,4]]", + "expected_output": "1", + "explanation": "Each circle contains the node number in black and its distanceToLastNode value in blue. The only restricted path is 1 --> 3 --> 7." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e59", + "questionid": 910, + "title": "Maximum Average Pass Ratio", + "slug": "maximum-average-pass-ratio", + "description": "There is a school that has classes of students and each class will be having a final exam. You are given a 2D integer array classes, where classes[i] = [passi, totali]. You know beforehand that in the ith class, there are totali total students, but only passi number of students will pass the exam. You are also given an integer extraStudents. There are another extraStudents brilliant students that are guaranteed to pass the exam of any class they are assigned to. You want to assign each of the extraStudents students to a class in a way that maximizes the average pass ratio across all the classes. The pass ratio of a class is equal to the number of students of the class that will pass the exam divided by the total number of students of the class. The average pass ratio is the sum of pass ratios of all the classes divided by the number of the classes. Return the maximum possible average pass ratio after assigning the extraStudents students. Answers within 10-5 of the actual answer will be accepted. ", + "category": [ + "Array", + "Greedy", + "Heap (Priority Queue)" + ], + "complexity": "Medium", + "successrate": 50.7, + "totalsubmissions": 29069, + "totalaccepted": 14741, + "likes": 474, + "dislikes": 58, + "hints": "Pay attention to how much the pass ratio changes when you add a student to the class. If you keep adding students, what happens to the change in pass ratio? The more students you add to a class, the smaller the change in pass ratio becomes. Since the change in the pass ratio is always decreasing with the more students you add, then the very first student you add to each class is the one that makes the biggest change in the pass ratio. Because each class's pass ratio is weighted equally, it's always optimal to put the student in the class that makes the biggest change among all the other classes. Keep a max heap of the current class sizes and order them by the change in pass ratio. For each extra student, take the top of the heap, update the class size, and put it back in the heap.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "classes = [[1,2],[3,5],[2,2]], extraStudents = 2", + "expected_output": "0.78333", + "explanation": "You can assign the two extra students to the first class. The average pass ratio will be equal to (3/4 + 3/5 + 2/2) / 3 = 0.78333." + }, + { + "example_num": 2, + "expected_input": "classes = [[2,4],[3,9],[4,5],[2,10]], extraStudents = 4", + "expected_output": "0.53485", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e5d", + "questionid": 914, + "title": "Maximum Number of Groups Getting Fresh Donuts", + "slug": "maximum-number-of-groups-getting-fresh-donuts", + "description": "There is a donuts shop that bakes donuts in batches of batchSize. They have a rule where they must serve all of the donuts of a batch before serving any donuts of the next batch. You are given an integer batchSize and an integer array groups, where groups[i] denotes that there is a group of groups[i] customers that will visit the shop. Each customer will get exactly one donut. When a group visits the shop, all customers of the group must be served before serving any of the following groups. A group will be happy if they all get fresh donuts. That is, the first customer of the group does not receive a donut that was left over from the previous group. You can freely rearrange the ordering of the groups. Return the maximum possible number of happy groups after rearranging the groups. ", + "category": [ + "Array", + "Dynamic Programming", + "Bit Manipulation", + "Memoization", + "Bitmask" + ], + "complexity": "Hard", + "successrate": 39.9, + "totalsubmissions": 10493, + "totalaccepted": 4186, + "likes": 223, + "dislikes": 15, + "hints": "The maximum number of happy groups is the maximum number of partitions you can split the groups into such that the sum of group sizes in each partition is 0 mod batchSize. At most one partition is allowed to have a different remainder (the first group will get fresh donuts anyway). Suppose you have an array freq of length k where freq[i] = number of groups of size i mod batchSize. How can you utilize this in a dp solution? Make a DP state dp[freq][r] that represents \"the maximum number of partitions you can form given the current freq and current remainder r\". You can hash the freq array to store it more easily in the dp table. For each i from 0 to batchSize-1, the next DP state is dp[freq`][(r+i)%batchSize] where freq` is freq but with freq[i] decremented by 1. Take the largest of all of the next states and store it in ans. If r == 0, then return ans+1 (because you can form a new partition), otherwise return ans (continuing the current partition).", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "batchSize = 3, groups = [1,2,3,4,5,6]", + "expected_output": "4", + "explanation": "You can arrange the groups as [6,2,4,5,1,3]. Then the 1st, 2nd, 4th, and 6th groups will be happy." + }, + { + "example_num": 2, + "expected_input": "batchSize = 4, groups = [1,3,2,5,2,2,1,6]", + "expected_output": "4", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e60", + "questionid": 917, + "title": "Minimum Operations to Make the Array Increasing", + "slug": "minimum-operations-to-make-the-array-increasing", + "description": "You are given an integer array nums (0-indexed). In one operation, you can choose an element of the array and increment it by 1. Return the minimum number of operations needed to make nums strictly increasing. An array nums is strictly increasing if nums[i] < nums[i+1] for all 0 <= i < nums.length - 1. An array of length 1 is trivially strictly increasing. ", + "category": [ + "Array", + "Greedy" + ], + "complexity": "Easy", + "successrate": 78.3, + "totalsubmissions": 52341, + "totalaccepted": 40963, + "likes": 569, + "dislikes": 30, + "hints": "nums[i+1] must be at least equal to nums[i] + 1. Think greedily. You don't have to increase nums[i+1] beyond nums[i]+1. Iterate on i and set nums[i] = max(nums[i-1]+1, nums[i]) .", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,1,1]", + "expected_output": "3", + "explanation": "You can do the following operations:\r\n1) Increment nums[2], so nums becomes [1,1,2].\r\n2) Increment nums[1], so nums becomes [1,2,2].\r\n3) Increment nums[2], so nums becomes [1,2,3]." + }, + { + "example_num": 2, + "expected_input": "nums = [1,5,2,4,1]", + "expected_output": "14", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "nums = [8]", + "expected_output": "0", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e63", + "questionid": 920, + "title": "Finding the Users Active Minutes", + "slug": "finding-the-users-active-minutes", + "description": "You are given the logs for users' actions on LeetCode, and an integer k. The logs are represented by a 2D integer array logs where each logs[i] = [IDi, timei] indicates that the user with IDi performed an action at the minute timei. Multiple users can perform actions simultaneously, and a single user can perform multiple actions in the same minute. The user active minutes (UAM) for a given user is defined as the number of unique minutes in which the user performed an action on LeetCode. A minute can only be counted once, even if multiple actions occur during it. You are to calculate a 1-indexed array answer of size k such that, for each j (1 <= j <= k), answer[j] is the number of users whose UAM equals j. Return the array answer as described above. ", + "category": [ + "Array", + "Hash Table" + ], + "complexity": "Medium", + "successrate": 80.8, + "totalsubmissions": 40195, + "totalaccepted": 32468, + "likes": 410, + "dislikes": 157, + "hints": "Try to find the number of different minutes when action happened for each user. For each user increase the value of the answer array index which matches the UAM for this user.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "logs = [[0,5],[1,2],[0,2],[0,5],[1,3]], k = 5", + "expected_output": "[0,2,0,0,0]", + "explanation": "The user with ID=0 performed actions at minutes 5, 2, and 5 again. Hence, they have a UAM of 2 (minute 5 is only counted once).\nThe user with ID=1 performed actions at minutes 2 and 3. Hence, they have a UAM of 2.\nSince both users have a UAM of 2, answer[2] is 2, and the remaining answer[j] values are 0." + }, + { + "example_num": 2, + "expected_input": "logs = [[1,1],[2,2],[2,3]], k = 4", + "expected_output": "[1,1,0,0]", + "explanation": "The user with ID=1 performed a single action at minute 1. Hence, they have a UAM of 1.\nThe user with ID=2 performed actions at minutes 2 and 3. Hence, they have a UAM of 2.\nThere is one user with a UAM of 1 and one with a UAM of 2.\nHence, answer[1] = 1, answer[2] = 1, and the remaining values are 0." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e67", + "questionid": 924, + "title": "Find XOR Sum of All Pairs Bitwise AND", + "slug": "find-xor-sum-of-all-pairs-bitwise-and", + "description": "The XOR sum of a list is the bitwise XOR of all its elements. If the list only contains one element, then its XOR sum will be equal to this element. You are given two 0-indexed arrays arr1 and arr2 that consist only of non-negative integers. Consider the list containing the result of arr1[i] AND arr2[j] (bitwise AND) for every (i, j) pair where 0 <= i < arr1.length and 0 <= j < arr2.length. Return the XOR sum of the aforementioned list. ", + "category": [ + "Array", + "Math", + "Bit Manipulation" + ], + "complexity": "Hard", + "successrate": 58.7, + "totalsubmissions": 17587, + "totalaccepted": 10326, + "likes": 306, + "dislikes": 32, + "hints": "Think about (a&b) ^ (a&c). Can you simplify this expression? It is equal to a&(b^c). Then, (arr1[i]&arr2[0])^(arr1[i]&arr2[1]).. = arr1[i]&(arr2[0]^arr2[1]^arr[2]...). Let arr2XorSum = (arr2[0]^arr2[1]^arr2[2]...), arr1XorSum = (arr1[0]^arr1[1]^arr1[2]...) so the final answer is (arr2XorSum&arr1[0]) ^ (arr2XorSum&arr1[1]) ^ (arr2XorSum&arr1[2]) ^ ... = arr2XorSum & arr1XorSum.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "arr1 = [1,2,3], arr2 = [6,5]", + "expected_output": "0", + "explanation": "The list = [1 AND 6, 1 AND 5, 2 AND 6, 2 AND 5, 3 AND 6, 3 AND 5] = [0,1,2,0,2,1].\nThe XOR sum = 0 XOR 1 XOR 2 XOR 0 XOR 2 XOR 1 = 0." + }, + { + "example_num": 2, + "expected_input": "arr1 = [12], arr2 = [4]", + "expected_output": "4", + "explanation": "The list = [12 AND 4] = [4]. The XOR sum = 4." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e68", + "questionid": 925, + "title": "Sum of Digits in Base K", + "slug": "sum-of-digits-in-base-k", + "description": "Given an integer n (in base 10) and a base k, return the sum of the digits of n after converting n from base 10 to base k. After converting, each digit should be interpreted as a base 10 number, and the sum should be returned in base 10. ", + "category": [ + "Math" + ], + "complexity": "Easy", + "successrate": 76.4, + "totalsubmissions": 35662, + "totalaccepted": 27239, + "likes": 282, + "dislikes": 24, + "hints": "Convert the given number into base k. Use mod-10 to find what each digit is after the conversion and sum the digits.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 34, k = 6", + "expected_output": "9\nExplanation: 34 (base 10) expressed in base 6 is 54. 5 + 4 = 9.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "n = 10, k = 10", + "expected_output": "1\nExplanation: n is already in base 10. 1 + 0 = 1.", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e69", + "questionid": 926, + "title": "Frequency of the Most Frequent Element", + "slug": "frequency-of-the-most-frequent-element", + "description": "The frequency of an element is the number of times it occurs in an array. You are given an integer array nums and an integer k. In one operation, you can choose an index of nums and increment the element at that index by 1. Return the maximum possible frequency of an element after performing at most k operations. ", + "category": [ + "Array", + "Binary Search", + "Greedy", + "Sliding Window", + "Sorting", + "Prefix Sum" + ], + "complexity": "Medium", + "successrate": 36.6, + "totalsubmissions": 56651, + "totalaccepted": 20716, + "likes": 1162, + "dislikes": 24, + "hints": "Note that you can try all values in a brute force manner and find the maximum frequency of that value. To find the maximum frequency of a value consider the biggest elements smaller than or equal to this value", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,2,4], k = 5", + "expected_output": "3\nExplanation: Increment the first element three times and the second element two times to make nums = [4,4,4].\n4 has a frequency of 3.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "nums = [1,4,8,13], k = 5", + "expected_output": "2", + "explanation": "There are multiple optimal solutions:\n- Increment the first element three times to make nums = [4,4,8,13]. 4 has a frequency of 2.\n- Increment the second element four times to make nums = [1,8,8,13]. 8 has a frequency of 2.\n- Increment the third element five times to make nums = [1,4,13,13]. 13 has a frequency of 2." + }, + { + "example_num": 3, + "expected_input": "nums = [3,9,6], k = 2", + "expected_output": "1", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e6c", + "questionid": 929, + "title": "Minimum Distance to the Target Element", + "slug": "minimum-distance-to-the-target-element", + "description": "Given an integer array nums (0-indexed) and two integers target and start, find an index i such that nums[i] == target and abs(i - start) is minimized. Note that abs(x) is the absolute value of x. Return abs(i - start). It is guaranteed that target exists in nums. ", + "category": [ + "Array" + ], + "complexity": "Easy", + "successrate": 59.7, + "totalsubmissions": 41147, + "totalaccepted": 24574, + "likes": 172, + "dislikes": 39, + "hints": "Loop in both directions until you find the target element. For each index i such that nums[i] == target calculate abs(i - start).", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,2,3,4,5], target = 5, start = 3", + "expected_output": "1", + "explanation": "nums[4] = 5 is the only value equal to target, so the answer is abs(4 - 3) = 1." + }, + { + "example_num": 2, + "expected_input": "nums = [1], target = 1, start = 0", + "expected_output": "0", + "explanation": "nums[0] = 1 is the only value equal to target, so the answer is abs(0 - 0) = 0." + }, + { + "example_num": 3, + "expected_input": "nums = [1,1,1,1,1,1,1,1,1,1], target = 1, start = 0", + "expected_output": "0", + "explanation": "Every value of nums is 1, but nums[0] minimizes abs(i - start), which is abs(0 - 0) = 0." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e6f", + "questionid": 932, + "title": "Minimum Adjacent Swaps to Reach the Kth Smallest Number", + "slug": "minimum-adjacent-swaps-to-reach-the-kth-smallest-number", + "description": "You are given a string num, representing a large integer, and an integer k. We call some integer wonderful if it is a permutation of the digits in num and is greater in value than num. There can be many wonderful integers. However, we only care about the smallest-valued ones. Return the minimum number of adjacent digit swaps that needs to be applied to num to reach the kth smallest wonderful integer. The tests are generated in such a way that kth smallest wonderful integer exists. ", + "category": [ + "Two Pointers", + "String", + "Greedy" + ], + "complexity": "Medium", + "successrate": 72.1, + "totalsubmissions": 19150, + "totalaccepted": 13807, + "likes": 443, + "dislikes": 56, + "hints": "Find the next permutation of the given string k times. Try to move each element to its correct position and calculate the number of steps.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "num = "5489355142", k = 4", + "expected_output": "2", + "explanation": "The 4th smallest wonderful number is "5489355421". To get this number:\n- Swap index 7 with index 8: "5489355142" -> "5489355412"\n- Swap index 8 with index 9: "5489355412" -> "5489355421"" + }, + { + "example_num": 2, + "expected_input": "num = "11112", k = 4", + "expected_output": "4", + "explanation": "The 4th smallest wonderful number is "21111". To get this number:\n- Swap index 3 with index 4: "11112" -> "11121"\n- Swap index 2 with index 3: "11121" -> "11211"\n- Swap index 1 with index 2: "11211" -> "12111"\n- Swap index 0 with index 1: "12111" -> "21111"" + }, + { + "example_num": 3, + "expected_input": "num = "00123", k = 1", + "expected_output": "1", + "explanation": "The 1st smallest wonderful number is "00132". To get this number:\n- Swap index 3 with index 4: "00123" -> "00132"" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e70", + "questionid": 933, + "title": "Maximum Population Year", + "slug": "maximum-population-year", + "description": "You are given a 2D integer array logs where each logs[i] = [birthi, deathi] indicates the birth and death years of the ith person. The population of some year x is the number of people alive during that year. The ith person is counted in year x's population if x is in the inclusive range [birthi, deathi - 1]. Note that the person is not counted in the year that they die. Return the earliest year with the maximum population. ", + "category": [ + "Array", + "Counting" + ], + "complexity": "Easy", + "successrate": 58.6, + "totalsubmissions": 49364, + "totalaccepted": 28951, + "likes": 539, + "dislikes": 77, + "hints": "For each year find the number of people whose birth_i ‰¤ year and death_i > year. Find the maximum value between all years.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "logs = [[1993,1999],[2000,2010]]", + "expected_output": "1993", + "explanation": "The maximum population is 1, and 1993 is the earliest year with this population." + }, + { + "example_num": 2, + "expected_input": "logs = [[1950,1961],[1960,1971],[1970,1981]]", + "expected_output": "1960", + "explanation": "The maximum population is 2, and it had happened in years 1960 and 1970.\nThe earlier year between them is 1960." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e71", + "questionid": 934, + "title": "Maximum Distance Between a Pair of Values", + "slug": "maximum-distance-between-a-pair-of-values", + "description": "You are given two non-increasing 0-indexed integer arrays nums1 and nums2. A pair of indices (i, j), where 0 <= i < nums1.length and 0 <= j < nums2.length, is valid if both i <= j and nums1[i] <= nums2[j]. The distance of the pair is j - i. Return the maximum distance of any valid pair (i, j). If there are no valid pairs, return 0. An array arr is non-increasing if arr[i-1] >= arr[i] for every 1 <= i < arr.length. ", + "category": [ + "Array", + "Two Pointers", + "Binary Search", + "Greedy" + ], + "complexity": "Medium", + "successrate": 50, + "totalsubmissions": 43219, + "totalaccepted": 21602, + "likes": 564, + "dislikes": 11, + "hints": "Since both arrays are sorted in a non-increasing way this means that for each value in the first array. We can find the farthest value smaller than it using binary search. There is another solution using a two pointers approach since the first array is non-increasing the farthest j such that nums2[j] ‰¥ nums1[i] is at least as far as the farthest j such that nums2[j] ‰¥ nums1[i-1]", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums1 = [55,30,5,4,2], nums2 = [100,20,10,10,5]", + "expected_output": "2", + "explanation": "The valid pairs are (0,0), (2,2), (2,3), (2,4), (3,3), (3,4), and (4,4).\nThe maximum distance is 2 with pair (2,4)." + }, + { + "example_num": 2, + "expected_input": "nums1 = [2,2,2], nums2 = [10,10,1]", + "expected_output": "1", + "explanation": "The valid pairs are (0,0), (0,1), and (1,1).\nThe maximum distance is 1 with pair (0,1)." + }, + { + "example_num": 3, + "expected_input": "nums1 = [30,29,19,5], nums2 = [25,25,25,25,25]", + "expected_output": "2", + "explanation": "The valid pairs are (2,2), (2,3), (2,4), (3,3), and (3,4).\nThe maximum distance is 2 with pair (2,4)." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e72", + "questionid": 935, + "title": "Maximum Subarray Min-Product", + "slug": "maximum-subarray-min-product", + "description": "The min-product of an array is equal to the minimum value in the array multiplied by the array's sum. Given an array of integers nums, return the maximum min-product of any non-empty subarray of nums. Since the answer may be large, return it modulo 109 + 7. Note that the min-product should be maximized before performing the modulo operation. Testcases are generated such that the maximum min-product without modulo will fit in a 64-bit signed integer. A subarray is a contiguous part of an array. ", + "category": [ + "Array", + "Stack", + "Monotonic Stack", + "Prefix Sum" + ], + "complexity": "Medium", + "successrate": 35.4, + "totalsubmissions": 33411, + "totalaccepted": 11814, + "likes": 745, + "dislikes": 43, + "hints": "Is there a way we can sort the elements to simplify the problem? Can we find the maximum min-product for every value in the array?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,2,3,2]", + "expected_output": "14", + "explanation": "The maximum min-product is achieved with the subarray [2,3,2] (minimum value is 2).\n2 * (2+3+2) = 2 * 7 = 14." + }, + { + "example_num": 2, + "expected_input": "nums = [2,3,3,1,2]", + "expected_output": "18", + "explanation": "The maximum min-product is achieved with the subarray [3,3] (minimum value is 3).\n3 * (3+3) = 3 * 6 = 18." + }, + { + "example_num": 3, + "expected_input": "nums = [3,1,5,6,4,2]", + "expected_output": "60", + "explanation": "The maximum min-product is achieved with the subarray [5,6,4] (minimum value is 4).\n4 * (5+6+4) = 4 * 15 = 60." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e74", + "questionid": 937, + "title": "Substrings of Size Three with Distinct Characters", + "slug": "substrings-of-size-three-with-distinct-characters", + "description": "A string is good if there are no repeated characters. Given a string s, return the number of good substrings of length three in s. Note that if there are multiple occurrences of the same substring, every occurrence should be counted. A substring is a contiguous sequence of characters in a string. ", + "category": [ + "Hash Table", + "String", + "Sliding Window", + "Counting" + ], + "complexity": "Easy", + "successrate": 69.7, + "totalsubmissions": 57457, + "totalaccepted": 40059, + "likes": 556, + "dislikes": 19, + "hints": "Try using a set to find out the number of distinct characters in a substring.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "xyzzaz"", + "expected_output": "1", + "explanation": "There are 4 substrings of size 3: "xyz", "yzz", "zza", and "zaz". \nThe only good substring of length 3 is "xyz"." + }, + { + "example_num": 2, + "expected_input": "s = "aababcabc"", + "expected_output": "4", + "explanation": "There are 7 substrings of size 3: "aab", "aba", "bab", "abc", "bca", "cab", and "abc".\nThe good substrings are "abc", "bca", "cab", and "abc"." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e75", + "questionid": 938, + "title": "Minimum XOR Sum of Two Arrays", + "slug": "minimum-xor-sum-of-two-arrays", + "description": "You are given two integer arrays nums1 and nums2 of length n. The XOR sum of the two integer arrays is (nums1[0] XOR nums2[0]) + (nums1[1] XOR nums2[1]) + ... + (nums1[n - 1] XOR nums2[n - 1]) (0-indexed). Rearrange the elements of nums2 such that the resulting XOR sum is minimized. Return the XOR sum after the rearrangement. ", + "category": [ + "Array", + "Dynamic Programming", + "Bit Manipulation", + "Bitmask" + ], + "complexity": "Hard", + "successrate": 42.2, + "totalsubmissions": 18212, + "totalaccepted": 7684, + "likes": 401, + "dislikes": 8, + "hints": "Since n <= 14, we can consider every subset of nums2. We can represent every subset of nums2 using bitmasks.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums1 = [1,2], nums2 = [2,3]", + "expected_output": "2\nExplanation: Rearrange nums2 so that it becomes [3,2].\nThe XOR sum is (1 XOR 3) + (2 XOR 2) = 2 + 0 = 2.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "nums1 = [1,0,3], nums2 = [5,3,4]", + "expected_output": "8\nExplanation: Rearrange nums2 so that it becomes [5,4,3]. \nThe XOR sum is (1 XOR 5) + (0 XOR 4) + (3 XOR 3) = 4 + 4 + 0 = 8.", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e77", + "questionid": 940, + "title": "Number of Ways to Rearrange Sticks With K Sticks Visible", + "slug": "number-of-ways-to-rearrange-sticks-with-k-sticks-visible", + "description": "There are n uniquely-sized sticks whose lengths are integers from 1 to n. You want to arrange the sticks such that exactly k sticks are visible from the left. A stick is visible from the left if there are no longer sticks to the left of it. Given n and k, return the number of such arrangements. Since the answer may be large, return it modulo 109 + 7. ", + "category": [ + "Math", + "Dynamic Programming", + "Combinatorics" + ], + "complexity": "Hard", + "successrate": 55.3, + "totalsubmissions": 14390, + "totalaccepted": 7953, + "likes": 437, + "dislikes": 10, + "hints": "Is there a way to build the solution from a base case? How many ways are there if we fix the position of one stick?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 3, k = 2", + "expected_output": "3", + "explanation": "[1,3,2], [2,3,1], and [2,1,3] are the only arrangements such that exactly 2 sticks are visible.\nThe visible sticks are underlined." + }, + { + "example_num": 2, + "expected_input": "n = 5, k = 5", + "expected_output": "1", + "explanation": "[1,2,3,4,5] is the only arrangement such that all 5 sticks are visible.\nThe visible sticks are underlined." + }, + { + "example_num": 3, + "expected_input": "n = 20, k = 11", + "expected_output": "647427950", + "explanation": "There are 647427950 (mod 109 + 7) ways to rearrange the sticks such that exactly 11 sticks are visible." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e78", + "questionid": 941, + "title": "Longer Contiguous Segments of Ones than Zeros", + "slug": "longer-contiguous-segments-of-ones-than-zeros", + "description": "Given a binary string s, return true if the longest contiguous segment of 1's is strictly longer than the longest contiguous segment of 0's in s, or return false otherwise. Note that if there are no 0's, then the longest continuous segment of 0's is considered to have a length 0. The same applies if there is no 1's. ", + "category": [ + "String" + ], + "complexity": "Easy", + "successrate": 60.3, + "totalsubmissions": 46660, + "totalaccepted": 28113, + "likes": 281, + "dislikes": 6, + "hints": "Check every possible segment of 0s and 1s. Is there a way to iterate through the string to keep track of the current character and its count?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "1101"", + "expected_output": "true", + "explanation": "The longest contiguous segment of 1s has length 2: "1101"\nThe longest contiguous segment of 0s has length 1: "1101"\nThe segment of 1s is longer, so return true." + }, + { + "example_num": 2, + "expected_input": "s = "111000"", + "expected_output": "false", + "explanation": "The longest contiguous segment of 1s has length 3: "111000"\nThe longest contiguous segment of 0s has length 3: "111000"\nThe segment of 1s is not longer, so return false." + }, + { + "example_num": 3, + "expected_input": "s = "110100010"", + "expected_output": "false", + "explanation": "The longest contiguous segment of 1s has length 2: "110100010"\nThe longest contiguous segment of 0s has length 3: "110100010"\nThe segment of 1s is not longer, so return false." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e79", + "questionid": 942, + "title": "Minimum Speed to Arrive on Time", + "slug": "minimum-speed-to-arrive-on-time", + "description": "You are given a floating-point number hour, representing the amount of time you have to reach the office. To commute to the office, you must take n trains in sequential order. You are also given an integer array dist of length n, where dist[i] describes the distance (in kilometers) of the ith train ride. Each train can only depart at an integer hour, so you may need to wait in between each train ride. Return the minimum positive integer speed (in kilometers per hour) that all the trains must travel at for you to reach the office on time, or -1 if it is impossible to be on time. Tests are generated such that the answer will not exceed 107 and hour will have at most two digits after the decimal point. ", + "category": [ + "Array", + "Binary Search" + ], + "complexity": "Medium", + "successrate": 35.6, + "totalsubmissions": 49620, + "totalaccepted": 17647, + "likes": 459, + "dislikes": 76, + "hints": "Given the speed the trains are traveling at, can you find the total time it takes for you to arrive? Is there a cutoff where any speeds larger will always allow you to arrive on time?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "dist = [1,3,2], hour = 6", + "expected_output": "1\nExplanation: At speed 1:\n- The first train ride takes 1/1 = 1 hour.\n- Since we are already at an integer hour, we depart immediately at the 1 hour mark. The second train takes 3/1 = 3 hours.\n- Since we are already at an integer hour, we depart immediately at the 4 hour mark. The third train takes 2/1 = 2 hours.\n- You will arrive at exactly the 6 hour mark.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "dist = [1,3,2], hour = 2.7", + "expected_output": "3\nExplanation: At speed 3:\n- The first train ride takes 1/3 = 0.33333 hours.\n- Since we are not at an integer hour, we wait until the 1 hour mark to depart. The second train ride takes 3/3 = 1 hour.\n- Since we are already at an integer hour, we depart immediately at the 2 hour mark. The third train takes 2/3 = 0.66667 hours.\n- You will arrive at the 2.66667 hour mark.", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "dist = [1,3,2], hour = 1.9", + "expected_output": "-1", + "explanation": "It is impossible because the earliest the third train can depart is at the 2 hour mark." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e7a", + "questionid": 943, + "title": "Check if All the Integers in a Range Are Covered", + "slug": "check-if-all-the-integers-in-a-range-are-covered", + "description": "You are given a 2D integer array ranges and two integers left and right. Each ranges[i] = [starti, endi] represents an inclusive interval between starti and endi. Return true if each integer in the inclusive range [left, right] is covered by at least one interval in ranges. Return false otherwise. An integer x is covered by an interval ranges[i] = [starti, endi] if starti <= x <= endi. ", + "category": [ + "Array", + "Hash Table", + "Prefix Sum" + ], + "complexity": "Easy", + "successrate": 50.7, + "totalsubmissions": 40622, + "totalaccepted": 20609, + "likes": 252, + "dislikes": 56, + "hints": "Iterate over every integer point in the range [left, right]. For each of these points check if it is included in one of the ranges.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "ranges = [[1,2],[3,4],[5,6]], left = 2, right = 5", + "expected_output": "true", + "explanation": "Every integer between 2 and 5 is covered:\n- 2 is covered by the first range.\n- 3 and 4 are covered by the second range.\n- 5 is covered by the third range." + }, + { + "example_num": 2, + "expected_input": "ranges = [[1,10],[10,20]], left = 21, right = 21", + "expected_output": "false", + "explanation": "21 is not covered by any range." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e7b", + "questionid": 944, + "title": "Find the Student that Will Replace the Chalk", + "slug": "find-the-student-that-will-replace-the-chalk", + "description": "There are n students in a class numbered from 0 to n - 1. The teacher will give each student a problem starting with the student number 0, then the student number 1, and so on until the teacher reaches the student number n - 1. After that, the teacher will restart the process, starting with the student number 0 again. You are given a 0-indexed integer array chalk and an integer k. There are initially k pieces of chalk. When the student number i is given a problem to solve, they will use chalk[i] pieces of chalk to solve that problem. However, if the current number of chalk pieces is strictly less than chalk[i], then the student number i will be asked to replace the chalk. Return the index of the student that will replace the chalk. ", + "category": [ + "Array", + "Binary Search", + "Simulation", + "Prefix Sum" + ], + "complexity": "Medium", + "successrate": 41.3, + "totalsubmissions": 40798, + "totalaccepted": 16834, + "likes": 248, + "dislikes": 36, + "hints": "Subtract the sum of chalk[i] from k until k is less than that sum Now just iterate over the array if chalk[i] is less thank k this is your answer otherwise this i is the answer", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "chalk = [5,1,5], k = 22", + "expected_output": "0\nExplanation: The students go in turns as follows:\n- Student number 0 uses 5 chalk, so k = 17.\n- Student number 1 uses 1 chalk, so k = 16.\n- Student number 2 uses 5 chalk, so k = 11.\n- Student number 0 uses 5 chalk, so k = 6.\n- Student number 1 uses 1 chalk, so k = 5.\n- Student number 2 uses 5 chalk, so k = 0.\nStudent number 0 does not have enough chalk, so they will have to replace it.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "chalk = [3,4,1,2], k = 25", + "expected_output": "1\nExplanation: The students go in turns as follows:\n- Student number 0 uses 3 chalk so k = 22.\n- Student number 1 uses 4 chalk so k = 18.\n- Student number 2 uses 1 chalk so k = 17.\n- Student number 3 uses 2 chalk so k = 15.\n- Student number 0 uses 3 chalk so k = 12.\n- Student number 1 uses 4 chalk so k = 8.\n- Student number 2 uses 1 chalk so k = 7.\n- Student number 3 uses 2 chalk so k = 5.\n- Student number 0 uses 3 chalk so k = 2.\nStudent number 1 does not have enough chalk, so they will have to replace it.", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e7d", + "questionid": 946, + "title": "Maximum Value after Insertion", + "slug": "maximum-value-after-insertion", + "description": "You are given a very large integer n, represented as a string, and an integer digit x. The digits in n and the digit x are in the inclusive range [1, 9], and n may represent a negative number. You want to maximize n's numerical value by inserting x anywhere in the decimal representation of n. You cannot insert x to the left of the negative sign. Return a string representing the maximum value of n after the insertion. ", + "category": [ + "String", + "Greedy" + ], + "complexity": "Medium", + "successrate": 35.8, + "totalsubmissions": 49400, + "totalaccepted": 17697, + "likes": 238, + "dislikes": 41, + "hints": "Note that if the number is negative it's the same as positive but you look for the minimum instead. In the case of maximum, if s[i] < x it's optimal that x is put before s[i]. In the case of minimum, if s[i] > x it's optimal that x is put before s[i].", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = "99", x = 9", + "expected_output": ""999"", + "explanation": "The result is the same regardless of where you insert 9." + }, + { + "example_num": 2, + "expected_input": "n = "-13", x = 2", + "expected_output": ""-123"", + "explanation": "You can make n one of {-213, -123, -132}, and the largest of those three is -123." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e50", + "questionid": 901, + "title": "Minimum Number of Operations to Move All Balls to Each Box", + "slug": "minimum-number-of-operations-to-move-all-balls-to-each-box", + "description": "You have n boxes. You are given a binary string boxes of length n, where boxes[i] is '0' if the ith box is empty, and '1' if it contains one ball. In one operation, you can move one ball from a box to an adjacent box. Box i is adjacent to box j if abs(i - j) == 1. Note that after doing so, there may be more than one ball in some boxes. Return an array answer of size n, where answer[i] is the minimum number of operations needed to move all the balls to the ith box. Each answer[i] is calculated considering the initial state of the boxes. ", + "category": [ + "Array", + "String" + ], + "complexity": "Medium", + "successrate": 85.7, + "totalsubmissions": 83851, + "totalaccepted": 71875, + "likes": 1341, + "dislikes": 50, + "hints": "If you want to move a ball from box i to box j, you'll need abs(i-j) moves. To move all balls to some box, you can move them one by one. For each box i, iterate on each ball in a box j, and add abs(i-j) to answers[i].", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "boxes = "110"", + "expected_output": "[1,1,3]", + "explanation": "The answer for each box is as follows:\n1) First box: you will have to move one ball from the second box to the first box in one operation.\n2) Second box: you will have to move one ball from the first box to the second box in one operation.\n3) Third box: you will have to move one ball from the first box to the third box in two operations, and move one ball from the second box to the third box in one operation." + }, + { + "example_num": 2, + "expected_input": "boxes = "001011"", + "expected_output": "[11,8,5,4,3,4]", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e53", + "questionid": 904, + "title": "Count Pairs With XOR in a Range", + "slug": "count-pairs-with-xor-in-a-range", + "description": "Given a (0-indexed) integer array nums and two integers low and high, return the number of nice pairs. A nice pair is a pair (i, j) where 0 <= i < j < nums.length and low <= (nums[i] XOR nums[j]) <= high. ", + "category": [ + "Array", + "Bit Manipulation", + "Trie" + ], + "complexity": "Hard", + "successrate": 46.3, + "totalsubmissions": 9859, + "totalaccepted": 4565, + "likes": 277, + "dislikes": 11, + "hints": "Let's note that we can count all pairs with XOR ‰¤ K, so the answer would be to subtract the number of pairs withs XOR < low from the number of pairs with XOR ‰¤ high. For each value, find out the number of values when you XOR it with the result is ‰¤ K using a trie.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,4,2,7], low = 2, high = 6", + "expected_output": "6", + "explanation": "All nice pairs (i, j) are as follows:\r\n - (0, 1): nums[0] XOR nums[1] = 5 \r\n - (0, 2): nums[0] XOR nums[2] = 3\r\n - (0, 3): nums[0] XOR nums[3] = 6\r\n - (1, 2): nums[1] XOR nums[2] = 6\r\n - (1, 3): nums[1] XOR nums[3] = 3\r\n - (2, 3): nums[2] XOR nums[3] = 5" + }, + { + "example_num": 2, + "expected_input": "nums = [9,8,4,2,1], low = 5, high = 14", + "expected_output": "8", + "explanation": "All nice pairs (i, j) are as follows:\r\n​​​​​ - (0, 2): nums[0] XOR nums[2] = 13\r\n  - (0, 3): nums[0] XOR nums[3] = 11\r\n  - (0, 4): nums[0] XOR nums[4] = 8\r\n  - (1, 2): nums[1] XOR nums[2] = 12\r\n  - (1, 3): nums[1] XOR nums[3] = 10\r\n  - (1, 4): nums[1] XOR nums[4] = 9\r\n  - (2, 3): nums[2] XOR nums[3] = 6\r\n  - (2, 4): nums[2] XOR nums[4] = 5" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e55", + "questionid": 906, + "title": "Minimum Elements to Add to Form a Given Sum", + "slug": "minimum-elements-to-add-to-form-a-given-sum", + "description": "You are given an integer array nums and two integers limit and goal. The array nums has an interesting property that abs(nums[i]) <= limit. Return the minimum number of elements you need to add to make the sum of the array equal to goal. The array must maintain its property that abs(nums[i]) <= limit. Note that abs(x) equals x if x >= 0, and -x otherwise. ", + "category": [ + "Array", + "Greedy" + ], + "complexity": "Medium", + "successrate": 41.6, + "totalsubmissions": 33964, + "totalaccepted": 14123, + "likes": 150, + "dislikes": 145, + "hints": "Try thinking about the problem as if the array is empty. Then you only need to form goal using elements whose absolute value is <= limit. You can greedily set all of the elements except one to limit or -limit, so the number of elements you need is ceil(abs(goal)/ limit). You can \"normalize\" goal by offsetting it by the sum of the array. For example, if the goal is 5 and the sum is -3, then it's exactly the same as if the goal is 8 and the array is empty. The answer is ceil(abs(goal-sum)/limit) = (abs(goal-sum)+limit-1) / limit.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,-1,1], limit = 3, goal = -4", + "expected_output": "2", + "explanation": "You can add -2 and -3, then the sum of the array will be 1 - 1 + 1 - 2 - 3 = -4." + }, + { + "example_num": 2, + "expected_input": "nums = [1,-10,9,1], limit = 100, goal = 0", + "expected_output": "1", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e58", + "questionid": 909, + "title": "Find Center of Star Graph", + "slug": "find-center-of-star-graph", + "description": "There is an undirected star graph consisting of n nodes labeled from 1 to n. A star graph is a graph where there is one center node and exactly n - 1 edges that connect the center node with every other node. You are given a 2D integer array edges where each edges[i] = [ui, vi] indicates that there is an edge between the nodes ui and vi. Return the center of the given star graph. ", + "category": [ + "Graph" + ], + "complexity": "Easy", + "successrate": 83.6, + "totalsubmissions": 93407, + "totalaccepted": 78108, + "likes": 530, + "dislikes": 70, + "hints": "The center is the only node that has more than one edge. The center is also connected to all other nodes. Any two edges must have a common node, which is the center.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "edges = [[1,2],[2,3],[4,2]]", + "expected_output": "2", + "explanation": "As shown in the figure above, node 2 is connected to every other node, so 2 is the center." + }, + { + "example_num": 2, + "expected_input": "edges = [[1,2],[5,1],[1,3],[1,4]]", + "expected_output": "1", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e5b", + "questionid": 912, + "title": "Determine Color of a Chessboard Square", + "slug": "determine-color-of-a-chessboard-square", + "description": "You are given coordinates, a string that represents the coordinates of a square of the chessboard. Below is a chessboard for your reference. Return true if the square is white, and false if the square is black. The coordinate will always represent a valid chessboard square. The coordinate will always have the letter first, and the number second. ", + "category": [ + "Math", + "String" + ], + "complexity": "Easy", + "successrate": 77.7, + "totalsubmissions": 45757, + "totalaccepted": 35535, + "likes": 403, + "dislikes": 13, + "hints": "Convert the coordinates to (x, y) - that is, \"a1\" is (1, 1), \"d7\" is (4, 7). Try add the numbers together and look for a pattern.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "coordinates = "a1"", + "expected_output": "false", + "explanation": "From the chessboard above, the square with coordinates "a1" is black, so return false." + }, + { + "example_num": 2, + "expected_input": "coordinates = "h3"", + "expected_output": "true", + "explanation": "From the chessboard above, the square with coordinates "h3" is white, so return true." + }, + { + "example_num": 3, + "expected_input": "coordinates = "c7"", + "expected_output": "false", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e61", + "questionid": 918, + "title": "Queries on Number of Points Inside a Circle", + "slug": "queries-on-number-of-points-inside-a-circle", + "description": "You are given an array points where points[i] = [xi, yi] is the coordinates of the ith point on a 2D plane. Multiple points can have the same coordinates. You are also given an array queries where queries[j] = [xj, yj, rj] describes a circle centered at (xj, yj) with a radius of rj. For each query queries[j], compute the number of points inside the jth circle. Points on the border of the circle are considered inside. Return an array answer, where answer[j] is the answer to the jth query. ", + "category": [ + "Array", + "Math", + "Geometry" + ], + "complexity": "Medium", + "successrate": 86.6, + "totalsubmissions": 43513, + "totalaccepted": 37679, + "likes": 533, + "dislikes": 53, + "hints": "For a point to be inside a circle, the euclidean distance between it and the circle's center needs to be less than or equal to the radius. Brute force for each circle and iterate overall points and find those inside it.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "points = [[1,3],[3,3],[5,3],[2,2]], queries = [[2,3,1],[4,3,1],[1,1,2]]", + "expected_output": "[3,2,2]\nExplanation: The points and circles are shown above.\nqueries[0] is the green circle, queries[1] is the red circle, and queries[2] is the blue circle.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "points = [[1,1],[2,2],[3,3],[4,4],[5,5]], queries = [[1,2,2],[2,2,2],[4,3,2],[4,3,3]]", + "expected_output": "[2,3,2,4]\nExplanation: The points and circles are shown above.\nqueries[0] is green, queries[1] is red, queries[2] is blue, and queries[3] is purple.", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e62", + "questionid": 919, + "title": "Truncate Sentence", + "slug": "truncate-sentence", + "description": "A sentence is a list of words that are separated by a single space with no leading or trailing spaces. Each of the words consists of only uppercase and lowercase English letters (no punctuation). You are given a sentence s and an integer k. You want to truncate s such that it contains only the first k words. Return s after truncating it. ", + "category": [ + "Array", + "String" + ], + "complexity": "Easy", + "successrate": 81.3, + "totalsubmissions": 72039, + "totalaccepted": 58571, + "likes": 475, + "dislikes": 15, + "hints": "It's easier to solve this problem on an array of strings so parse the string to an array of words After return the first k words as a sentence", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "Hello how are you Contestant", k = 4", + "expected_output": ""Hello how are you"", + "explanation": "The words in s are ["Hello", "how" "are", "you", "Contestant"].\nThe first 4 words are ["Hello", "how", "are", "you"].\nHence, you should return "Hello how are you"." + }, + { + "example_num": 2, + "expected_input": "s = "What is the solution to this problem", k = 4", + "expected_output": ""What is the solution"", + "explanation": "The words in s are ["What", "is" "the", "solution", "to", "this", "problem"].\nThe first 4 words are ["What", "is", "the", "solution"].\nHence, you should return "What is the solution"." + }, + { + "example_num": 3, + "expected_input": "s = "chopper is not a tanuki", k = 5", + "expected_output": ""chopper is not a tanuki"", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e6b", + "questionid": 928, + "title": "Incremental Memory Leak", + "slug": "incremental-memory-leak", + "description": "You are given two integers memory1 and memory2 representing the available memory in bits on two memory sticks. There is currently a faulty program running that consumes an increasing amount of memory every second. At the ith second (starting from 1), i bits of memory are allocated to the stick with more available memory (or from the first memory stick if both have the same available memory). If neither stick has at least i bits of available memory, the program crashes. Return an array containing [crashTime, memory1crash, memory2crash], where crashTime is the time (in seconds) when the program crashed and memory1crash and memory2crash are the available bits of memory in the first and second sticks respectively. ", + "category": [ + "Simulation" + ], + "complexity": "Medium", + "successrate": 71, + "totalsubmissions": 17187, + "totalaccepted": 12204, + "likes": 133, + "dislikes": 58, + "hints": "What is the upper bound for the number of seconds? Simulate the process of allocating memory.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "memory1 = 2, memory2 = 2", + "expected_output": "[3,1,0]", + "explanation": "The memory is allocated as follows:\n- At the 1st second, 1 bit of memory is allocated to stick 1. The first stick now has 1 bit of available memory.\n- At the 2nd second, 2 bits of memory are allocated to stick 2. The second stick now has 0 bits of available memory.\n- At the 3rd second, the program crashes. The sticks have 1 and 0 bits available respectively." + }, + { + "example_num": 2, + "expected_input": "memory1 = 8, memory2 = 11", + "expected_output": "[6,0,4]", + "explanation": "The memory is allocated as follows:\n- At the 1st second, 1 bit of memory is allocated to stick 2. The second stick now has 10 bit of available memory.\n- At the 2nd second, 2 bits of memory are allocated to stick 2. The second stick now has 8 bits of available memory.\n- At the 3rd second, 3 bits of memory are allocated to stick 1. The first stick now has 5 bits of available memory.\n- At the 4th second, 4 bits of memory are allocated to stick 2. The second stick now has 4 bits of available memory.\n- At the 5th second, 5 bits of memory are allocated to stick 1. The first stick now has 0 bits of available memory.\n- At the 6th second, the program crashes. The sticks have 0 and 4 bits available respectively." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e6e", + "questionid": 931, + "title": "Minimum Interval to Include Each Query", + "slug": "minimum-interval-to-include-each-query", + "description": "You are given a 2D integer array intervals, where intervals[i] = [lefti, righti] describes the ith interval starting at lefti and ending at righti (inclusive). The size of an interval is defined as the number of integers it contains, or more formally righti - lefti + 1. You are also given an integer array queries. The answer to the jth query is the size of the smallest interval i such that lefti <= queries[j] <= righti. If no such interval exists, the answer is -1. Return an array containing the answers to the queries. ", + "category": [ + "Array", + "Binary Search", + "Line Sweep", + "Sorting", + "Heap (Priority Queue)" + ], + "complexity": "Hard", + "successrate": 45.5, + "totalsubmissions": 14492, + "totalaccepted": 6599, + "likes": 336, + "dislikes": 6, + "hints": "Is there a way to order the intervals and queries such that it takes less time to query? Is there a way to add and remove intervals by going from the smallest query to the largest query to find the minimum size?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "intervals = [[1,4],[2,4],[3,6],[4,4]], queries = [2,3,4,5]", + "expected_output": "[3,3,1,4]", + "explanation": "The queries are processed as follows:\n- Query = 2: The interval [2,4] is the smallest interval containing 2. The answer is 4 - 2 + 1 = 3.\n- Query = 3: The interval [2,4] is the smallest interval containing 3. The answer is 4 - 2 + 1 = 3.\n- Query = 4: The interval [4,4] is the smallest interval containing 4. The answer is 4 - 4 + 1 = 1.\n- Query = 5: The interval [3,6] is the smallest interval containing 5. The answer is 6 - 3 + 1 = 4." + }, + { + "example_num": 2, + "expected_input": "intervals = [[2,3],[2,5],[1,8],[20,25]], queries = [2,19,5,22]", + "expected_output": "[2,-1,4,6]", + "explanation": "The queries are processed as follows:\n- Query = 2: The interval [2,3] is the smallest interval containing 2. The answer is 3 - 2 + 1 = 2.\n- Query = 19: None of the intervals contain 19. The answer is -1.\n- Query = 5: The interval [2,5] is the smallest interval containing 5. The answer is 5 - 2 + 1 = 4.\n- Query = 22: The interval [20,25] is the smallest interval containing 22. The answer is 25 - 20 + 1 = 6." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e7c", + "questionid": 945, + "title": "Check if Word Equals Summation of Two Words", + "slug": "check-if-word-equals-summation-of-two-words", + "description": "The letter value of a letter is its position in the alphabet starting from 0 (i.e. 'a' -> 0, 'b' -> 1, 'c' -> 2, etc.). The numerical value of some string of lowercase English letters s is the concatenation of the letter values of each letter in s, which is then converted into an integer. You are given three strings firstWord, secondWord, and targetWord, each consisting of lowercase English letters 'a' through 'j' inclusive. Return true if the summation of the numerical values of firstWord and secondWord equals the numerical value of targetWord, or false otherwise. ", + "category": [ + "String" + ], + "complexity": "Easy", + "successrate": 73.2, + "totalsubmissions": 53107, + "totalaccepted": 38861, + "likes": 321, + "dislikes": 20, + "hints": "Convert each character of each word to its numerical value. Check if the numerical values satisfies the condition.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "firstWord = "acb", secondWord = "cba", targetWord = "cdb"", + "expected_output": "true", + "explanation": "The numerical value of firstWord is "acb" -> "021" -> 21.\nThe numerical value of secondWord is "cba" -> "210" -> 210.\nThe numerical value of targetWord is "cdb" -> "231" -> 231.\nWe return true because 21 + 210 == 231." + }, + { + "example_num": 2, + "expected_input": "firstWord = "aaa", secondWord = "a", targetWord = "aab"", + "expected_output": "false", + "explanation": "The numerical value of firstWord is "aaa" -> "000" -> 0.\nThe numerical value of secondWord is "a" -> "0" -> 0.\nThe numerical value of targetWord is "aab" -> "001" -> 1.\nWe return false because 0 + 0 != 1." + }, + { + "example_num": 3, + "expected_input": "firstWord = "aaa", secondWord = "a", targetWord = "aaaa"", + "expected_output": "true", + "explanation": "The numerical value of firstWord is "aaa" -> "000" -> 0.\nThe numerical value of secondWord is "a" -> "0" -> 0.\nThe numerical value of targetWord is "aaaa" -> "0000" -> 0.\nWe return true because 0 + 0 == 0." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e7e", + "questionid": 947, + "title": "Process Tasks Using Servers", + "slug": "process-tasks-using-servers", + "description": "You are given two 0-indexed integer arrays servers and tasks of lengths n and m respectively. servers[i] is the weight of the i server, and tasks[j] is the time needed to process the j task in seconds. Tasks are assigned to the servers using a task queue. Initially, all servers are free, and the queue is empty. At second j, the jth task is inserted into the queue (starting with the 0th task being inserted at second 0). As long as there are free servers and the queue is not empty, the task in the front of the queue will be assigned to a free server with the smallest weight, and in case of a tie, it is assigned to a free server with the smallest index. If there are no free servers and the queue is not empty, we wait until a server becomes free and immediately assign the next task. If multiple servers become free at the same time, then multiple tasks from the queue will be assigned in order of insertion following the weight and index priorities above. A server that is assigned task j at second t will be free again at second t + tasks[j]. Build an array ans of length m, where ans[j] is the index of the server the jth task will be assigned to. Return the array ans. ", + "category": [ + "Array", + "Heap (Priority Queue)" + ], + "complexity": "Medium", + "successrate": 37.4, + "totalsubmissions": 44636, + "totalaccepted": 16674, + "likes": 551, + "dislikes": 165, + "hints": "You can maintain a Heap of available Servers and a Heap of unavailable servers Note that the tasks will be processed in the input order so you just need to find the x-th server that will be available according to the rules", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "servers = [3,3,2], tasks = [1,2,3,2,1,2]", + "expected_output": "[2,2,0,2,1,2]\nExplanation: Events in chronological order go as follows:\n- At second 0, task 0 is added and processed using server 2 until second 1.\n- At second 1, server 2 becomes free. Task 1 is added and processed using server 2 until second 3.\n- At second 2, task 2 is added and processed using server 0 until second 5.\n- At second 3, server 2 becomes free. Task 3 is added and processed using server 2 until second 5.\n- At second 4, task 4 is added and processed using server 1 until second 5.\n- At second 5, all servers become free. Task 5 is added and processed using server 2 until second 7.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "servers = [5,1,4,3,2], tasks = [2,1,2,4,5,2,1]", + "expected_output": "[1,4,1,4,1,3,2]\nExplanation: Events in chronological order go as follows: \n- At second 0, task 0 is added and processed using server 1 until second 2.\n- At second 1, task 1 is added and processed using server 4 until second 2.\n- At second 2, servers 1 and 4 become free. Task 2 is added and processed using server 1 until second 4. \n- At second 3, task 3 is added and processed using server 4 until second 7.\n- At second 4, server 1 becomes free. Task 4 is added and processed using server 1 until second 9. \n- At second 5, task 5 is added and processed using server 3 until second 7.\n- At second 6, task 6 is added and processed using server 2 until second 7.", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e7f", + "questionid": 948, + "title": "Minimum Skips to Arrive at Meeting On Time", + "slug": "minimum-skips-to-arrive-at-meeting-on-time", + "description": "You are given an integer hoursBefore, the number of hours you have to travel to your meeting. To arrive at your meeting, you have to travel through n roads. The road lengths are given as an integer array dist of length n, where dist[i] describes the length of the ith road in kilometers. In addition, you are given an integer speed, which is the speed (in km/h) you will travel at. After you travel road i, you must rest and wait for the next integer hour before you can begin traveling on the next road. Note that you do not have to rest after traveling the last road because you are already at the meeting. However, you are allowed to skip some rests to be able to arrive on time, meaning you do not need to wait for the next integer hour. Note that this means you may finish traveling future roads at different hour marks. Return the minimum number of skips required to arrive at the meeting on time, or -1 if it is impossible. ", + "category": [ + "Array", + "Dynamic Programming" + ], + "complexity": "Hard", + "successrate": 38.6, + "totalsubmissions": 11818, + "totalaccepted": 4559, + "likes": 210, + "dislikes": 39, + "hints": "Is there something you can keep track of from one road to another? How would knowing the start time for each state help us solve the problem?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "dist = [1,3,2], speed = 4, hoursBefore = 2", + "expected_output": "1", + "explanation": "Without skipping any rests, you will arrive in (1/4 + 3/4) + (3/4 + 1/4) + (2/4) = 2.5 hours.\nYou can skip the first rest to arrive in ((1/4 + 0) + (3/4 + 0)) + (2/4) = 1.5 hours.\nNote that the second rest is shortened because you finish traveling the second road at an integer hour due to skipping the first rest." + }, + { + "example_num": 2, + "expected_input": "dist = [7,3,5,5], speed = 2, hoursBefore = 10", + "expected_output": "2", + "explanation": "Without skipping any rests, you will arrive in (7/2 + 1/2) + (3/2 + 1/2) + (5/2 + 1/2) + (5/2) = 11.5 hours.\nYou can skip the first and third rest to arrive in ((7/2 + 0) + (3/2 + 0)) + ((5/2 + 0) + (5/2)) = 10 hours." + }, + { + "example_num": 3, + "expected_input": "dist = [7,3,5,5], speed = 1, hoursBefore = 10", + "expected_output": "-1", + "explanation": "It is impossible to arrive at the meeting on time even if you skip all the rests." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e81", + "questionid": 950, + "title": "Minimum Space Wasted From Packaging", + "slug": "minimum-space-wasted-from-packaging", + "description": "You have n packages that you are trying to place in boxes, one package in each box. There are m suppliers that each produce boxes of different sizes (with infinite supply). A package can be placed in a box if the size of the package is less than or equal to the size of the box. The package sizes are given as an integer array packages, where packages[i] is the size of the ith package. The suppliers are given as a 2D integer array boxes, where boxes[j] is an array of box sizes that the jth supplier produces. You want to choose a single supplier and use boxes from them such that the total wasted space is minimized. For each package in a box, we define the space wasted to be size of the box - size of the package. The total wasted space is the sum of the space wasted in all the boxes. Return the minimum total wasted space by choosing the box supplier optimally, or -1 if it is impossible to fit all the packages inside boxes. Since the answer may be large, return it modulo 109 + 7. ", + "category": [ + "Array", + "Binary Search", + "Sorting", + "Prefix Sum" + ], + "complexity": "Hard", + "successrate": 30, + "totalsubmissions": 25170, + "totalaccepted": 7560, + "likes": 239, + "dislikes": 27, + "hints": "Given a fixed size box, is there a way to quickly query which packages (i.e., count and sizes) should end up in that box size? Do we have to order the boxes a certain way to allow us to answer the query quickly?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "packages = [2,3,5], boxes = [[4,8],[2,8]]", + "expected_output": "6\nExplanation: It is optimal to choose the first supplier, using two size-4 boxes and one size-8 box.\nThe total waste is (4-2) + (4-3) + (8-5) = 6.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "packages = [2,3,5], boxes = [[1,4],[2,3],[3,4]]", + "expected_output": "-1", + "explanation": "There is no box that the package of size 5 can fit in." + }, + { + "example_num": 3, + "expected_input": "packages = [3,5,8,10,11,12], boxes = [[12],[11,9],[10,5,14]]", + "expected_output": "9", + "explanation": "It is optimal to choose the third supplier, using two size-5 boxes, two size-10 boxes, and two size-14 boxes.\nThe total waste is (5-3) + (5-5) + (10-8) + (10-10) + (14-11) + (14-12) = 9." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e83", + "questionid": 952, + "title": "Maximum Alternating Subsequence Sum", + "slug": "maximum-alternating-subsequence-sum", + "description": "The alternating sum of a 0-indexed array is defined as the sum of the elements at even indices minus the sum of the elements at odd indices. Given an array nums, return the maximum alternating sum of any subsequence of nums (after reindexing the elements of the subsequence). A subsequence of an array is a new array generated from the original array by deleting some elements (possibly none) without changing the remaining elements' relative order. For example, [2,7,4] is a subsequence of [4,2,3,7,2,1,4] (the underlined elements), while [2,4,2] is not. ", + "category": [ + "Array", + "Dynamic Programming" + ], + "complexity": "Medium", + "successrate": 59.1, + "totalsubmissions": 25840, + "totalaccepted": 15277, + "likes": 635, + "dislikes": 11, + "hints": "Is only tracking a single sum enough to solve the problem? How does tracking an odd sum and an even sum reduce the number of states?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [4,2,5,3]", + "expected_output": "7", + "explanation": "It is optimal to choose the subsequence [4,2,5] with alternating sum (4 + 5) - 2 = 7." + }, + { + "example_num": 2, + "expected_input": "nums = [5,6,7,8]", + "expected_output": "8", + "explanation": "It is optimal to choose the subsequence [8] with alternating sum 8." + }, + { + "example_num": 3, + "expected_input": "nums = [6,2,1,2,4,5]", + "expected_output": "10", + "explanation": "It is optimal to choose the subsequence [6,1,5] with alternating sum (6 + 5) - 1 = 10." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e8d", + "questionid": 962, + "title": "Maximum Product Difference Between Two Pairs", + "slug": "maximum-product-difference-between-two-pairs", + "description": "The product difference between two pairs (a, b) and (c, d) is defined as (a * b) - (c * d). Given an integer array nums, choose four distinct indices w, x, y, and z such that the product difference between pairs (nums[w], nums[x]) and (nums[y], nums[z]) is maximized. Return the maximum such product difference. ", + "category": [ + "Array", + "Sorting" + ], + "complexity": "Easy", + "successrate": 81.3, + "totalsubmissions": 58929, + "totalaccepted": 47905, + "likes": 401, + "dislikes": 20, + "hints": "If you only had to find the maximum product of 2 numbers in an array, which 2 numbers should you choose? We only need to worry about 4 numbers in the array.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [5,6,2,7,4]", + "expected_output": "34", + "explanation": "We can choose indices 1 and 3 for the first pair (6, 7) and indices 2 and 4 for the second pair (2, 4).\r\nThe product difference is (6 * 7) - (2 * 4) = 34." + }, + { + "example_num": 2, + "expected_input": "nums = [4,2,5,9,7,4,8]", + "expected_output": "64", + "explanation": "We can choose indices 3 and 6 for the first pair (9, 8) and indices 1 and 5 for the second pair (2, 4).\r\nThe product difference is (9 * 8) - (2 * 4) = 64." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e91", + "questionid": 966, + "title": "Eliminate Maximum Number of Monsters", + "slug": "eliminate-maximum-number-of-monsters", + "description": "You are playing a video game where you are defending your city from a group of n monsters. You are given a 0-indexed integer array dist of size n, where dist[i] is the initial distance in kilometers of the ith monster from the city. The monsters walk toward the city at a constant speed. The speed of each monster is given to you in an integer array speed of size n, where speed[i] is the speed of the ith monster in kilometers per minute. You have a weapon that, once fully charged, can eliminate a single monster. However, the weapon takes one minute to charge.The weapon is fully charged at the very start. You lose when any monster reaches your city. If a monster reaches the city at the exact moment the weapon is fully charged, it counts as a loss, and the game ends before you can use your weapon. Return the maximum number of monsters that you can eliminate before you lose, or n if you can eliminate all the monsters before they reach the city. ", + "category": [ + "Array", + "Greedy", + "Sorting" + ], + "complexity": "Medium", + "successrate": 37.6, + "totalsubmissions": 42275, + "totalaccepted": 15880, + "likes": 306, + "dislikes": 48, + "hints": "Find the amount of time it takes each monster to arrive. Find the order in which the monsters will arrive.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "dist = [1,3,4], speed = [1,1,1]", + "expected_output": "3", + "explanation": "In the beginning, the distances of the monsters are [1,3,4]. You eliminate the first monster.\nAfter a minute, the distances of the monsters are [X,2,3]. You eliminate the second monster.\nAfter a minute, the distances of the monsters are [X,X,2]. You eliminate the third monster.\nAll 3 monsters can be eliminated." + }, + { + "example_num": 2, + "expected_input": "dist = [1,1,2,3], speed = [1,1,1,1]", + "expected_output": "1", + "explanation": "In the beginning, the distances of the monsters are [1,1,2,3]. You eliminate the first monster.\nAfter a minute, the distances of the monsters are [X,0,1,2], so you lose.\nYou can only eliminate 1 monster." + }, + { + "example_num": 3, + "expected_input": "dist = [3,2,4], speed = [5,3,2]", + "expected_output": "1", + "explanation": "In the beginning, the distances of the monsters are [3,2,4]. You eliminate the first monster.\nAfter a minute, the distances of the monsters are [X,0,2], so you lose.\nYou can only eliminate 1 monster." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e93", + "questionid": 968, + "title": "Longest Common Subpath", + "slug": "longest-common-subpath", + "description": "There is a country of n cities numbered from 0 to n - 1. In this country, there is a road connecting every pair of cities. There are m friends numbered from 0 to m - 1 who are traveling through the country. Each one of them will take a path consisting of some cities. Each path is represented by an integer array that contains the visited cities in order. The path may contain a city more than once, but the same city will not be listed consecutively. Given an integer n and a 2D integer array paths where paths[i] is an integer array representing the path of the ith friend, return the length of the longest common subpath that is shared by every friend's path, or 0 if there is no common subpath at all. A subpath of a path is a contiguous sequence of cities within that path. ", + "category": [ + "Array", + "Binary Search", + "Rolling Hash", + "Suffix Array", + "Hash Function" + ], + "complexity": "Hard", + "successrate": 28.3, + "totalsubmissions": 16630, + "totalaccepted": 4707, + "likes": 267, + "dislikes": 24, + "hints": "If there is a common path with length x, there is for sure a common path of length y where y < x. We can use binary search over the answer with the range [0, min(path[i].length)]. Using binary search, we want to verify if we have a common path of length m. We can achieve this using hashing.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 5, paths = [[0,1,2,3,4],\n [2,3,4],\n [4,0,1,2,3]]", + "expected_output": "2", + "explanation": "The longest common subpath is [2,3]." + }, + { + "example_num": 2, + "expected_input": "n = 3, paths = [[0],[1],[2]]", + "expected_output": "0", + "explanation": "There is no common subpath shared by the three paths." + }, + { + "example_num": 3, + "expected_input": "n = 5, paths = [[0,1,2,3,4],\n [4,3,2,1,0]]", + "expected_output": "1", + "explanation": "The possible longest common subpaths are [0], [1], [2], [3], and [4]. All have a length of 1." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e95", + "questionid": 970, + "title": "The Number of the Smallest Unoccupied Chair", + "slug": "the-number-of-the-smallest-unoccupied-chair", + "description": "There is a party where n friends numbered from 0 to n - 1 are attending. There is an infinite number of chairs in this party that are numbered from 0 to infinity. When a friend arrives at the party, they sit on the unoccupied chair with the smallest number. When a friend leaves the party, their chair becomes unoccupied at the moment they leave. If another friend arrives at that same moment, they can sit in that chair. You are given a 0-indexed 2D integer array times where times[i] = [arrivali, leavingi], indicating the arrival and leaving times of the ith friend respectively, and an integer targetFriend. All arrival times are distinct. Return the chair number that the friend numbered targetFriend will sit on. ", + "category": [ + "Array", + "Heap (Priority Queue)", + "Ordered Set" + ], + "complexity": "Medium", + "successrate": 38.9, + "totalsubmissions": 27895, + "totalaccepted": 10846, + "likes": 371, + "dislikes": 18, + "hints": "Sort times by arrival time. for each arrival_i find the smallest unoccupied chair and mark it as occupied until leaving_i.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "times = [[1,4],[2,3],[4,6]], targetFriend = 1", + "expected_output": "1", + "explanation": "- Friend 0 arrives at time 1 and sits on chair 0.\n- Friend 1 arrives at time 2 and sits on chair 1.\n- Friend 1 leaves at time 3 and chair 1 becomes empty.\n- Friend 0 leaves at time 4 and chair 0 becomes empty.\n- Friend 2 arrives at time 4 and sits on chair 0.\nSince friend 1 sat on chair 1, we return 1." + }, + { + "example_num": 2, + "expected_input": "times = [[3,10],[1,5],[2,6]], targetFriend = 0", + "expected_output": "2", + "explanation": "- Friend 1 arrives at time 1 and sits on chair 0.\n- Friend 2 arrives at time 2 and sits on chair 1.\n- Friend 0 arrives at time 3 and sits on chair 2.\n- Friend 1 leaves at time 5 and chair 0 becomes empty.\n- Friend 2 leaves at time 6 and chair 1 becomes empty.\n- Friend 0 leaves at time 10 and chair 2 becomes empty.\nSince friend 0 sat on chair 2, we return 2." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e96", + "questionid": 971, + "title": "Describe the Painting", + "slug": "describe-the-painting", + "description": "There is a long and thin painting that can be represented by a number line. The painting was painted with multiple overlapping segments where each segment was painted with a unique color. You are given a 2D integer array segments, where segments[i] = [starti, endi, colori] represents the half-closed segment [starti, endi) with colori as the color. The colors in the overlapping segments of the painting were mixed when it was painted. When two or more colors mix, they form a new color that can be represented as a set of mixed colors. For the sake of simplicity, you should only output the sum of the elements in the set rather than the full set. You want to describe the painting with the minimum number of non-overlapping half-closed segments of these mixed colors. These segments can be represented by the 2D array painting where painting[j] = [leftj, rightj, mixj] describes a half-closed segment [leftj, rightj) with the mixed color sum of mixj. Return the 2D array painting describing the finished painting (excluding any parts that are not painted). You may return the segments in any order. A half-closed segment [a, b) is the section of the number line between points a and b including point a and not including point b. ", + "category": [ + "Array", + "Prefix Sum" + ], + "complexity": "Medium", + "successrate": 46.5, + "totalsubmissions": 15676, + "totalaccepted": 7288, + "likes": 275, + "dislikes": 16, + "hints": "Can we sort the segments in a way to help solve the problem? How can we dynamically keep track of the sum of the current segment(s)?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "segments = [[1,4,5],[4,7,7],[1,7,9]]", + "expected_output": "[[1,4,14],[4,7,16]]\nExplanation: The painting can be described as follows:\n- [1,4) is colored {5,9} (with a sum of 14) from the first and third segments.\n- [4,7) is colored {7,9} (with a sum of 16) from the second and third segments.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "segments = [[1,7,9],[6,8,15],[8,10,7]]", + "expected_output": "[[1,6,9],[6,7,24],[7,8,15],[8,10,7]]\nExplanation: The painting can be described as follows:\n- [1,6) is colored 9 from the first segment.\n- [6,7) is colored {9,15} (with a sum of 24) from the first and second segments.\n- [7,8) is colored 15 from the second segment.\n- [8,10) is colored 7 from the third segment.", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "segments = [[1,4,5],[1,4,7],[4,7,1],[4,7,11]]", + "expected_output": "[[1,4,12],[4,7,12]]\nExplanation: The painting can be described as follows:\n- [1,4) is colored {5,7} (with a sum of 12) from the first and second segments.\n- [4,7) is colored {1,11} (with a sum of 12) from the third and fourth segments.\nNote that returning a single segment [1,7) is incorrect because the mixed color sets are different.", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e99", + "questionid": 974, + "title": "Painting a Grid With Three Different Colors", + "slug": "painting-a-grid-with-three-different-colors", + "description": "You are given two integers m and n. Consider an m x n grid where each cell is initially white. You can paint each cell red, green, or blue. All cells must be painted. Return the number of ways to color the grid with no two adjacent cells having the same color. Since the answer can be very large, return it modulo 109 + 7. ", + "category": [ + "Dynamic Programming" + ], + "complexity": "Hard", + "successrate": 57, + "totalsubmissions": 10825, + "totalaccepted": 6171, + "likes": 297, + "dislikes": 16, + "hints": "Represent each colored column by a bitmask based on each cell color. Use bitmasks DP with state (currentCell, prevColumn).", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "m = 1, n = 1", + "expected_output": "3", + "explanation": "The three possible colorings are shown in the image above." + }, + { + "example_num": 2, + "expected_input": "m = 1, n = 2", + "expected_output": "6", + "explanation": "The six possible colorings are shown in the image above." + }, + { + "example_num": 3, + "expected_input": "m = 5, n = 5", + "expected_output": "580986", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e9f", + "questionid": 980, + "title": "Three Divisors", + "slug": "three-divisors", + "description": "Given an integer n, return true if n has exactly three positive divisors. Otherwise, return false. An integer m is a divisor of n if there exists an integer k such that n = k * m. ", + "category": [ + "Math" + ], + "complexity": "Easy", + "successrate": 56.5, + "totalsubmissions": 45242, + "totalaccepted": 25550, + "likes": 218, + "dislikes": 15, + "hints": "You can count the number of divisors and just check that they are 3 Beware of the case of n equal 1 as some solutions might fail in it", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 2", + "expected_output": "false\nExplantion: 2 has only two divisors: 1 and 2.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "n = 4", + "expected_output": "true\nExplantion: 4 has three divisors: 1, 2, and 4.", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720ea1", + "questionid": 982, + "title": "Count Number of Special Subsequences", + "slug": "count-number-of-special-subsequences", + "description": "A sequence is special if it consists of a positive number of 0s, followed by a positive number of 1s, then a positive number of 2s. Given an array nums (consisting of only integers 0, 1, and 2), return the number of different subsequences that are special. Since the answer may be very large, return it modulo 109 + 7. A subsequence of an array is a sequence that can be derived from the array by deleting some or no elements without changing the order of the remaining elements. Two subsequences are different if the set of indices chosen are different. ", + "category": [ + "Array", + "Dynamic Programming" + ], + "complexity": "Hard", + "successrate": 50.9, + "totalsubmissions": 14394, + "totalaccepted": 7326, + "likes": 341, + "dislikes": 6, + "hints": "Can we first solve a simpler problem? Counting the number of subsequences with 1s followed by 0s. How can we keep track of the partially matched subsequences to help us find the answer?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [0,1,2,2]", + "expected_output": "3", + "explanation": "The special subsequences are bolded [0,1,2,2], [0,1,2,2], and [0,1,2,2]." + }, + { + "example_num": 2, + "expected_input": "nums = [2,2,0,0]", + "expected_output": "0", + "explanation": "There are no special subsequences in [2,2,0,0]." + }, + { + "example_num": 3, + "expected_input": "nums = [0,1,2,0,1,2]", + "expected_output": "7", + "explanation": "The special subsequences are bolded:\n- [0,1,2,0,1,2]\n- [0,1,2,0,1,2]\n- [0,1,2,0,1,2]\n- [0,1,2,0,1,2]\n- [0,1,2,0,1,2]\n- [0,1,2,0,1,2]\n- [0,1,2,0,1,2]" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720ea4", + "questionid": 985, + "title": "Check If String Is a Prefix of Array", + "slug": "check-if-string-is-a-prefix-of-array", + "description": "Given a string s and an array of strings words, determine whether s is a prefix string of words. A string s is a prefix string of words if s can be made by concatenating the first k strings in words for some positive k no larger than words.length. Return true if s is a prefix string of words, or false otherwise. ", + "category": [ + "Array", + "String" + ], + "complexity": "Easy", + "successrate": 54.7, + "totalsubmissions": 45019, + "totalaccepted": 24606, + "likes": 212, + "dislikes": 31, + "hints": "There are only words.length prefix strings. Create all of them and see if s is one of them.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "iloveleetcode", words = ["i","love","leetcode","apples"]", + "expected_output": "true", + "explanation": "s can be made by concatenating "i", "love", and "leetcode" together." + }, + { + "example_num": 2, + "expected_input": "s = "iloveleetcode", words = ["apples","i","love","leetcode"]", + "expected_output": "false", + "explanation": "It is impossible to make s using a prefix of arr." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720eae", + "questionid": 995, + "title": "Number of Unique Good Subsequences", + "slug": "number-of-unique-good-subsequences", + "description": "You are given a binary string binary. A subsequence of binary is considered good if it is not empty and has no leading zeros (with the exception of \"0\"). Find the number of unique good subsequences of binary. Return the number of unique good subsequences of binary. Since the answer may be very large, return it modulo 109 + 7. A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements. ", + "category": [ + "String", + "Dynamic Programming" + ], + "complexity": "Hard", + "successrate": 51.9, + "totalsubmissions": 13193, + "totalaccepted": 6850, + "likes": 369, + "dislikes": 7, + "hints": "The number of unique good subsequences is equal to the number of unique decimal values there are for all possible subsequences. Find the answer at each index based on the previous indexes' answers.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "binary = "001"", + "expected_output": "2", + "explanation": "The good subsequences of binary are ["0", "0", "1"].\nThe unique good subsequences are "0" and "1"." + }, + { + "example_num": 2, + "expected_input": "binary = "11"", + "expected_output": "2", + "explanation": "The good subsequences of binary are ["1", "1", "11"].\nThe unique good subsequences are "1" and "11"." + }, + { + "example_num": 3, + "expected_input": "binary = "101"", + "expected_output": "5", + "explanation": "The good subsequences of binary are ["1", "0", "1", "10", "11", "101"]. \nThe unique good subsequences are "0", "1", "10", "11", and "101"." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720eaf", + "questionid": 996, + "title": "Find Original Array From Doubled Array", + "slug": "find-original-array-from-doubled-array", + "description": "An integer array original is transformed into a doubled array changed by appending twice the value of every element in original, and then randomly shuffling the resulting array. Given an array changed, return original if changed is a doubled array. If changed is not a doubled array, return an empty array. The elements in original may be returned in any order. ", + "category": [ + "Array", + "Hash Table", + "Greedy", + "Sorting" + ], + "complexity": "Medium", + "successrate": 38, + "totalsubmissions": 105116, + "totalaccepted": 39908, + "likes": 571, + "dislikes": 44, + "hints": "If changed is a doubled array, you should be able to delete elements and their doubled values until the array is empty. Which element is guaranteed to not be a doubled value? It is the smallest element. After removing the smallest element and its double from changed, is there another number that is guaranteed to not be a doubled value?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "changed = [1,3,4,2,6,8]", + "expected_output": "[1,3,4]", + "explanation": "One possible original array could be [1,3,4]:\n- Twice the value of 1 is 1 * 2 = 2.\n- Twice the value of 3 is 3 * 2 = 6.\n- Twice the value of 4 is 4 * 2 = 8.\nOther original arrays could be [4,3,1] or [3,1,4]." + }, + { + "example_num": 2, + "expected_input": "changed = [6,3,0,1]", + "expected_output": "[]", + "explanation": "changed is not a doubled array." + }, + { + "example_num": 3, + "expected_input": "changed = [1]", + "expected_output": "[]", + "explanation": "changed is not a doubled array." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720eb0", + "questionid": 997, + "title": "Find if Path Exists in Graph", + "slug": "find-if-path-exists-in-graph", + "description": "There is a bi-directional graph with n vertices, where each vertex is labeled from 0 to n - 1 (inclusive). The edges in the graph are represented as a 2D integer array edges, where each edges[i] = [ui, vi] denotes a bi-directional edge between vertex ui and vertex vi. Every vertex pair is connected by at most one edge, and no vertex has an edge to itself. You want to determine if there is a valid path that exists from vertex source to vertex destination. Given edges and the integers n, source, and destination, return true if there is a valid path from source to destination, or false otherwise. ", + "category": [ + "Depth-First Search", + "Breadth-First Search", + "Graph" + ], + "complexity": "Easy", + "successrate": 50.2, + "totalsubmissions": 164420, + "totalaccepted": 82591, + "likes": 888, + "dislikes": 51, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 3, edges = [[0,1],[1,2],[2,0]], source = 0, destination = 2", + "expected_output": "true", + "explanation": "There are two paths from vertex 0 to vertex 2:\n- 0 → 1 → 2\n- 0 → 2" + }, + { + "example_num": 2, + "expected_input": "n = 6, edges = [[0,1],[0,2],[3,5],[5,4],[4,3]], source = 0, destination = 5", + "expected_output": "false", + "explanation": "There is no path from vertex 0 to vertex 5." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e98", + "questionid": 973, + "title": "Unique Length-3 Palindromic Subsequences", + "slug": "unique-length-3-palindromic-subsequences", + "description": "Given a string s, return the number of unique palindromes of length three that are a subsequence of s. Note that even if there are multiple ways to obtain the same subsequence, it is still only counted once. A palindrome is a string that reads the same forwards and backwards. A subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters. ", + "category": [ + "Hash Table", + "String", + "Prefix Sum" + ], + "complexity": "Medium", + "successrate": 51.1, + "totalsubmissions": 30682, + "totalaccepted": 15670, + "likes": 409, + "dislikes": 11, + "hints": "What is the maximum number of length-3 palindromic strings? How can we keep track of the characters that appeared to the left of a given position?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "aabca"", + "expected_output": "3", + "explanation": "The 3 palindromic subsequences of length 3 are:\n- "aba" (subsequence of "aabca")\n- "aaa" (subsequence of "aabca")\n- "aca" (subsequence of "aabca")" + }, + { + "example_num": 2, + "expected_input": "s = "adc"", + "expected_output": "0", + "explanation": "There are no palindromic subsequences of length 3 in "adc"." + }, + { + "example_num": 3, + "expected_input": "s = "bbcbaba"", + "expected_output": "4", + "explanation": "The 4 palindromic subsequences of length 3 are:\n- "bbb" (subsequence of "bbcbaba")\n- "bcb" (subsequence of "bbcbaba")\n- "bab" (subsequence of "bbcbaba")\n- "aba" (subsequence of "bbcbaba")" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e9a", + "questionid": 975, + "title": "Add Minimum Number of Rungs", + "slug": "add-minimum-number-of-rungs", + "description": "You are given a strictly increasing integer array rungs that represents the height of rungs on a ladder. You are currently on the floor at height 0, and you want to reach the last rung. You are also given an integer dist. You can only climb to the next highest rung if the distance between where you are currently at (the floor or on a rung) and the next rung is at most dist. You are able to insert rungs at any positive integer height if a rung is not already there. Return the minimum number of rungs that must be added to the ladder in order for you to climb to the last rung. ", + "category": [ + "Array", + "Greedy" + ], + "complexity": "Medium", + "successrate": 42.4, + "totalsubmissions": 43557, + "totalaccepted": 18474, + "likes": 220, + "dislikes": 18, + "hints": "Go as far as you can on the available rungs before adding new rungs. If you have to add a new rung, add it as high up as possible. Try using division to decrease the number of computations.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "rungs = [1,3,5,10], dist = 2", + "expected_output": "2\nExplanation:\nYou currently cannot reach the last rung.\nAdd rungs at heights 7 and 8 to climb this ladder. \nThe ladder will now have rungs at [1,3,5,7,8,10].", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "rungs = [3,6,8,10], dist = 3", + "expected_output": "0", + "explanation": "This ladder can be climbed without adding additional rungs." + }, + { + "example_num": 3, + "expected_input": "rungs = [3,4,6,7], dist = 2", + "expected_output": "1", + "explanation": "You currently cannot reach the first rung from the ground.\nAdd a rung at height 1 to climb this ladder.\nThe ladder will now have rungs at [1,3,4,6,7]." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e9b", + "questionid": 976, + "title": "Maximum Genetic Difference Query", + "slug": "maximum-genetic-difference-query", + "description": "There is a rooted tree consisting of n nodes numbered 0 to n - 1. Each node's number denotes its unique genetic value (i.e. the genetic value of node x is x). The genetic difference between two genetic values is defined as the bitwise-XOR of their values. You are given the integer array parents, where parents[i] is the parent for node i. If node x is the root of the tree, then parents[x] == -1. You are also given the array queries where queries[i] = [nodei, vali]. For each query i, find the maximum genetic difference between vali and pi, where pi is the genetic value of any node that is on the path between nodei and the root (including nodei and the root). More formally, you want to maximize vali XOR pi. Return an array ans where ans[i] is the answer to the ith query. ", + "category": [ + "Array", + "Bit Manipulation", + "Trie" + ], + "complexity": "Hard", + "successrate": 39.2, + "totalsubmissions": 8253, + "totalaccepted": 3234, + "likes": 218, + "dislikes": 11, + "hints": "How can we use a trie to store all the XOR values in the path from a node to the root? How can we dynamically add the XOR values with a DFS search?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "parents = [-1,0,1,1], queries = [[0,2],[3,2],[2,5]]", + "expected_output": "[2,3,7]\nExplanation: The queries are processed as follows:\n- [0,2]: The node with the maximum genetic difference is 0, with a difference of 2 XOR 0 = 2.\n- [3,2]: The node with the maximum genetic difference is 1, with a difference of 2 XOR 1 = 3.\n- [2,5]: The node with the maximum genetic difference is 2, with a difference of 5 XOR 2 = 7.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "parents = [3,7,-1,2,0,7,0,2], queries = [[4,6],[1,15],[0,5]]", + "expected_output": "[6,14,7]\nExplanation: The queries are processed as follows:\n- [4,6]: The node with the maximum genetic difference is 0, with a difference of 6 XOR 0 = 6.\n- [1,15]: The node with the maximum genetic difference is 1, with a difference of 15 XOR 1 = 14.\n- [0,5]: The node with the maximum genetic difference is 2, with a difference of 5 XOR 2 = 7.", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e9c", + "questionid": 977, + "title": "Largest Number After Mutating Substring", + "slug": "largest-number-after-mutating-substring", + "description": "You are given a string num, which represents a large integer. You are also given a 0-indexed integer array change of length 10 that maps each digit 0-9 to another digit. More formally, digit d maps to digit change[d]. You may choose to mutate a single substring of num. To mutate a substring, replace each digit num[i] with the digit it maps to in change (i.e. replace num[i] with change[num[i]]). Return a string representing the largest possible integer after mutating (or choosing not to) a single substring of num. A substring is a contiguous sequence of characters within the string. ", + "category": [ + "Array", + "String", + "Greedy" + ], + "complexity": "Medium", + "successrate": 33.9, + "totalsubmissions": 41615, + "totalaccepted": 14112, + "likes": 139, + "dislikes": 163, + "hints": "Should you change a digit if the new digit is smaller than the original? If changing the first digit and the last digit both make the number bigger, but you can only change one of them; which one should you change? Changing numbers closer to the front is always better", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "num = "132", change = [9,8,5,0,3,6,4,2,6,8]", + "expected_output": ""832"", + "explanation": "Replace the substring "1":\n- 1 maps to change[1] = 8.\nThus, "132" becomes "832".\n"832" is the largest number that can be created, so return it." + }, + { + "example_num": 2, + "expected_input": "num = "021", change = [9,4,3,5,7,2,1,9,0,6]", + "expected_output": ""934"", + "explanation": "Replace the substring "021":\n- 0 maps to change[0] = 9.\n- 2 maps to change[2] = 3.\n- 1 maps to change[1] = 4.\nThus, "021" becomes "934".\n"934" is the largest number that can be created, so return it." + }, + { + "example_num": 3, + "expected_input": "num = "5", change = [1,4,7,5,3,2,5,6,9,4]", + "expected_output": ""5"", + "explanation": ""5" is already the largest number that can be created, so return it." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e9e", + "questionid": 979, + "title": "Delete Duplicate Folders in System", + "slug": "delete-duplicate-folders-in-system", + "description": "Due to a bug, there are many duplicate folders in a file system. You are given a 2D array paths, where paths[i] is an array representing an absolute path to the ith folder in the file system. Two folders (not necessarily on the same level) are identical if they contain the same non-empty set of identical subfolders and underlying subfolder structure. The folders do not need to be at the root level to be identical. If two or more folders are identical, then mark the folders as well as all their subfolders. Once all the identical folders and their subfolders have been marked, the file system will delete all of them. The file system only runs the deletion once, so any folders that become identical after the initial deletion are not deleted. Return the 2D array ans containing the paths of the remaining folders after deleting all the marked folders. The paths may be returned in any order. ", + "category": [ + "Array", + "Hash Table", + "String", + "Trie", + "Hash Function" + ], + "complexity": "Hard", + "successrate": 58.6, + "totalsubmissions": 7699, + "totalaccepted": 4513, + "likes": 166, + "dislikes": 48, + "hints": "Can we use a trie to build the folder structure? Can we utilize hashing to hash the folder structures?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "paths = [["a"],["c"],["d"],["a","b"],["c","b"],["d","a"]]", + "expected_output": "[["d"],["d","a"]]", + "explanation": "The file structure is as shown.\nFolders "/a" and "/c" (and their subfolders) are marked for deletion because they both contain an empty\nfolder named "b"." + }, + { + "example_num": 2, + "expected_input": "paths = [["a"],["c"],["a","b"],["c","b"],["a","b","x"],["a","b","x","y"],["w"],["w","y"]]", + "expected_output": "[["c"],["c","b"],["a"],["a","b"]]\nExplanation: The file structure is as shown. \nFolders "/a/b/x" and "/w" (and their subfolders) are marked for deletion because they both contain an empty folder named "y".\nNote that folders "/a" and "/c" are identical after the deletion, but they are not deleted because they were not marked beforehand.", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "paths = [["a","b"],["c","d"],["c"],["a"]]", + "expected_output": "[["c"],["c","d"],["a"],["a","b"]]", + "explanation": "All folders are unique in the file system.\nNote that the returned array can be in a different order as the order does not matter." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720ea0", + "questionid": 981, + "title": "Array With Elements Not Equal to Average of Neighbors", + "slug": "array-with-elements-not-equal-to-average-of-neighbors", + "description": "You are given a 0-indexed array nums of distinct integers. You want to rearrange the elements in the array such that every element in the rearranged array is not equal to the average of its neighbors. More formally, the rearranged array should have the property such that for every i in the range 1 <= i < nums.length - 1, (nums[i-1] + nums[i+1]) / 2 is not equal to nums[i]. Return any rearrangement of nums that meets the requirements. ", + "category": [ + "Array", + "Greedy", + "Sorting" + ], + "complexity": "Medium", + "successrate": 48.5, + "totalsubmissions": 33552, + "totalaccepted": 16267, + "likes": 256, + "dislikes": 17, + "hints": "A number can be the average of its neighbors if one neighbor is smaller than the number and the other is greater than the number. We can put numbers smaller than the median on odd indices and the rest on even indices.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,2,3,4,5]", + "expected_output": "[1,2,4,5,3]", + "explanation": "When i=1, nums[i] = 2, and the average of its neighbors is (1+4) / 2 = 2.5.\nWhen i=2, nums[i] = 4, and the average of its neighbors is (2+5) / 2 = 3.5.\nWhen i=3, nums[i] = 5, and the average of its neighbors is (4+3) / 2 = 3.5." + }, + { + "example_num": 2, + "expected_input": "nums = [6,2,0,9,7]", + "expected_output": "[9,7,6,2,0]", + "explanation": "When i=1, nums[i] = 7, and the average of its neighbors is (9+6) / 2 = 7.5.\nWhen i=2, nums[i] = 6, and the average of its neighbors is (7+2) / 2 = 4.5.\nWhen i=3, nums[i] = 2, and the average of its neighbors is (6+0) / 2 = 3." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720ea2", + "questionid": 983, + "title": "Number of Ways to Arrive at Destination", + "slug": "number-of-ways-to-arrive-at-destination", + "description": "You are in a city that consists of n intersections numbered from 0 to n - 1 with bi-directional roads between some intersections. The inputs are generated such that you can reach any intersection from any other intersection and that there is at most one road between any two intersections. You are given an integer n and a 2D integer array roads where roads[i] = [ui, vi, timei] means that there is a road between intersections ui and vi that takes timei minutes to travel. You want to know in how many ways you can travel from intersection 0 to intersection n - 1 in the shortest amount of time. Return the number of ways you can arrive at your destination in the shortest amount of time. Since the answer may be large, return it modulo 109 + 7. ", + "category": [ + "Dynamic Programming", + "Graph", + "Topological Sort", + "Shortest Path" + ], + "complexity": "Medium", + "successrate": 32.9, + "totalsubmissions": 41803, + "totalaccepted": 13760, + "likes": 795, + "dislikes": 23, + "hints": "First use any shortest path algorithm to get edges where dist[u] + weight = dist[v], here dist[x] is the shortest distance between node 0 and x Using those edges only the graph turns into a dag now we just need to know the number of ways to get from node 0 to node n - 1 on a dag using dp", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 7, roads = [[0,6,7],[0,1,2],[1,2,3],[1,3,3],[6,3,3],[3,5,1],[6,5,1],[2,5,1],[0,4,5],[4,6,2]]", + "expected_output": "4", + "explanation": "The shortest amount of time it takes to go from intersection 0 to intersection 6 is 7 minutes.\nThe four ways to get there in 7 minutes are:\n- 0 ➝ 6\n- 0 ➝ 4 ➝ 6\n- 0 ➝ 1 ➝ 2 ➝ 5 ➝ 6\n- 0 ➝ 1 ➝ 3 ➝ 5 ➝ 6" + }, + { + "example_num": 2, + "expected_input": "n = 2, roads = [[1,0,10]]", + "expected_output": "1", + "explanation": "There is only one way to go from intersection 0 to intersection 1, and it takes 10 minutes." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720ea8", + "questionid": 989, + "title": "Find All Groups of Farmland", + "slug": "find-all-groups-of-farmland", + "description": "You are given a 0-indexed m x n binary matrix land where a 0 represents a hectare of forested land and a 1 represents a hectare of farmland. To keep the land organized, there are designated rectangular areas of hectares that consist entirely of farmland. These rectangular areas are called groups. No two groups are adjacent, meaning farmland in one group is not four-directionally adjacent to another farmland in a different group. land can be represented by a coordinate system where the top left corner of land is (0, 0) and the bottom right corner of land is (m-1, n-1). Find the coordinates of the top left and bottom right corner of each group of farmland. A group of farmland with a top left corner at (r1, c1) and a bottom right corner at (r2, c2) is represented by the 4-length array [r1, c1, r2, c2]. Return a 2D array containing the 4-length arrays described above for each group of farmland in land. If there are no groups of farmland, return an empty array. You may return the answer in any order. ", + "category": [ + "Array", + "Depth-First Search", + "Breadth-First Search", + "Matrix" + ], + "complexity": "Medium", + "successrate": 67.2, + "totalsubmissions": 19741, + "totalaccepted": 13260, + "likes": 345, + "dislikes": 17, + "hints": "Since every group of farmland is rectangular, the top left corner of each group will have the smallest x-coordinate and y-coordinate of any farmland in the group. Similarly, the bootm right corner of each group will have the largest x-coordinate and y-coordinate of any farmland in the group. Use DFS to traverse through different groups of farmlands and keep track of the smallest and largest x-coordinate and y-coordinates you have seen in each group.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "land = [[1,0,0],[0,1,1],[0,1,1]]", + "expected_output": "[[0,0,0,0],[1,1,2,2]]", + "explanation": "The first group has a top left corner at land[0][0] and a bottom right corner at land[0][0].\nThe second group has a top left corner at land[1][1] and a bottom right corner at land[2][2]." + }, + { + "example_num": 2, + "expected_input": "land = [[1,1],[1,1]]", + "expected_output": "[[0,0,1,1]]", + "explanation": "The first group has a top left corner at land[0][0] and a bottom right corner at land[1][1]." + }, + { + "example_num": 3, + "expected_input": "land = [[0]]", + "expected_output": "[]", + "explanation": "There are no groups of farmland." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720ea9", + "questionid": 990, + "title": "The Number of Good Subsets", + "slug": "the-number-of-good-subsets", + "description": "You are given an integer array nums. We call a subset of nums good if its product can be represented as a product of one or more distinct prime numbers. Return the number of different good subsets in nums modulo 109 + 7. A subset of nums is any array that can be obtained by deleting some (possibly none or all) elements from nums. Two subsets are different if and only if the chosen indices to delete are different. ", + "category": [ + "Array", + "Math", + "Dynamic Programming", + "Bit Manipulation", + "Bitmask" + ], + "complexity": "Hard", + "successrate": 33.9, + "totalsubmissions": 10566, + "totalaccepted": 3587, + "likes": 208, + "dislikes": 7, + "hints": "Consider only the numbers which have a good prime factorization. Use brute force to find all possible good subsets and then calculate its frequency in nums.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,2,3,4]", + "expected_output": "6", + "explanation": "The good subsets are:\n- [1,2]: product is 2, which is the product of distinct prime 2.\n- [1,2,3]: product is 6, which is the product of distinct primes 2 and 3.\n- [1,3]: product is 3, which is the product of distinct prime 3.\n- [2]: product is 2, which is the product of distinct prime 2.\n- [2,3]: product is 6, which is the product of distinct primes 2 and 3.\n- [3]: product is 3, which is the product of distinct prime 3." + }, + { + "example_num": 2, + "expected_input": "nums = [4,2,3,15]", + "expected_output": "5", + "explanation": "The good subsets are:\n- [2]: product is 2, which is the product of distinct prime 2.\n- [2,3]: product is 6, which is the product of distinct primes 2 and 3.\n- [2,15]: product is 30, which is the product of distinct primes 2, 3, and 5.\n- [3]: product is 3, which is the product of distinct prime 3.\n- [15]: product is 15, which is the product of distinct primes 3 and 5." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720eb1", + "questionid": 998, + "title": "Reverse Prefix of Word", + "slug": "reverse-prefix-of-word", + "description": "Given a 0-indexed string word and a character ch, reverse the segment of word that starts at index 0 and ends at the index of the first occurrence of ch (inclusive). If the character ch does not exist in word, do nothing. Return the resulting string. ", + "category": [ + "Two Pointers", + "String" + ], + "complexity": "Easy", + "successrate": 78, + "totalsubmissions": 41520, + "totalaccepted": 32378, + "likes": 310, + "dislikes": 6, + "hints": "Find the first index where ch appears. Find a way to reverse a substring of word.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "word = "abcdefd", ch = "d"", + "expected_output": ""dcbaefd"", + "explanation": " The first occurrence of "d" is at index 3. \nReverse the part of word from 0 to 3 (inclusive), the resulting string is "dcbaefd"." + }, + { + "example_num": 2, + "expected_input": "word = "xyxzxe", ch = "z"", + "expected_output": ""zxyxxe"", + "explanation": " The first and only occurrence of "z" is at index 3.\nReverse the part of word from 0 to 3 (inclusive), the resulting string is "zxyxxe"." + }, + { + "example_num": 3, + "expected_input": "word = "abcd", ch = "z"", + "expected_output": ""abcd"", + "explanation": " "z" does not exist in word.\nYou should not do any reverse operation, the resulting string is "abcd"." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e8f", + "questionid": 964, + "title": "Find a Peak Element II", + "slug": "find-a-peak-element-ii", + "description": "A peak element in a 2D grid is an element that is strictly greater than all of its adjacent neighbors to the left, right, top, and bottom. Given a 0-indexed m x n matrix mat where no two adjacent cells are equal, find any peak element mat[i][j] and return the length 2 array [i,j]. You may assume that the entire matrix is surrounded by an outer perimeter with the value -1 in each cell. You must write an algorithm that runs in O(m log(n)) or O(n log(m)) time. ", + "category": [ + "Array", + "Binary Search", + "Divide and Conquer", + "Matrix" + ], + "complexity": "Medium", + "successrate": 53.5, + "totalsubmissions": 34416, + "totalaccepted": 18416, + "likes": 681, + "dislikes": 54, + "hints": "Let's assume that the width of the array is bigger than the height, otherwise, we will split in another direction. Split the array into three parts: central column left side and right side. Go through the central column and two neighbor columns and look for maximum. If it's in the central column - this is our peak. If it's on the left side, run this algorithm on subarray left_side + central_column. If it's on the right side, run this algorithm on subarray right_side + central_column", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "mat = [[1,4],[3,2]]", + "expected_output": "[0,1]", + "explanation": " Both 3 and 4 are peak elements so [1,0] and [0,1] are both acceptable answers." + }, + { + "example_num": 2, + "expected_input": "mat = [[10,20,15],[21,30,14],[7,16,32]]", + "expected_output": "[1,1]", + "explanation": " Both 30 and 32 are peak elements so [1,1] and [2,2] are both acceptable answers." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e90", + "questionid": 965, + "title": "Build Array from Permutation", + "slug": "build-array-from-permutation", + "description": "Given a zero-based permutation nums (0-indexed), build an array ans of the same length where ans[i] = nums[nums[i]] for each 0 <= i < nums.length and return it. A zero-based permutation nums is an array of distinct integers from 0 to nums.length - 1 (inclusive). ", + "category": [ + "Array", + "Simulation" + ], + "complexity": "Easy", + "successrate": 91.6, + "totalsubmissions": 160267, + "totalaccepted": 146876, + "likes": 1157, + "dislikes": 156, + "hints": "Just apply what's said in the statement. Notice that you can't apply it on the same array directly since some elements will change after application", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [0,2,1,5,3,4]", + "expected_output": "[0,1,2,4,5,3]\nExplanation: The array ans is built as follows: \nans = [nums[nums[0]], nums[nums[1]], nums[nums[2]], nums[nums[3]], nums[nums[4]], nums[nums[5]]]\n = [nums[0], nums[2], nums[1], nums[5], nums[3], nums[4]]\n = [0,1,2,4,5,3]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "nums = [5,0,1,2,3,4]", + "expected_output": "[4,5,0,1,2,3]", + "explanation": "The array ans is built as follows:\nans = [nums[nums[0]], nums[nums[1]], nums[nums[2]], nums[nums[3]], nums[nums[4]], nums[nums[5]]]\n = [nums[5], nums[0], nums[1], nums[2], nums[3], nums[4]]\n = [4,5,0,1,2,3]" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e92", + "questionid": 967, + "title": "Count Good Numbers", + "slug": "count-good-numbers", + "description": "A digit string is good if the digits (0-indexed) at even indices are even and the digits at odd indices are prime (2, 3, 5, or 7). Given an integer n, return the total number of good digit strings of length n. Since the answer may be large, return it modulo 109 + 7. A digit string is a string consisting of digits 0 through 9 that may contain leading zeros. ", + "category": [ + "Math", + "Recursion" + ], + "complexity": "Medium", + "successrate": 38.2, + "totalsubmissions": 38945, + "totalaccepted": 14887, + "likes": 316, + "dislikes": 217, + "hints": "Is there a formula we can use to find the count of all the good numbers? Exponentiation can be done very fast if we looked at the binary bits of n.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 1", + "expected_output": "5", + "explanation": "The good numbers of length 1 are "0", "2", "4", "6", "8"." + }, + { + "example_num": 2, + "expected_input": "n = 4", + "expected_output": "400", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "n = 50", + "expected_output": "564908303", + "explanation": "" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e94", + "questionid": 969, + "title": "Check if All Characters Have Equal Number of Occurrences", + "slug": "check-if-all-characters-have-equal-number-of-occurrences", + "description": "Given a string s, return true if s is a good string, or false otherwise. A string s is good if all the characters that appear in s have the same number of occurrences (i.e., the same frequency). ", + "category": [ + "Hash Table", + "String", + "Counting" + ], + "complexity": "Easy", + "successrate": 77.1, + "totalsubmissions": 43486, + "totalaccepted": 33510, + "likes": 328, + "dislikes": 11, + "hints": "Build a dictionary containing the frequency of each character appearing in s Check if all values in the dictionary are the same.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "abacbc"", + "expected_output": "true", + "explanation": "The characters that appear in s are 'a', 'b', and 'c'. All characters occur 2 times in s." + }, + { + "example_num": 2, + "expected_input": "s = "aaabb"", + "expected_output": "false", + "explanation": "The characters that appear in s are 'a' and 'b'.\n'a' occurs 3 times while 'b' occurs 2 times, which is not the same number of times." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e9d", + "questionid": 978, + "title": "Maximum Compatibility Score Sum", + "slug": "maximum-compatibility-score-sum", + "description": "There is a survey that consists of n questions where each question's answer is either 0 (no) or 1 (yes). The survey was given to m students numbered from 0 to m - 1 and m mentors numbered from 0 to m - 1. The answers of the students are represented by a 2D integer array students where students[i] is an integer array that contains the answers of the ith student (0-indexed). The answers of the mentors are represented by a 2D integer array mentors where mentors[j] is an integer array that contains the answers of the jth mentor (0-indexed). Each student will be assigned to one mentor, and each mentor will have one student assigned to them. The compatibility score of a student-mentor pair is the number of answers that are the same for both the student and the mentor. You are tasked with finding the optimal student-mentor pairings to maximize the sum of the compatibility scores. Given students and mentors, return the maximum compatibility score sum that can be achieved. ", + "category": [ + "Array", + "Dynamic Programming", + "Backtracking", + "Bit Manipulation", + "Bitmask" + ], + "complexity": "Medium", + "successrate": 60, + "totalsubmissions": 23285, + "totalaccepted": 13971, + "likes": 442, + "dislikes": 9, + "hints": "Calculate the compatibility score for each student-mentor pair. Try every permutation of students with the original mentors array.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "students = [[1,1,0],[1,0,1],[0,0,1]], mentors = [[1,0,0],[0,0,1],[1,1,0]]", + "expected_output": "8", + "explanation": " We assign students to mentors in the following way:\n- student 0 to mentor 2 with a compatibility score of 3.\n- student 1 to mentor 0 with a compatibility score of 2.\n- student 2 to mentor 1 with a compatibility score of 3.\nThe compatibility score sum is 3 + 2 + 3 = 8." + }, + { + "example_num": 2, + "expected_input": "students = [[0,0],[0,0],[0,0]], mentors = [[1,1],[1,1],[1,1]]", + "expected_output": "0", + "explanation": "The compatibility score of any student-mentor pair is 0." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720ea6", + "questionid": 987, + "title": "Last Day Where You Can Still Cross", + "slug": "last-day-where-you-can-still-cross", + "description": "There is a 1-based binary matrix where 0 represents land and 1 represents water. You are given integers row and col representing the number of rows and columns in the matrix, respectively. Initially on day 0, the entire matrix is land. However, each day a new cell becomes flooded with water. You are given a 1-based 2D array cells, where cells[i] = [ri, ci] represents that on the ith day, the cell on the rith row and cith column (1-based coordinates) will be covered with water (i.e., changed to 1). You want to find the last day that it is possible to walk from the top to the bottom by only walking on land cells. You can start from any cell in the top row and end at any cell in the bottom row. You can only travel in the four cardinal directions (left, right, up, and down). Return the last day where it is possible to walk from the top to the bottom by only walking on land cells. ", + "category": [ + "Array", + "Binary Search", + "Depth-First Search", + "Breadth-First Search", + "Union Find", + "Matrix" + ], + "complexity": "Hard", + "successrate": 48.5, + "totalsubmissions": 16843, + "totalaccepted": 8176, + "likes": 419, + "dislikes": 8, + "hints": "What graph algorithm allows us to find whether a path exists? Can we use binary search to help us solve the problem?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "row = 2, col = 2, cells = [[1,1],[2,1],[1,2],[2,2]]", + "expected_output": "2", + "explanation": "The above image depicts how the matrix changes each day starting from day 0.\nThe last day where it is possible to cross from top to bottom is on day 2." + }, + { + "example_num": 2, + "expected_input": "row = 2, col = 2, cells = [[1,1],[1,2],[2,1],[2,2]]", + "expected_output": "1", + "explanation": "The above image depicts how the matrix changes each day starting from day 0.\nThe last day where it is possible to cross from top to bottom is on day 1." + }, + { + "example_num": 3, + "expected_input": "row = 3, col = 3, cells = [[1,2],[2,1],[3,3],[2,2],[1,1],[1,3],[2,3],[3,2],[3,1]]", + "expected_output": "3", + "explanation": "The above image depicts how the matrix changes each day starting from day 0.\nThe last day where it is possible to cross from top to bottom is on day 3." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720ea7", + "questionid": 988, + "title": "Find the Middle Index in Array", + "slug": "find-the-middle-index-in-array", + "description": "Given a 0-indexed integer array nums, find the leftmost middleIndex (i.e., the smallest amongst all the possible ones). A middleIndex is an index where nums[0] + nums[1] + ... + nums[middleIndex-1] == nums[middleIndex+1] + nums[middleIndex+2] + ... + nums[nums.length-1]. If middleIndex == 0, the left side sum is considered to be 0. Similarly, if middleIndex == nums.length - 1, the right side sum is considered to be 0. Return the leftmost middleIndex that satisfies the condition, or -1 if there is no such index. ", + "category": [ + "Array", + "Prefix Sum" + ], + "complexity": "Easy", + "successrate": 66.2, + "totalsubmissions": 39296, + "totalaccepted": 26017, + "likes": 390, + "dislikes": 18, + "hints": "Could we go from left to right and check to see if an index is a middle index? Do we need to sum every number to the left and right of an index each time? Use a prefix sum array where prefix[i] = nums[0] + nums[1] + ... + nums[i].", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [2,3,-1,8,4]", + "expected_output": "3", + "explanation": "The sum of the numbers before index 3 is: 2 + 3 + -1 = 4\nThe sum of the numbers after index 3 is: 4 = 4" + }, + { + "example_num": 2, + "expected_input": "nums = [1,-1,4]", + "expected_output": "2", + "explanation": "The sum of the numbers before index 2 is: 1 + -1 = 0\nThe sum of the numbers after index 2 is: 0" + }, + { + "example_num": 3, + "expected_input": "nums = [2,5]", + "expected_output": "-1", + "explanation": "There is no valid middleIndex." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720eaa", + "questionid": 991, + "title": "Find Greatest Common Divisor of Array", + "slug": "find-greatest-common-divisor-of-array", + "description": "Given an integer array nums, return the greatest common divisor of the smallest number and largest number in nums. The greatest common divisor of two numbers is the largest positive integer that evenly divides both numbers. ", + "category": [ + "Array", + "Math", + "Number Theory" + ], + "complexity": "Easy", + "successrate": 77.9, + "totalsubmissions": 50222, + "totalaccepted": 39136, + "likes": 355, + "dislikes": 14, + "hints": "Find the minimum and maximum in one iteration. Let them be mn and mx. Try all the numbers in the range [1, mn] and check the largest number which divides both of them.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [2,5,6,9,10]", + "expected_output": "2", + "explanation": "The smallest number in nums is 2.\nThe largest number in nums is 10.\nThe greatest common divisor of 2 and 10 is 2." + }, + { + "example_num": 2, + "expected_input": "nums = [7,5,6,8,3]", + "expected_output": "1", + "explanation": "The smallest number in nums is 3.\nThe largest number in nums is 8.\nThe greatest common divisor of 3 and 8 is 1." + }, + { + "example_num": 3, + "expected_input": "nums = [3,3]", + "expected_output": "3", + "explanation": "The smallest number in nums is 3.\nThe largest number in nums is 3.\nThe greatest common divisor of 3 and 3 is 3." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720eab", + "questionid": 992, + "title": "Find Unique Binary String", + "slug": "find-unique-binary-string", + "description": "Given an array of strings nums containing n unique binary strings each of length n, return a binary string of length n that does not appear in nums. If there are multiple answers, you may return any of them. ", + "category": [ + "Array", + "String", + "Backtracking" + ], + "complexity": "Medium", + "successrate": 63.2, + "totalsubmissions": 34802, + "totalaccepted": 21982, + "likes": 487, + "dislikes": 24, + "hints": "We can convert the given strings into base 10 integers. Can we use recursion to generate all possible strings?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = ["01","10"]", + "expected_output": ""11"", + "explanation": ""11" does not appear in nums. "00" would also be correct." + }, + { + "example_num": 2, + "expected_input": "nums = ["00","01"]", + "expected_output": ""11"", + "explanation": ""11" does not appear in nums. "10" would also be correct." + }, + { + "example_num": 3, + "expected_input": "nums = ["111","011","001"]", + "expected_output": ""101"", + "explanation": ""101" does not appear in nums. "000", "010", "100", and "110" would also be correct." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e8c", + "questionid": 961, + "title": "Minimum Cost to Reach Destination in Time", + "slug": "minimum-cost-to-reach-destination-in-time", + "description": "There is a country of n cities numbered from 0 to n - 1 where all the cities are connected by bi-directional roads. The roads are represented as a 2D integer array edges where edges[i] = [xi, yi, timei] denotes a road between cities xi and yi that takes timei minutes to travel. There may be multiple roads of differing travel times connecting the same two cities, but no road connects a city to itself. Each time you pass through a city, you must pay a passing fee. This is represented as a 0-indexed integer array passingFees of length n where passingFees[j] is the amount of dollars you must pay when you pass through city j. In the beginning, you are at city 0 and want to reach city n - 1 in maxTime minutes or less. The cost of your journey is the summation of passing fees for each city that you passed through at some moment of your journey (including the source and destination cities). Given maxTime, edges, and passingFees, return the minimum cost to complete your journey, or -1 if you cannot complete it within maxTime minutes. ", + "category": [ + "Dynamic Programming", + "Graph" + ], + "complexity": "Hard", + "successrate": 37.2, + "totalsubmissions": 26465, + "totalaccepted": 9844, + "likes": 435, + "dislikes": 6, + "hints": "Consider a new graph where each node is one of the old nodes at a specific time. For example, node 0 at time 5. You need to find the shortest path in the new graph.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "maxTime = 30, edges = [[0,1,10],[1,2,10],[2,5,10],[0,3,1],[3,4,10],[4,5,15]], passingFees = [5,1,2,20,20,3]", + "expected_output": "11", + "explanation": "The path to take is 0 -> 1 -> 2 -> 5, which takes 30 minutes and has $11 worth of passing fees." + }, + { + "example_num": 2, + "expected_input": "maxTime = 29, edges = [[0,1,10],[1,2,10],[2,5,10],[0,3,1],[3,4,10],[4,5,15]], passingFees = [5,1,2,20,20,3]", + "expected_output": "48", + "explanation": "The path to take is 0 -> 3 -> 4 -> 5, which takes 26 minutes and has $48 worth of passing fees.\nYou cannot take path 0 -> 1 -> 2 -> 5 since it would take too long." + }, + { + "example_num": 3, + "expected_input": "maxTime = 25, edges = [[0,1,10],[1,2,10],[2,5,10],[0,3,1],[3,4,10],[4,5,15]], passingFees = [5,1,2,20,20,3]", + "expected_output": "-1", + "explanation": "There is no way to reach city 5 from city 0 within 25 minutes." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e8e", + "questionid": 963, + "title": "Number of Wonderful Substrings", + "slug": "number-of-wonderful-substrings", + "description": "A wonderful string is a string where at most one letter appears an odd number of times. Given a string word that consists of the first ten lowercase English letters ('a' through 'j'), return the number of wonderful non-empty substrings in word. If the same substring appears multiple times in word, then count each occurrence separately. A substring is a contiguous sequence of characters in a string. ", + "category": [ + "Hash Table", + "String", + "Bit Manipulation", + "Prefix Sum" + ], + "complexity": "Medium", + "successrate": 43.4, + "totalsubmissions": 19348, + "totalaccepted": 8405, + "likes": 598, + "dislikes": 43, + "hints": "For each prefix of the string, check which characters are of even frequency and which are not and represent it by a bitmask. Find the other prefixes whose masks differs from the current prefix mask by at most one bit.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "word = "aba"", + "expected_output": "4", + "explanation": "The four wonderful substrings are underlined below:\r\n- "aba" -> "a"\r\n- "aba" -> "b"\r\n- "aba" -> "a"\r\n- "aba" -> "aba"" + }, + { + "example_num": 2, + "expected_input": "word = "aabb"", + "expected_output": "9", + "explanation": "The nine wonderful substrings are underlined below:\r\n- "aabb" -> "a"\r\n- "aabb" -> "aa"\r\n- "aabb" -> "aab"\r\n- "aabb" -> "aabb"\r\n- "aabb" -> "a"\r\n- "aabb" -> "abb"\r\n- "aabb" -> "b"\r\n- "aabb" -> "bb"\r\n- "aabb" -> "b"" + }, + { + "example_num": 3, + "expected_input": "word = "he"", + "expected_output": "2", + "explanation": "The two wonderful substrings are underlined below:\r\n- "he" -> "h"\r\n- "he" -> "e"" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720e97", + "questionid": 972, + "title": "Concatenation of Array", + "slug": "concatenation-of-array", + "description": "Given an integer array nums of length n, you want to create an array ans of length 2n where ans[i] == nums[i] and ans[i + n] == nums[i] for 0 <= i < n (0-indexed). Specifically, ans is the concatenation of two nums arrays. Return the array ans. ", + "category": [ + "Array" + ], + "complexity": "Easy", + "successrate": 91.6, + "totalsubmissions": 184207, + "totalaccepted": 168811, + "likes": 908, + "dislikes": 181, + "hints": "Build an array of size 2 * n and assign num[i] to ans[i] and ans[i + n]", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,2,1]", + "expected_output": "[1,2,1,1,2,1]", + "explanation": "The array ans is formed as follows:\n- ans = [nums[0],nums[1],nums[2],nums[0],nums[1],nums[2]]\n- ans = [1,2,1,1,2,1]" + }, + { + "example_num": 2, + "expected_input": "nums = [1,3,2,1]", + "expected_output": "[1,3,2,1,1,3,2,1]", + "explanation": "The array ans is formed as follows:\n- ans = [nums[0],nums[1],nums[2],nums[3],nums[0],nums[1],nums[2],nums[3]]\n- ans = [1,3,2,1,1,3,2,1]" + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720ea3", + "questionid": 984, + "title": "Number of Ways to Separate Numbers", + "slug": "number-of-ways-to-separate-numbers", + "description": "You wrote down many positive integers in a string called num. However, you realized that you forgot to add commas to seperate the different numbers. You remember that the list of integers was non-decreasing and that no integer had leading zeros. Return the number of possible lists of integers that you could have written down to get the string num. Since the answer may be large, return it modulo 109 + 7. ", + "category": [ + "String", + "Dynamic Programming", + "Suffix Array" + ], + "complexity": "Hard", + "successrate": 22.3, + "totalsubmissions": 12191, + "totalaccepted": 2715, + "likes": 223, + "dislikes": 29, + "hints": "If we know the current number has d digits, how many digits can the previous number have? Is there a quick way of calculating the number of possibilities for the previous number if we know that it must have less than or equal to d digits? Try to do some pre-processing.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "num = "327"", + "expected_output": "2", + "explanation": "You could have written down the numbers:\n3, 27\n327" + }, + { + "example_num": 2, + "expected_input": "num = "094"", + "expected_output": "0", + "explanation": "No numbers can have leading zeros and all numbers must be positive." + }, + { + "example_num": 3, + "expected_input": "num = "0"", + "expected_output": "0", + "explanation": "No numbers can have leading zeros and all numbers must be positive." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720ea5", + "questionid": 986, + "title": "Number of Strings That Appear as Substrings in Word", + "slug": "number-of-strings-that-appear-as-substrings-in-word", + "description": "Given an array of strings patterns and a string word, return the number of strings in patterns that exist as a substring in word. A substring is a contiguous sequence of characters within a string. ", + "category": [ + "String" + ], + "complexity": "Easy", + "successrate": 79.4, + "totalsubmissions": 34760, + "totalaccepted": 27602, + "likes": 276, + "dislikes": 12, + "hints": "Deal with each of the patterns individually. Use the built-in function in the language you are using to find if the pattern exists as a substring in word.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "patterns = ["a","abc","bc","d"], word = "abc"", + "expected_output": "3", + "explanation": "- "a" appears as a substring in "abc".\n- "abc" appears as a substring in "abc".\n- "bc" appears as a substring in "abc".\n- "d" does not appear as a substring in "abc".\n3 of the strings in patterns appear as a substring in word." + }, + { + "example_num": 2, + "expected_input": "patterns = ["a","b","c"], word = "aaaaabbbbb"", + "expected_output": "2", + "explanation": "- "a" appears as a substring in "aaaaabbbbb".\n- "b" appears as a substring in "aaaaabbbbb".\n- "c" does not appear as a substring in "aaaaabbbbb".\n2 of the strings in patterns appear as a substring in word." + }, + { + "example_num": 3, + "expected_input": "patterns = ["a","a","a"], word = "ab"", + "expected_output": "3", + "explanation": "Each of the patterns appears as a substring in word "ab"." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720eac", + "questionid": 993, + "title": "Minimize the Difference Between Target and Chosen Elements", + "slug": "minimize-the-difference-between-target-and-chosen-elements", + "description": "You are given an m x n integer matrix mat and an integer target. Choose one integer from each row in the matrix such that the absolute difference between target and the sum of the chosen elements is minimized. Return the minimum absolute difference. The absolute difference between two numbers a and b is the absolute value of a - b. ", + "category": [ + "Array", + "Dynamic Programming", + "Matrix" + ], + "complexity": "Medium", + "successrate": 32.7, + "totalsubmissions": 44943, + "totalaccepted": 14696, + "likes": 478, + "dislikes": 89, + "hints": "The sum of chosen elements will not be too large. Consider using a hash set to record all possible sums while iterating each row. Instead of keeping track of all possible sums, since in each row, we are adding positive numbers, only keep those that can be a candidate, not exceeding the target by too much.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "mat = [[1,2,3],[4,5,6],[7,8,9]], target = 13", + "expected_output": "0", + "explanation": "One possible choice is to:\n- Choose 1 from the first row.\n- Choose 5 from the second row.\n- Choose 7 from the third row.\nThe sum of the chosen elements is 13, which equals the target, so the absolute difference is 0." + }, + { + "example_num": 2, + "expected_input": "mat = [[1],[2],[3]], target = 100", + "expected_output": "94", + "explanation": "The best possible choice is to:\n- Choose 1 from the first row.\n- Choose 2 from the second row.\n- Choose 3 from the third row.\nThe sum of the chosen elements is 6, and the absolute difference is 94." + }, + { + "example_num": 3, + "expected_input": "mat = [[1,2,9,8,7]], target = 6", + "expected_output": "1", + "explanation": "The best choice is to choose 7 from the first row.\nThe absolute difference is 1." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720ead", + "questionid": 994, + "title": "Minimum Difference Between Highest and Lowest of K Scores", + "slug": "minimum-difference-between-highest-and-lowest-of-k-scores", + "description": "You are given a 0-indexed integer array nums, where nums[i] represents the score of the ith student. You are also given an integer k. Pick the scores of any k students from the array so that the difference between the highest and the lowest of the k scores is minimized. Return the minimum possible difference. ", + "category": [ + "Array", + "Sliding Window", + "Sorting" + ], + "complexity": "Easy", + "successrate": 53.7, + "totalsubmissions": 39714, + "totalaccepted": 21342, + "likes": 295, + "dislikes": 42, + "hints": "For the difference between the highest and lowest element to be minimized, the k chosen scores need to be as close to each other as possible. What if the array was sorted? After sorting the scores, any contiguous k scores are as close to each other as possible. Apply a sliding window solution to iterate over each contiguous k scores, and find the minimum of the differences of all windows.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [90], k = 1", + "expected_output": "0", + "explanation": "There is one way to pick score(s) of one student:\n- [90]. The difference between the highest and lowest score is 90 - 90 = 0.\nThe minimum possible difference is 0." + }, + { + "example_num": 2, + "expected_input": "nums = [9,4,1,7], k = 2", + "expected_output": "2", + "explanation": "There are six ways to pick score(s) of two students:\n- [9,4,1,7]. The difference between the highest and lowest score is 9 - 4 = 5.\n- [9,4,1,7]. The difference between the highest and lowest score is 9 - 1 = 8.\n- [9,4,1,7]. The difference between the highest and lowest score is 9 - 7 = 2.\n- [9,4,1,7]. The difference between the highest and lowest score is 4 - 1 = 3.\n- [9,4,1,7]. The difference between the highest and lowest score is 7 - 4 = 3.\n- [9,4,1,7]. The difference between the highest and lowest score is 7 - 1 = 6.\nThe minimum possible difference is 2." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720eb2", + "questionid": 999, + "title": "Number of Pairs of Interchangeable Rectangles", + "slug": "number-of-pairs-of-interchangeable-rectangles", + "description": "You are given n rectangles represented by a 0-indexed 2D integer array rectangles, where rectangles[i] = [widthi, heighti] denotes the width and height of the ith rectangle. Two rectangles i and j (i < j) are considered interchangeable if they have the same width-to-height ratio. More formally, two rectangles are interchangeable if widthi/heighti == widthj/heightj (using decimal division, not integer division). Return the number of pairs of interchangeable rectangles in rectangles. ", + "category": [ + "Array", + "Hash Table", + "Math", + "Counting", + "Number Theory" + ], + "complexity": "Medium", + "successrate": 43, + "totalsubmissions": 36412, + "totalaccepted": 15645, + "likes": 212, + "dislikes": 20, + "hints": "Store the rectangle height and width ratio in a hashmap. Traverse the ratios, and for each ratio, use the frequency of the ratio to add to the total pair count.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "rectangles = [[4,8],[3,6],[10,20],[15,30]]", + "expected_output": "6", + "explanation": "The following are the interchangeable pairs of rectangles by index (0-indexed):\n- Rectangle 0 with rectangle 1: 4/8 == 3/6.\n- Rectangle 0 with rectangle 2: 4/8 == 10/20.\n- Rectangle 0 with rectangle 3: 4/8 == 15/30.\n- Rectangle 1 with rectangle 2: 3/6 == 10/20.\n- Rectangle 1 with rectangle 3: 3/6 == 15/30.\n- Rectangle 2 with rectangle 3: 10/20 == 15/30." + }, + { + "example_num": 2, + "expected_input": "rectangles = [[4,5],[7,8]]", + "expected_output": "0", + "explanation": "There are no interchangeable pairs of rectangles." + } + ] + }, + { + "_id": "66f925ddfdfb8e1665720eb3", + "questionid": 1000, + "title": "Maximum Product of the Length of Two Palindromic Subsequences", + "slug": "maximum-product-of-the-length-of-two-palindromic-subsequences", + "description": "Given a string s, find two disjoint palindromic subsequences of s such that the product of their lengths is maximized. The two subsequences are disjoint if they do not both pick a character at the same index. Return the maximum possible product of the lengths of the two palindromic subsequences. A subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters. A string is palindromic if it reads the same forward and backward. ", + "category": [ + "String", + "Dynamic Programming", + "Backtracking", + "Bit Manipulation", + "Bitmask" + ], + "complexity": "Medium", + "successrate": 52.8, + "totalsubmissions": 21493, + "totalaccepted": 11339, + "likes": 436, + "dislikes": 30, + "hints": "Could you generate all possible pairs of disjoint subsequences? Could you find the maximum length palindrome in each subsequence for a pair of disjoint subsequences?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "leetcodecom"", + "expected_output": "9\nExplanation: An optimal solution is to choose "ete" for the 1st subsequence and "cdc" for the 2nd subsequence.\nThe product of their lengths is: 3 * 3 = 9.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "s = "bb"", + "expected_output": "1\nExplanation: An optimal solution is to choose "b" (the first character) for the 1st subsequence and "b" (the second character) for the 2nd subsequence.\nThe product of their lengths is: 1 * 1 = 1.", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "s = "accbcaxxcxx"", + "expected_output": "25\nExplanation: An optimal solution is to choose "accca" for the 1st subsequence and "xxcxx" for the 2nd subsequence.\nThe product of their lengths is: 5 * 5 = 25.", + "explanation": "" + } + ] + }, + { + "_id": "66f925defdfb8e1665720eb6", + "questionid": 1003, + "title": "Number of Pairs of Strings With Concatenation Equal to Target", + "slug": "number-of-pairs-of-strings-with-concatenation-equal-to-target", + "description": "Given an array of digit strings nums and a digit string target, return the number of pairs of indices (i, j) (where i != j) such that the concatenation of nums[i] + nums[j] equals target. ", + "category": [ + "Array", + "String" + ], + "complexity": "Medium", + "successrate": 73, + "totalsubmissions": 23817, + "totalaccepted": 17394, + "likes": 278, + "dislikes": 26, + "hints": "Try to concatenate every two different strings from the list. Count the number of pairs with concatenation equals to target.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = ["777","7","77","77"], target = "7777"", + "expected_output": "4", + "explanation": "Valid pairs are:\n- (0, 1): "777" + "7"\n- (1, 0): "7" + "777"\n- (2, 3): "77" + "77"\n- (3, 2): "77" + "77"" + }, + { + "example_num": 2, + "expected_input": "nums = ["123","4","12","34"], target = "1234"", + "expected_output": "2", + "explanation": "Valid pairs are:\n- (0, 1): "123" + "4"\n- (2, 3): "12" + "34"" + }, + { + "example_num": 3, + "expected_input": "nums = ["1","1","1"], target = "11"", + "expected_output": "6", + "explanation": "Valid pairs are:\n- (0, 1): "1" + "1"\n- (1, 0): "1" + "1"\n- (0, 2): "1" + "1"\n- (2, 0): "1" + "1"\n- (1, 2): "1" + "1"\n- (2, 1): "1" + "1"" + } + ] + }, + { + "_id": "66f925defdfb8e1665720eb7", + "questionid": 1004, + "title": "Longest Subsequence Repeated k Times", + "slug": "longest-subsequence-repeated-k-times", + "description": "You are given a string s of length n, and an integer k. You are tasked to find the longest subsequence repeated k times in string s. A subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters. A subsequence seq is repeated k times in the string s if seq * k is a subsequence of s, where seq * k represents a string constructed by concatenating seq k times. Return the longest subsequence repeated k times in string s. If multiple such subsequences are found, return the lexicographically largest one. If there is no such subsequence, return an empty string. ", + "category": [ + "String", + "Backtracking", + "Greedy", + "Counting", + "Enumeration" + ], + "complexity": "Hard", + "successrate": 54.7, + "totalsubmissions": 7316, + "totalaccepted": 4005, + "likes": 185, + "dislikes": 52, + "hints": "The length of the longest subsequence does not exceed n/k. Do you know why? Find the characters that could be included in the potential answer. A character occurring more than or equal to k times can be used in the answer up to (count of the character / k) times. Try all possible candidates in reverse lexicographic order, and check the string for the subsequence condition.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "letsleetcode", k = 2", + "expected_output": ""let"", + "explanation": "There are two longest subsequences repeated 2 times: "let" and "ete".\n"let" is the lexicographically largest one." + }, + { + "example_num": 2, + "expected_input": "s = "bb", k = 2", + "expected_output": ""b"", + "explanation": "The longest subsequence repeated 2 times is "b"." + }, + { + "example_num": 3, + "expected_input": "s = "ab", k = 2", + "expected_output": """", + "explanation": "There is no subsequence repeated 2 times. Empty string is returned." + } + ] + }, + { + "_id": "66f925defdfb8e1665720ec1", + "questionid": 1014, + "title": "Kth Distinct String in an Array", + "slug": "kth-distinct-string-in-an-array", + "description": "A distinct string is a string that is present only once in an array. Given an array of strings arr, and an integer k, return the kth distinct string present in arr. If there are fewer than k distinct strings, return an empty string \"\". Note that the strings are considered in the order in which they appear in the array. ", + "category": [ + "Array", + "Hash Table", + "String", + "Counting" + ], + "complexity": "Easy", + "successrate": 72.9, + "totalsubmissions": 29728, + "totalaccepted": 21680, + "likes": 288, + "dislikes": 6, + "hints": "Try 'mapping' the strings to check if they are unique or not.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "arr = ["d","b","c","b","c","a"], k = 2", + "expected_output": ""a"", + "explanation": "The only distinct strings in arr are "d" and "a".\n"d" appears 1st, so it is the 1st distinct string.\n"a" appears 2nd, so it is the 2nd distinct string.\nSince k == 2, "a" is returned." + }, + { + "example_num": 2, + "expected_input": "arr = ["aaa","aa","a"], k = 1", + "expected_output": ""aaa"", + "explanation": "All strings in arr are distinct, so the 1st string "aaa" is returned." + }, + { + "example_num": 3, + "expected_input": "arr = ["a","b","a"], k = 3", + "expected_output": """", + "explanation": "The only distinct string is "b". Since there are fewer than 3 distinct strings, we return an empty string ""." + } + ] + }, + { + "_id": "66f925defdfb8e1665720ec2", + "questionid": 1015, + "title": "Plates Between Candles", + "slug": "plates-between-candles", + "description": "There is a long table with a line of plates and candles arranged on top of it. You are given a 0-indexed string s consisting of characters '*' and '|' only, where a '*' represents a plate and a '|' represents a candle. You are also given a 0-indexed 2D integer array queries where queries[i] = [lefti, righti] denotes the substring s[lefti...righti] (inclusive). For each query, you need to find the number of plates between candles that are in the substring. A plate is considered between candles if there is at least one candle to its left and at least one candle to its right in the substring. Return an integer array answer where answer[i] is the answer to the ith query. ", + "category": [ + "Array", + "String", + "Binary Search", + "Prefix Sum" + ], + "complexity": "Medium", + "successrate": 46, + "totalsubmissions": 22217, + "totalaccepted": 10217, + "likes": 381, + "dislikes": 10, + "hints": "Can you find the indices of the most left and right candles for a given substring, perhaps by using binary search (or better) over an array of indices of all the bars? Once the indices of the most left and right bars are determined, how can you efficiently count the number of plates within the range? Prefix sums?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "**|**|***|", queries = [[2,5],[5,9]]", + "expected_output": "[2,3]", + "explanation": "- queries[0] has two plates between candles.\n- queries[1] has three plates between candles." + }, + { + "example_num": 2, + "expected_input": "s = "***|**|*****|**||**|*", queries = [[1,17],[4,5],[14,17],[5,11],[15,16]]", + "expected_output": "[9,0,0,0,0]", + "explanation": "- queries[0] has nine plates between candles.\n- The other queries have zero plates between candles." + } + ] + }, + { + "_id": "66f925defdfb8e1665720ec4", + "questionid": 1017, + "title": "Count Number of Maximum Bitwise-OR Subsets", + "slug": "count-number-of-maximum-bitwise-or-subsets", + "description": "Given an integer array nums, find the maximum possible bitwise OR of a subset of nums and return the number of different non-empty subsets with the maximum bitwise OR. An array a is a subset of an array b if a can be obtained from b by deleting some (possibly zero) elements of b. Two subsets are considered different if the indices of the elements chosen are different. The bitwise OR of an array a is equal to a[0] OR a[1] OR ... OR a[a.length - 1] (0-indexed). ", + "category": [ + "Array", + "Backtracking", + "Bit Manipulation" + ], + "complexity": "Medium", + "successrate": 74.8, + "totalsubmissions": 17312, + "totalaccepted": 12945, + "likes": 246, + "dislikes": 13, + "hints": "Can we enumerate all possible subsets? The maximum bitwise-OR is the bitwise-OR of the whole array.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [3,1]", + "expected_output": "2", + "explanation": "The maximum possible bitwise OR of a subset is 3. There are 2 subsets with a bitwise OR of 3:\n- [3]\n- [3,1]" + }, + { + "example_num": 2, + "expected_input": "nums = [2,2,2]", + "expected_output": "7", + "explanation": "All non-empty subsets of [2,2,2] have a bitwise OR of 2. There are 23 - 1 = 7 total subsets." + }, + { + "example_num": 3, + "expected_input": "nums = [3,2,1,5]", + "expected_output": "6", + "explanation": "The maximum possible bitwise OR of a subset is 7. There are 6 subsets with a bitwise OR of 7:\n- [3,5]\n- [3,1,5]\n- [3,2,5]\n- [3,2,1,5]\n- [2,5]\n- [2,1,5]" + } + ] + }, + { + "_id": "66f925defdfb8e1665720ecb", + "questionid": 1024, + "title": "Find the Minimum and Maximum Number of Nodes Between Critical Points", + "slug": "find-the-minimum-and-maximum-number-of-nodes-between-critical-points", + "description": "A critical point in a linked list is defined as either a local maxima or a local minima. A node is a local maxima if the current node has a value strictly greater than the previous node and the next node. A node is a local minima if the current node has a value strictly smaller than the previous node and the next node. Note that a node can only be a local maxima/minima if there exists both a previous node and a next node. Given a linked list head, return an array of length 2 containing [minDistance, maxDistance] where minDistance is the minimum distance between any two distinct critical points and maxDistance is the maximum distance between any two distinct critical points. If there are fewer than two critical points, return [-1, -1]. ", + "category": [ + "Linked List" + ], + "complexity": "Medium", + "successrate": 57.7, + "totalsubmissions": 25922, + "totalaccepted": 14965, + "likes": 248, + "dislikes": 12, + "hints": "The maximum distance must be the distance between the first and last critical point. For each adjacent critical point, calculate the difference and check if it is the minimum distance.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "head = [3,1]", + "expected_output": "[-1,-1]", + "explanation": "There are no critical points in [3,1]." + }, + { + "example_num": 2, + "expected_input": "head = [5,3,1,2,5,1,2]", + "expected_output": "[1,3]", + "explanation": "There are three critical points:\n- [5,3,1,2,5,1,2]: The third node is a local minima because 1 is less than 3 and 2.\n- [5,3,1,2,5,1,2]: The fifth node is a local maxima because 5 is greater than 2 and 1.\n- [5,3,1,2,5,1,2]: The sixth node is a local minima because 1 is less than 5 and 2.\nThe minimum distance is between the fifth and the sixth node. minDistance = 6 - 5 = 1.\nThe maximum distance is between the third and the sixth node. maxDistance = 6 - 3 = 3." + }, + { + "example_num": 3, + "expected_input": "head = [1,3,2,2,3,2,2,2,7]", + "expected_output": "[3,3]", + "explanation": "There are two critical points:\n- [1,3,2,2,3,2,2,2,7]: The second node is a local maxima because 3 is greater than 1 and 2.\n- [1,3,2,2,3,2,2,2,7]: The fifth node is a local maxima because 3 is greater than 2 and 2.\nBoth the minimum and maximum distances are between the second and the fifth node.\nThus, minDistance and maxDistance is 5 - 2 = 3.\nNote that the last node is not considered a local maxima because it does not have a next node." + } + ] + }, + { + "_id": "66f925defdfb8e1665720ecf", + "questionid": 1028, + "title": "Time Needed to Buy Tickets", + "slug": "time-needed-to-buy-tickets", + "description": "There are n people in a line queuing to buy tickets, where the 0th person is at the front of the line and the (n - 1)th person is at the back of the line. You are given a 0-indexed integer array tickets of length n where the number of tickets that the ith person would like to buy is tickets[i]. Each person takes exactly 1 second to buy a ticket. A person can only buy 1 ticket at a time and has to go back to the end of the line (which happens instantaneously) in order to buy more tickets. If a person does not have any tickets left to buy, the person will leave the line. Return the time taken for the person at position k (0-indexed) to finish buying tickets. ", + "category": [ + "Array", + "Queue", + "Simulation" + ], + "complexity": "Easy", + "successrate": 62.4, + "totalsubmissions": 33581, + "totalaccepted": 20942, + "likes": 329, + "dislikes": 22, + "hints": "Loop through the line of people and decrement the number of tickets for each to buy one at a time as if simulating the line moving forward. Keep track of how many tickets have been sold up until person k has no more tickets to buy. Remember that those who have no more tickets to buy will leave the line.", + "deleted": false, + "examples": [] + }, + { + "_id": "66f925defdfb8e1665720edc", + "questionid": 1041, + "title": "Sum of Subarray Ranges", + "slug": "sum-of-subarray-ranges", + "description": "You are given an integer array nums. The range of a subarray of nums is the difference between the largest and smallest element in the subarray. Return the sum of all subarray ranges of nums. A subarray is a contiguous non-empty sequence of elements within an array. ", + "category": [ + "Array", + "Stack", + "Monotonic Stack" + ], + "complexity": "Medium", + "successrate": 60.3, + "totalsubmissions": 39464, + "totalaccepted": 23805, + "likes": 626, + "dislikes": 29, + "hints": "Can you get the max/min of a certain subarray by using the max/min of a smaller subarray within it? Notice that the max of the subarray from index i to j is equal to max of (max of the subarray from index i to j-1) and nums[j].", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,2,3]", + "expected_output": "4", + "explanation": "The 6 subarrays of nums are the following:\n[1], range = largest - smallest = 1 - 1 = 0 \n[2], range = 2 - 2 = 0\n[3], range = 3 - 3 = 0\n[1,2], range = 2 - 1 = 1\n[2,3], range = 3 - 2 = 1\n[1,2,3], range = 3 - 1 = 2\nSo the sum of all ranges is 0 + 0 + 0 + 1 + 1 + 2 = 4." + }, + { + "example_num": 2, + "expected_input": "nums = [1,3,3]", + "expected_output": "4", + "explanation": "The 6 subarrays of nums are the following:\n[1], range = largest - smallest = 1 - 1 = 0\n[3], range = 3 - 3 = 0\n[3], range = 3 - 3 = 0\n[1,3], range = 3 - 1 = 2\n[3,3], range = 3 - 3 = 0\n[1,3,3], range = 3 - 1 = 2\nSo the sum of all ranges is 0 + 0 + 0 + 2 + 0 + 2 = 4." + }, + { + "example_num": 3, + "expected_input": "nums = [4,-2,-3,4,1]", + "expected_output": "59", + "explanation": "The sum of all subarray ranges of nums is 59." + } + ] + }, + { + "_id": "66f925defdfb8e1665720ee1", + "questionid": 1046, + "title": "Minimum Operations to Make the Array K-Increasing", + "slug": "minimum-operations-to-make-the-array-k-increasing", + "description": "You are given a 0-indexed array arr consisting of n positive integers, and a positive integer k. The array arr is called K-increasing if arr[i-k] <= arr[i] holds for every index i, where k <= i <= n-1. In one operation, you can choose an index i and change arr[i] into any positive integer. Return the minimum number of operations required to make the array K-increasing for the given k. ", + "category": [ + "Array", + "Binary Search" + ], + "complexity": "Hard", + "successrate": 36.4, + "totalsubmissions": 23198, + "totalaccepted": 8433, + "likes": 467, + "dislikes": 8, + "hints": "Can we divide the array into non-overlapping subsequences and simplify the problem? In the final array, arr[i-k] ‰¤ arr[i] should hold. We can use this to divide the array into at most k non-overlapping sequences, where arr[i] will belong to the (i%k)th sequence. Now our problem boils down to performing the minimum operations on each sequence such that it becomes non-decreasing. Our answer will be the sum of operations on each sequence. Which indices of a sequence should we not change in order to count the minimum operations? Can finding the longest non-decreasing subsequence of the sequence help?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "arr = [5,4,3,2,1], k = 1", + "expected_output": "4\nExplanation:\nFor k = 1, the resultant array has to be non-decreasing.\nSome of the K-increasing arrays that can be formed are [5,6,7,8,9], [1,1,1,1,1], [2,2,3,4,4]. All of them require 4 operations.\nIt is suboptimal to change the array to, for example, [6,7,8,9,10] because it would take 5 operations.\nIt can be shown that we cannot make the array K-increasing in less than 4 operations.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "arr = [4,1,5,2,6,2], k = 2", + "expected_output": "0", + "explanation": "This is the same example as the one in the problem description.\nHere, for every index i where 2 <= i <= 5, arr[i-2] <= arr[i].\nSince the given array is already K-increasing, we do not need to perform any operations." + }, + { + "example_num": 3, + "expected_input": "arr = [4,1,5,2,6,2], k = 3", + "expected_output": "2", + "explanation": "Indices 3 and 5 are the only ones not satisfying arr[i-3] <= arr[i] for 3 <= i <= 5.\nOne of the ways we can make the array K-increasing is by changing arr[3] to 4 and arr[5] to 5.\nThe array will now be [4,1,5,4,6,5].\nNote that there can be other ways to make the array K-increasing, but none of them require less than 2 operations." + } + ] + }, + { + "_id": "66f925defdfb8e1665720ee3", + "questionid": 1048, + "title": "Longest Palindrome by Concatenating Two Letter Words", + "slug": "longest-palindrome-by-concatenating-two-letter-words", + "description": "You are given an array of strings words. Each element of words consists of two lowercase English letters. Create the longest possible palindrome by selecting some elements from words and concatenating them in any order. Each element can be selected at most once. Return the length of the longest palindrome that you can create. If it is impossible to create any palindrome, return 0. A palindrome is a string that reads the same forward and backward. ", + "category": [ + "Array", + "Hash Table", + "String", + "Greedy", + "Counting" + ], + "complexity": "Medium", + "successrate": 38.3, + "totalsubmissions": 33870, + "totalaccepted": 12956, + "likes": 381, + "dislikes": 8, + "hints": "A palindrome must be mirrored over the center. Suppose we have a palindrome. If we prepend the word \"ab\" on the left, what must we append on the right to keep it a palindrome? We must append \"ba\" on the right. The number of times we can do this is the minimum of (occurrences of \"ab\") and (occurrences of \"ba\"). For words that are already palindromes, e.g. \"aa\", we can prepend and append these in pairs as described in the previous hint. We can also use exactly one in the middle to form an even longer palindrome.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "words = ["lc","cl","gg"]", + "expected_output": "6", + "explanation": "One longest palindrome is "lc" + "gg" + "cl" = "lcggcl", of length 6.\nNote that "clgglc" is another longest palindrome that can be created." + }, + { + "example_num": 2, + "expected_input": "words = ["ab","ty","yt","lc","cl","ab"]", + "expected_output": "8", + "explanation": "One longest palindrome is "ty" + "lc" + "cl" + "yt" = "tylcclyt", of length 8.\nNote that "lcyttycl" is another longest palindrome that can be created." + }, + { + "example_num": 3, + "expected_input": "words = ["cc","ll","xx"]", + "expected_output": "2", + "explanation": "One longest palindrome is "cc", of length 2.\nNote that "ll" is another longest palindrome that can be created, and so is "xx"." + } + ] + }, + { + "_id": "66f925defdfb8e1665720ee6", + "questionid": 1051, + "title": "Destroying Asteroids", + "slug": "destroying-asteroids", + "description": "You are given an integer mass, which represents the original mass of a planet. You are further given an integer array asteroids, where asteroids[i] is the mass of the ith asteroid. You can arrange for the planet to collide with the asteroids in any arbitrary order. If the mass of the planet is greater than or equal to the mass of the asteroid, the asteroid is destroyed and the planet gains the mass of the asteroid. Otherwise, the planet is destroyed. Return true if all asteroids can be destroyed. Otherwise, return false. ", + "category": [ + "Array", + "Greedy", + "Sorting" + ], + "complexity": "Medium", + "successrate": 48.4, + "totalsubmissions": 37728, + "totalaccepted": 18243, + "likes": 198, + "dislikes": 106, + "hints": "Choosing the asteroid to collide with can be done greedily. If an asteroid will destroy the planet, then every bigger asteroid will also destroy the planet. You only need to check the smallest asteroid at each collision. If it will destroy the planet, then every other asteroid will also destroy the planet. Sort the asteroids in non-decreasing order by mass, then greedily try to collide with the asteroids in that order.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "mass = 10, asteroids = [3,9,19,5,21]", + "expected_output": "true", + "explanation": "One way to order the asteroids is [9,19,5,3,21]:\n- The planet collides with the asteroid with a mass of 9. New planet mass: 10 + 9 = 19\n- The planet collides with the asteroid with a mass of 19. New planet mass: 19 + 19 = 38\n- The planet collides with the asteroid with a mass of 5. New planet mass: 38 + 5 = 43\n- The planet collides with the asteroid with a mass of 3. New planet mass: 43 + 3 = 46\n- The planet collides with the asteroid with a mass of 21. New planet mass: 46 + 21 = 67\nAll asteroids are destroyed." + }, + { + "example_num": 2, + "expected_input": "mass = 5, asteroids = [4,9,23,4]", + "expected_output": "false", + "explanation": "The planet cannot ever gain enough mass to destroy the asteroid with a mass of 23.\nAfter the planet destroys the other asteroids, it will have a mass of 5 + 4 + 9 + 4 = 22.\nThis is less than 23, so a collision would not destroy the last asteroid." + } + ] + }, + { + "_id": "66f925defdfb8e1665720ee9", + "questionid": 1054, + "title": "Count the Hidden Sequences", + "slug": "count-the-hidden-sequences", + "description": "You are given a 0-indexed array of n integers differences, which describes the differences between each pair of consecutive integers of a hidden sequence of length (n + 1). More formally, call the hidden sequence hidden, then we have that differences[i] = hidden[i + 1] - hidden[i]. You are further given two integers lower and upper that describe the inclusive range of values [lower, upper] that the hidden sequence can contain. Return the number of possible hidden sequences there are. If there are no possible sequences, return 0. ", + "category": [ + "Array", + "Prefix Sum" + ], + "complexity": "Medium", + "successrate": 35.1, + "totalsubmissions": 32252, + "totalaccepted": 11334, + "likes": 356, + "dislikes": 37, + "hints": "Fix the first element of the hidden sequence to any value x and ignore the given bounds. Notice that we can then determine all the other elements of the sequence by using the differences array. We will also be able to determine the difference between the minimum and maximum elements of the sequence. Notice that the value of x does not affect this. We now have the €˜range€™ of the sequence (difference between min and max element), we can then calculate how many ways there are to fit this range into the given range of lower to upper. Answer is (upper - lower + 1) - (range of sequence)", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "differences = [1,-3,4], lower = 1, upper = 6", + "expected_output": "2", + "explanation": "The possible hidden sequences are:\n- [3, 4, 1, 5]\n- [4, 5, 2, 6]\nThus, we return 2." + }, + { + "example_num": 2, + "expected_input": "differences = [3,-4,5,1,-2], lower = -4, upper = 5", + "expected_output": "4", + "explanation": "The possible hidden sequences are:\n- [-3, 0, -4, 1, 2, 0]\n- [-2, 1, -3, 2, 3, 1]\n- [-1, 2, -2, 3, 4, 2]\n- [0, 3, -1, 4, 5, 3]\nThus, we return 4." + }, + { + "example_num": 3, + "expected_input": "differences = [4,-7,2], lower = 3, upper = 6", + "expected_output": "0", + "explanation": "There are no possible hidden sequences. Thus, we return 0." + } + ] + }, + { + "_id": "66f925defdfb8e1665720eeb", + "questionid": 1056, + "title": "Check if Every Row and Column Contains All Numbers", + "slug": "check-if-every-row-and-column-contains-all-numbers", + "description": "An n x n matrix is valid if every row and every column contains all the integers from 1 to n (inclusive). Given an n x n integer matrix matrix, return true if the matrix is valid. Otherwise, return false. ", + "category": [ + "Array", + "Hash Table", + "Matrix" + ], + "complexity": "Easy", + "successrate": 52.2, + "totalsubmissions": 49781, + "totalaccepted": 25978, + "likes": 309, + "dislikes": 19, + "hints": "Use for loops to check each row for every number from 1 to n. Similarly, do the same for each column. For each check, you can keep a set of the unique elements in the checked row/col. By the end of the check, the size of the set should be n.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "matrix = [[1,2,3],[3,1,2],[2,3,1]]", + "expected_output": "true", + "explanation": "In this case, n = 3, and every row and column contains the numbers 1, 2, and 3.\nHence, we return true." + }, + { + "example_num": 2, + "expected_input": "matrix = [[1,1,1],[1,2,3],[1,2,3]]", + "expected_output": "false", + "explanation": "In this case, n = 3, but the first row and the first column do not contain the numbers 2 or 3.\nHence, we return false." + } + ] + }, + { + "_id": "66f925defdfb8e1665720ef0", + "questionid": 1061, + "title": "Count Elements With Strictly Smaller and Greater Elements ", + "slug": "count-elements-with-strictly-smaller-and-greater-elements", + "description": "Given an integer array nums, return the number of elements that have both a strictly smaller and a strictly greater element appear in nums. ", + "category": [ + "Array", + "Sorting" + ], + "complexity": "Easy", + "successrate": 60.5, + "totalsubmissions": 42268, + "totalaccepted": 25577, + "likes": 243, + "dislikes": 7, + "hints": "All the elements in the array should be counted except for the minimum and maximum elements. If the array has n elements, the answer will be n - count(min(nums)) - count(max(nums)) This formula will not work in case the array has all the elements equal, why?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [11,7,2,15]", + "expected_output": "2", + "explanation": "The element 7 has the element 2 strictly smaller than it and the element 11 strictly greater than it.\nElement 11 has element 7 strictly smaller than it and element 15 strictly greater than it.\nIn total there are 2 elements having both a strictly smaller and a strictly greater element appear in nums." + }, + { + "example_num": 2, + "expected_input": "nums = [-3,3,3,90]", + "expected_output": "2", + "explanation": "The element 3 has the element -3 strictly smaller than it and the element 90 strictly greater than it.\nSince there are two elements with the value 3, in total there are 2 elements having both a strictly smaller and a strictly greater element appear in nums." + } + ] + }, + { + "_id": "66f925defdfb8e1665720ef5", + "questionid": 1066, + "title": "Smallest Value of the Rearranged Number", + "slug": "smallest-value-of-the-rearranged-number", + "description": "You are given an integer num. Rearrange the digits of num such that its value is minimized and it does not contain any leading zeros. Return the rearranged number with minimal value. Note that the sign of the number does not change after rearranging the digits. ", + "category": [ + "Math", + "Sorting" + ], + "complexity": "Medium", + "successrate": 50.7, + "totalsubmissions": 39260, + "totalaccepted": 19915, + "likes": 287, + "dislikes": 9, + "hints": "For positive numbers, the leading digit should be the smallest nonzero digit. Then the remaining digits follow in ascending order. For negative numbers, the digits should be arranged in descending order.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "num = 310", + "expected_output": "103", + "explanation": "The possible arrangements for the digits of 310 are 013, 031, 103, 130, 301, 310. \nThe arrangement with the smallest value that does not contain any leading zeros is 103." + }, + { + "example_num": 2, + "expected_input": "num = -7605", + "expected_output": "-7650", + "explanation": "Some possible arrangements for the digits of -7605 are -7650, -6705, -5076, -0567.\nThe arrangement with the smallest value that does not contain any leading zeros is -7650." + } + ] + }, + { + "_id": "66f925defdfb8e1665720ef6", + "questionid": 1067, + "title": "Count Operations to Obtain Zero", + "slug": "count-operations-to-obtain-zero", + "description": "You are given two non-negative integers num1 and num2. In one operation, if num1 >= num2, you must subtract num2 from num1, otherwise subtract num1 from num2. Return the number of operations required to make either num1 = 0 or num2 = 0. ", + "category": [ + "Math", + "Simulation" + ], + "complexity": "Easy", + "successrate": 75.3, + "totalsubmissions": 36407, + "totalaccepted": 27423, + "likes": 200, + "dislikes": 5, + "hints": "Try simulating the process until either of the two integers is zero. Count the number of operations done.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "num1 = 2, num2 = 3", + "expected_output": "3", + "explanation": "- Operation 1: num1 = 2, num2 = 3. Since num1 < num2, we subtract num1 from num2 and get num1 = 2, num2 = 3 - 2 = 1.\n- Operation 2: num1 = 2, num2 = 1. Since num1 > num2, we subtract num2 from num1.\n- Operation 3: num1 = 1, num2 = 1. Since num1 == num2, we subtract num2 from num1.\nNow num1 = 0 and num2 = 1. Since num1 == 0, we do not need to perform any further operations.\nSo the total number of operations required is 3." + }, + { + "example_num": 2, + "expected_input": "num1 = 10, num2 = 10", + "expected_output": "1", + "explanation": "- Operation 1: num1 = 10, num2 = 10. Since num1 == num2, we subtract num2 from num1 and get num1 = 10 - 10 = 0.\nNow num1 = 0 and num2 = 10. Since num1 == 0, we are done.\nSo the total number of operations required is 1." + } + ] + }, + { + "_id": "66f925defdfb8e1665720ef7", + "questionid": 1068, + "title": "Removing Minimum Number of Magic Beans", + "slug": "removing-minimum-number-of-magic-beans", + "description": "You are given an array of positive integers beans, where each integer represents the number of magic beans found in a particular magic bag. Remove any number of beans (possibly none) from each bag such that the number of beans in each remaining non-empty bag (still containing at least one bean) is equal. Once a bean has been removed from a bag, you are not allowed to return it to any of the bags. Return the minimum number of magic beans that you have to remove. ", + "category": [ + "Array", + "Sorting", + "Prefix Sum" + ], + "complexity": "Medium", + "successrate": 40.9, + "totalsubmissions": 34492, + "totalaccepted": 14124, + "likes": 456, + "dislikes": 26, + "hints": "Notice that if we choose to make x bags of beans empty, we should choose the x bags with the least amount of beans. Notice that if the minimum number of beans in a non-empty bag is m, then the best way to make all bags have an equal amount of beans is to reduce all the bags to have m beans. Can we iterate over how many bags we should remove and choose the one that minimizes the total amount of beans to remove? Sort the bags of beans first.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "beans = [4,1,6,5]", + "expected_output": "4", + "explanation": "- We remove 1 bean from the bag with only 1 bean.\n This results in the remaining bags: [4,0,6,5]\n- Then we remove 2 beans from the bag with 6 beans.\n This results in the remaining bags: [4,0,4,5]\n- Then we remove 1 bean from the bag with 5 beans.\n This results in the remaining bags: [4,0,4,4]\nWe removed a total of 1 + 2 + 1 = 4 beans to make the remaining non-empty bags have an equal number of beans.\nThere are no other solutions that remove 4 beans or fewer." + }, + { + "example_num": 2, + "expected_input": "beans = [2,10,3,2]", + "expected_output": "7", + "explanation": "- We remove 2 beans from one of the bags with 2 beans.\n This results in the remaining bags: [0,10,3,2]\n- Then we remove 2 beans from the other bag with 2 beans.\n This results in the remaining bags: [0,10,3,0]\n- Then we remove 3 beans from the bag with 3 beans. \n This results in the remaining bags: [0,10,0,0]\nWe removed a total of 2 + 2 + 3 = 7 beans to make the remaining non-empty bags have an equal number of beans.\nThere are no other solutions that removes 7 beans or fewer." + } + ] + }, + { + "_id": "66f925defdfb8e1665720efc", + "questionid": 1073, + "title": "Minimum Time to Finish the Race", + "slug": "minimum-time-to-finish-the-race", + "description": "You are given a 0-indexed 2D integer array tires where tires[i] = [fi, ri] indicates that the ith tire can finish its xth successive lap in fi * ri(x-1) seconds. You are also given an integer changeTime and an integer numLaps. The race consists of numLaps laps and you may start the race with any tire. You have an unlimited supply of each tire and after every lap, you may change to any given tire (including the current tire type) if you wait changeTime seconds. Return the minimum time to finish the race. ", + "category": [ + "Array", + "Dynamic Programming" + ], + "complexity": "Hard", + "successrate": 40.4, + "totalsubmissions": 14102, + "totalaccepted": 5697, + "likes": 315, + "dislikes": 9, + "hints": "What is the maximum number of times we would want to go around the track without changing tires? Can we precompute the minimum time to go around the track x times without changing tires? Can we use dynamic programming to solve this efficiently using the precomputed values?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "tires = [[2,3],[3,4]], changeTime = 5, numLaps = 4", + "expected_output": "21", + "explanation": "Lap 1: Start with tire 0 and finish the lap in 2 seconds.\nLap 2: Continue with tire 0 and finish the lap in 2 * 3 = 6 seconds.\nLap 3: Change tires to a new tire 0 for 5 seconds and then finish the lap in another 2 seconds.\nLap 4: Continue with tire 0 and finish the lap in 2 * 3 = 6 seconds.\nTotal time = 2 + 6 + 5 + 2 + 6 = 21 seconds.\nThe minimum time to complete the race is 21 seconds." + }, + { + "example_num": 2, + "expected_input": "tires = [[1,10],[2,2],[3,4]], changeTime = 6, numLaps = 5", + "expected_output": "25", + "explanation": "Lap 1: Start with tire 1 and finish the lap in 2 seconds.\nLap 2: Continue with tire 1 and finish the lap in 2 * 2 = 4 seconds.\nLap 3: Change tires to a new tire 1 for 6 seconds and then finish the lap in another 2 seconds.\nLap 4: Continue with tire 1 and finish the lap in 2 * 2 = 4 seconds.\nLap 5: Change tires to tire 0 for 6 seconds then finish the lap in another 1 second.\nTotal time = 2 + 4 + 6 + 2 + 4 + 6 + 1 = 25 seconds.\nThe minimum time to complete the race is 25 seconds." + } + ] + }, + { + "_id": "66f925defdfb8e1665720efd", + "questionid": 1074, + "title": "Count Integers With Even Digit Sum", + "slug": "count-integers-with-even-digit-sum", + "description": "Given a positive integer num, return the number of positive integers less than or equal to num whose digit sums are even. The digit sum of a positive integer is the sum of all its digits. ", + "category": [ + "Math", + "Simulation" + ], + "complexity": "Easy", + "successrate": 64.8, + "totalsubmissions": 36506, + "totalaccepted": 23649, + "likes": 220, + "dislikes": 12, + "hints": "Iterate through all integers from 1 to num. For any integer, extract the individual digits to compute their sum and check if it is even.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "num = 4", + "expected_output": "2", + "explanation": "The only integers less than or equal to 4 whose digit sums are even are 2 and 4." + }, + { + "example_num": 2, + "expected_input": "num = 30", + "expected_output": "14", + "explanation": "The 14 integers less than or equal to 30 whose digit sums are even are\n2, 4, 6, 8, 11, 13, 15, 17, 19, 20, 22, 24, 26, and 28." + } + ] + }, + { + "_id": "66f925defdfb8e1665720f00", + "questionid": 1077, + "title": "Append K Integers With Minimal Sum", + "slug": "append-k-integers-with-minimal-sum", + "description": "You are given an integer array nums and an integer k. Append k unique positive integers that do not appear in nums to nums such that the resulting total sum is minimum. Return the sum of the k integers appended to nums. ", + "category": [ + "Array", + "Math", + "Greedy", + "Sorting" + ], + "complexity": "Medium", + "successrate": 22.9, + "totalsubmissions": 66897, + "totalaccepted": 15315, + "likes": 316, + "dislikes": 223, + "hints": "The k smallest numbers that do not appear in nums will result in the minimum sum. Recall that the sum of the first n positive numbers is equal to n * (n+1) / 2. Initialize the answer as the sum of 1 to k. Then, adjust the answer depending on the values in nums.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,4,25,10,25], k = 2", + "expected_output": "5", + "explanation": "The two unique positive integers that do not appear in nums which we append are 2 and 3.\nThe resulting sum of nums is 1 + 4 + 25 + 10 + 25 + 2 + 3 = 70, which is the minimum.\nThe sum of the two integers appended is 2 + 3 = 5, so we return 5." + }, + { + "example_num": 2, + "expected_input": "nums = [5,6], k = 6", + "expected_output": "25", + "explanation": "The six unique positive integers that do not appear in nums which we append are 1, 2, 3, 4, 7, and 8.\nThe resulting sum of nums is 5 + 6 + 1 + 2 + 3 + 4 + 7 + 8 = 36, which is the minimum. \nThe sum of the six integers appended is 1 + 2 + 3 + 4 + 7 + 8 = 25, so we return 25." + } + ] + }, + { + "_id": "66f925defdfb8e1665720f02", + "questionid": 1079, + "title": "Maximize Number of Subsequences in a String", + "slug": "maximize-number-of-subsequences-in-a-string", + "description": "You are given a 0-indexed string text and another 0-indexed string pattern of length 2, both of which consist of only lowercase English letters. You can add either pattern[0] or pattern[1] anywhere in text exactly once. Note that the character can be added even at the beginning or at the end of text. Return the maximum number of times pattern can occur as a subsequence of the modified text. A subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters. ", + "category": [ + "String", + "Greedy", + "Prefix Sum" + ], + "complexity": "Medium", + "successrate": 30.7, + "totalsubmissions": 33828, + "totalaccepted": 10383, + "likes": 215, + "dislikes": 12, + "hints": "Find the optimal position to add pattern[0] so that the number of subsequences is maximized. Similarly, find the optimal position to add pattern[1]. For each of the above cases, count the number of times the pattern occurs as a subsequence in text. The larger count is the required answer.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "text = "abdcdbc", pattern = "ac"", + "expected_output": "4", + "explanation": "If we add pattern[0] = 'a' in between text[1] and text[2], we get "abadcdbc". Now, the number of times "ac" occurs as a subsequence is 4.\nSome other strings which have 4 subsequences "ac" after adding a character to text are "aabdcdbc" and "abdacdbc".\nHowever, strings such as "abdcadbc", "abdccdbc", and "abdcdbcc", although obtainable, have only 3 subsequences "ac" and are thus suboptimal.\nIt can be shown that it is not possible to get more than 4 subsequences "ac" by adding only one character." + }, + { + "example_num": 2, + "expected_input": "text = "aabb", pattern = "ab"", + "expected_output": "6", + "explanation": "Some of the strings which can be obtained from text and have 6 subsequences "ab" are "aaabb", "aaabb", and "aabbb"." + } + ] + }, + { + "_id": "66f925defdfb8e1665720f04", + "questionid": 1081, + "title": "Count Hills and Valleys in an Array", + "slug": "count-hills-and-valleys-in-an-array", + "description": "You are given a 0-indexed integer array nums. An index i is part of a hill in nums if the closest non-equal neighbors of i are smaller than nums[i]. Similarly, an index i is part of a valley in nums if the closest non-equal neighbors of i are larger than nums[i]. Adjacent indices i and j are part of the same hill or valley if nums[i] == nums[j]. Note that for an index to be part of a hill or valley, it must have a non-equal neighbor on both the left and right of the index. Return the number of hills and valleys in nums. ", + "category": [ + "Array" + ], + "complexity": "Easy", + "successrate": 56.3, + "totalsubmissions": 30741, + "totalaccepted": 17316, + "likes": 184, + "dislikes": 44, + "hints": "For each index, could you find the closest non-equal neighbors? Ensure that adjacent indices that are part of the same hill or valley are not double-counted.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [2,4,1,1,6,5]", + "expected_output": "3", + "explanation": "At index 0: There is no non-equal neighbor of 2 on the left, so index 0 is neither a hill nor a valley.\nAt index 1: The closest non-equal neighbors of 4 are 2 and 1. Since 4 > 2 and 4 > 1, index 1 is a hill. \nAt index 2: The closest non-equal neighbors of 1 are 4 and 6. Since 1 < 4 and 1 < 6, index 2 is a valley.\nAt index 3: The closest non-equal neighbors of 1 are 4 and 6. Since 1 < 4 and 1 < 6, index 3 is a valley, but note that it is part of the same valley as index 2.\nAt index 4: The closest non-equal neighbors of 6 are 1 and 5. Since 6 > 1 and 6 > 5, index 4 is a hill.\nAt index 5: There is no non-equal neighbor of 5 on the right, so index 5 is neither a hill nor a valley. \nThere are 3 hills and valleys so we return 3." + }, + { + "example_num": 2, + "expected_input": "nums = [6,6,5,5,4,1]", + "expected_output": "0", + "explanation": "At index 0: There is no non-equal neighbor of 6 on the left, so index 0 is neither a hill nor a valley.\nAt index 1: There is no non-equal neighbor of 6 on the left, so index 1 is neither a hill nor a valley.\nAt index 2: The closest non-equal neighbors of 5 are 6 and 4. Since 5 < 6 and 5 > 4, index 2 is neither a hill nor a valley.\nAt index 3: The closest non-equal neighbors of 5 are 6 and 4. Since 5 < 6 and 5 > 4, index 3 is neither a hill nor a valley.\nAt index 4: The closest non-equal neighbors of 4 are 5 and 1. Since 4 < 5 and 4 > 1, index 4 is neither a hill nor a valley.\nAt index 5: There is no non-equal neighbor of 1 on the right, so index 5 is neither a hill nor a valley.\nThere are 0 hills and valleys so we return 0." + } + ] + }, + { + "_id": "66f925defdfb8e1665720f09", + "questionid": 1086, + "title": "Sum of Scores of Built Strings", + "slug": "sum-of-scores-of-built-strings", + "description": "You are building a string s of length n one character at a time, prepending each new character to the front of the string. The strings are labeled from 1 to n, where the string with length i is labeled si. The score of si is the length of the longest common prefix between si and sn (Note that s == sn). Given the final string s, return the sum of the score of every si. ", + "category": [ + "String", + "Binary Search", + "Rolling Hash", + "Suffix Array", + "String Matching", + "Hash Function" + ], + "complexity": "Hard", + "successrate": 32.9, + "totalsubmissions": 9479, + "totalaccepted": 3120, + "likes": 110, + "dislikes": 146, + "hints": "Each s_i is a suffix of the string s, so consider algorithms that can determine the longest prefix that is also a suffix. Could you use the Z array from the Z algorithm to find the score of each s_i?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "babab"", + "expected_output": "9", + "explanation": "For s1 == "b", the longest common prefix is "b" which has a score of 1.\nFor s2 == "ab", there is no common prefix so the score is 0.\nFor s3 == "bab", the longest common prefix is "bab" which has a score of 3.\nFor s4 == "abab", there is no common prefix so the score is 0.\nFor s5 == "babab", the longest common prefix is "babab" which has a score of 5.\nThe sum of the scores is 1 + 0 + 3 + 0 + 5 = 9, so we return 9." + }, + { + "example_num": 2, + "expected_input": "s = "azbazbzaz"", + "expected_output": "14", + "explanation": "For s2 == "az", the longest common prefix is "az" which has a score of 2.\nFor s6 == "azbzaz", the longest common prefix is "azb" which has a score of 3.\nFor s9 == "azbazbzaz", the longest common prefix is "azbazbzaz" which has a score of 9.\nFor all other si, the score is 0.\nThe sum of the scores is 2 + 3 + 9 = 14, so we return 14." + } + ] + }, + { + "_id": "66f925defdfb8e1665720f0a", + "questionid": 1087, + "title": "Largest Number After Digit Swaps by Parity", + "slug": "largest-number-after-digit-swaps-by-parity", + "description": "You are given a positive integer num. You may swap any two digits of num that have the same parity (i.e. both odd digits or both even digits). Return the largest possible value of num after any number of swaps. ", + "category": [ + "Sorting", + "Heap (Priority Queue)" + ], + "complexity": "Easy", + "successrate": 56.4, + "totalsubmissions": 27114, + "totalaccepted": 15301, + "likes": 134, + "dislikes": 139, + "hints": "The bigger digit should appear first (more to the left) because it contributes more to the value of the number. Get all the even digits, as well as odd digits. Sort them separately. Reconstruct the number by giving the earlier digits the highest available digit of the same parity.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "num = 1234", + "expected_output": "3412", + "explanation": "Swap the digit 3 with the digit 1, this results in the number 3214.\nSwap the digit 2 with the digit 4, this results in the number 3412.\nNote that there may be other sequences of swaps but it can be shown that 3412 is the largest possible number.\nAlso note that we may not swap the digit 4 with the digit 1 since they are of different parities." + }, + { + "example_num": 2, + "expected_input": "num = 65875", + "expected_output": "87655", + "explanation": "Swap the digit 8 with the digit 6, this results in the number 85675.\nSwap the first digit 5 with the digit 7, this results in the number 87655.\nNote that there may be other sequences of swaps but it can be shown that 87655 is the largest possible number." + } + ] + }, + { + "_id": "66f925defdfb8e1665720eb8", + "questionid": 1005, + "title": "Maximum Difference Between Increasing Elements", + "slug": "maximum-difference-between-increasing-elements", + "description": "Given a 0-indexed integer array nums of size n, find the maximum difference between nums[i] and nums[j] (i.e., nums[j] - nums[i]), such that 0 <= i < j < n and nums[i] < nums[j]. Return the maximum difference. If no such i and j exists, return -1. ", + "category": [ + "Array" + ], + "complexity": "Easy", + "successrate": 54.6, + "totalsubmissions": 54942, + "totalaccepted": 30006, + "likes": 368, + "dislikes": 15, + "hints": "Could you keep track of the minimum element visited while traversing? We have a potential candidate for the answer if the prefix min is lesser than nums[i].", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [7,1,5,4]", + "expected_output": "4", + "explanation": "The maximum difference occurs with i = 1 and j = 2, nums[j] - nums[i] = 5 - 1 = 4.\nNote that with i = 1 and j = 0, the difference nums[j] - nums[i] = 7 - 1 = 6, but i > j, so it is not valid." + }, + { + "example_num": 2, + "expected_input": "nums = [9,4,3,2]", + "expected_output": "-1", + "explanation": "There is no i and j such that i < j and nums[i] < nums[j]." + }, + { + "example_num": 3, + "expected_input": "nums = [1,5,2,10]", + "expected_output": "9", + "explanation": "The maximum difference occurs with i = 0 and j = 3, nums[j] - nums[i] = 10 - 1 = 9." + } + ] + }, + { + "_id": "66f925defdfb8e1665720ebb", + "questionid": 1008, + "title": "Minimum Moves to Convert String", + "slug": "minimum-moves-to-convert-string", + "description": "You are given a string s consisting of n characters which are either 'X' or 'O'. A move is defined as selecting three consecutive characters of s and converting them to 'O'. Note that if a move is applied to the character 'O', it will stay the same. Return the minimum number of moves required so that all the characters of s are converted to 'O'. ", + "category": [ + "String", + "Greedy" + ], + "complexity": "Easy", + "successrate": 53.4, + "totalsubmissions": 33422, + "totalaccepted": 17856, + "likes": 198, + "dislikes": 46, + "hints": "Find the smallest substring you need to consider at a time. Try delaying a move as long as possible.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "XXX"", + "expected_output": "1", + "explanation": "XXX -> OOO\nWe select all the 3 characters and convert them in one move." + }, + { + "example_num": 2, + "expected_input": "s = "XXOX"", + "expected_output": "2", + "explanation": "XXOX -> OOOX -> OOOO\nWe select the first 3 characters in the first move, and convert them to 'O'.\nThen we select the last 3 characters and convert them so that the final string contains all 'O's." + }, + { + "example_num": 3, + "expected_input": "s = "OOOO"", + "expected_output": "0", + "explanation": "There are no 'X's in s to convert." + } + ] + }, + { + "_id": "66f925defdfb8e1665720ebc", + "questionid": 1009, + "title": "Find Missing Observations", + "slug": "find-missing-observations", + "description": "You have observations of n + m 6-sided dice rolls with each face numbered from 1 to 6. n of the observations went missing, and you only have the observations of m rolls. Fortunately, you have also calculated the average value of the n + m rolls. You are given an integer array rolls of length m where rolls[i] is the value of the ith observation. You are also given the two integers mean and n. Return an array of length n containing the missing observations such that the average value of the n + m rolls is exactly mean. If there are multiple valid answers, return any of them. If no such array exists, return an empty array. The average value of a set of k numbers is the sum of the numbers divided by k. Note that mean is an integer, so the sum of the n + m rolls should be divisible by n + m. ", + "category": [ + "Array", + "Math", + "Simulation" + ], + "complexity": "Medium", + "successrate": 41.9, + "totalsubmissions": 30688, + "totalaccepted": 12857, + "likes": 211, + "dislikes": 10, + "hints": "What should the sum of the n rolls be? Could you generate an array of size n such that each element is between 1 and 6?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "rolls = [3,2,4,3], mean = 4, n = 2", + "expected_output": "[6,6]", + "explanation": "The mean of all n + m rolls is (3 + 2 + 4 + 3 + 6 + 6) / 6 = 4." + }, + { + "example_num": 2, + "expected_input": "rolls = [1,5,6], mean = 3, n = 4", + "expected_output": "[2,3,2,2]", + "explanation": "The mean of all n + m rolls is (1 + 5 + 6 + 2 + 3 + 2 + 2) / 7 = 3." + }, + { + "example_num": 3, + "expected_input": "rolls = [1,2,3,4], mean = 6, n = 4", + "expected_output": "[]", + "explanation": "It is impossible for the mean to be 6 no matter what the 4 missing rolls are." + } + ] + }, + { + "_id": "66f925defdfb8e1665720eca", + "questionid": 1023, + "title": "Smallest Index With Equal Value", + "slug": "smallest-index-with-equal-value", + "description": "Given a 0-indexed integer array nums, return the smallest index i of nums such that i mod 10 == nums[i], or -1 if such index does not exist. x mod y denotes the remainder when x is divided by y. ", + "category": [ + "Array" + ], + "complexity": "Easy", + "successrate": 73.2, + "totalsubmissions": 32095, + "totalaccepted": 23484, + "likes": 144, + "dislikes": 67, + "hints": "Starting with i=0, check the condition for each index. The first one you find to be true is the smallest index.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [0,1,2]", + "expected_output": "0", + "explanation": "i=0: 0 mod 10 = 0 == nums[0].\ni=1: 1 mod 10 = 1 == nums[1].\ni=2: 2 mod 10 = 2 == nums[2].\nAll indices have i mod 10 == nums[i], so we return the smallest index 0." + }, + { + "example_num": 2, + "expected_input": "nums = [4,3,2,1]", + "expected_output": "2", + "explanation": "i=0: 0 mod 10 = 0 != nums[0].\ni=1: 1 mod 10 = 1 != nums[1].\ni=2: 2 mod 10 = 2 == nums[2].\ni=3: 3 mod 10 = 3 != nums[3].\n2 is the only index which has i mod 10 == nums[i]." + }, + { + "example_num": 3, + "expected_input": "nums = [1,2,3,4,5,6,7,8,9,0]", + "expected_output": "-1", + "explanation": "No index satisfies i mod 10 == nums[i]." + } + ] + }, + { + "_id": "66f925defdfb8e1665720ed4", + "questionid": 1033, + "title": "Detonate the Maximum Bombs", + "slug": "detonate-the-maximum-bombs", + "description": "You are given a list of bombs. The range of a bomb is defined as the area where its effect can be felt. This area is in the shape of a circle with the center as the location of the bomb. The bombs are represented by a 0-indexed 2D integer array bombs where bombs[i] = [xi, yi, ri]. xi and yi denote the X-coordinate and Y-coordinate of the location of the ith bomb, whereas ri denotes the radius of its range. You may choose to detonate a single bomb. When a bomb is detonated, it will detonate all bombs that lie in its range. These bombs will further detonate the bombs that lie in their ranges. Given the list of bombs, return the maximum number of bombs that can be detonated if you are allowed to detonate only one bomb. ", + "category": [ + "Array", + "Math", + "Depth-First Search", + "Breadth-First Search", + "Graph", + "Geometry" + ], + "complexity": "Medium", + "successrate": 39.9, + "totalsubmissions": 25051, + "totalaccepted": 9999, + "likes": 374, + "dislikes": 42, + "hints": "How can we model the relationship between different bombs? Can \"graphs\" help us? Bombs are nodes and are connected to other bombs in their range by directed edges. If we know which bombs will be affected when any bomb is detonated, how can we find the total number of bombs that will be detonated if we start from a fixed bomb? Run a Depth First Search (DFS) from every node, and all the nodes it reaches are the bombs that will be detonated.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "bombs = [[2,1,3],[6,1,4]]", + "expected_output": "2", + "explanation": "The above figure shows the positions and ranges of the 2 bombs.\nIf we detonate the left bomb, the right bomb will not be affected.\nBut if we detonate the right bomb, both bombs will be detonated.\nSo the maximum bombs that can be detonated is max(1, 2) = 2." + }, + { + "example_num": 2, + "expected_input": "bombs = [[1,1,5],[10,10,5]]", + "expected_output": "1\nExplanation:\nDetonating either bomb will not detonate the other bomb, so the maximum number of bombs that can be detonated is 1.", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "bombs = [[1,2,3],[2,3,1],[3,4,2],[4,5,3],[5,6,4]]", + "expected_output": "5", + "explanation": "The best bomb to detonate is bomb 0 because:\n- Bomb 0 detonates bombs 1 and 2. The red circle denotes the range of bomb 0.\n- Bomb 2 detonates bomb 3. The blue circle denotes the range of bomb 2.\n- Bomb 3 detonates bomb 4. The green circle denotes the range of bomb 3.\nThus all 5 bombs are detonated." + } + ] + }, + { + "_id": "66f925defdfb8e1665720eda", + "questionid": 1039, + "title": "Maximum Number of Words Found in Sentences", + "slug": "maximum-number-of-words-found-in-sentences", + "description": "A sentence is a list of words that are separated by a single space with no leading or trailing spaces. You are given an array of strings sentences, where each sentences[i] represents a single sentence. Return the maximum number of words that appear in a single sentence. ", + "category": [ + "Array", + "String" + ], + "complexity": "Easy", + "successrate": 89, + "totalsubmissions": 68223, + "totalaccepted": 60728, + "likes": 485, + "dislikes": 17, + "hints": "Process each sentence separately and count the number of words by looking for the number of space characters in the sentence and adding it by 1.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "sentences = ["alice and bob love leetcode", "i think so too", "this is great thanks very much"]", + "expected_output": "6", + "explanation": "- The first sentence, "alice and bob love leetcode", has 5 words in total.\n- The second sentence, "i think so too", has 4 words in total.\n- The third sentence, "this is great thanks very much", has 6 words in total.\nThus, the maximum number of words in a single sentence comes from the third sentence, which has 6 words." + }, + { + "example_num": 2, + "expected_input": "sentences = ["please wait", "continue to fight", "continue to win"]", + "expected_output": "3", + "explanation": "It is possible that multiple sentences contain the same number of words. \nIn this example, the second and third sentences (underlined) have the same number of words." + } + ] + }, + { + "_id": "66f925defdfb8e1665720ee0", + "questionid": 1045, + "title": "Number of Smooth Descent Periods of a Stock", + "slug": "number-of-smooth-descent-periods-of-a-stock", + "description": "You are given an integer array prices representing the daily price history of a stock, where prices[i] is the stock price on the ith day. A smooth descent period of a stock consists of one or more contiguous days such that the price on each day is lower than the price on the preceding day by exactly 1. The first day of the period is exempted from this rule. Return the number of smooth descent periods. ", + "category": [ + "Array", + "Math", + "Dynamic Programming" + ], + "complexity": "Medium", + "successrate": 55.3, + "totalsubmissions": 32528, + "totalaccepted": 17988, + "likes": 326, + "dislikes": 12, + "hints": "Any array is a series of adjacent longest possible smooth descent periods. For example, [5,3,2,1,7,6] is [5] + [3,2,1] + [7,6]. Think of a 2-pointer approach to traverse the array and find each longest possible period. Suppose you found the longest possible period with a length of k. How many periods are within that period? How can you count them quickly? Think of the formula to calculate the sum of 1, 2, 3, ..., k.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "prices = [3,2,1,4]", + "expected_output": "7", + "explanation": "There are 7 smooth descent periods:\n[3], [2], [1], [4], [3,2], [2,1], and [3,2,1]\nNote that a period with one day is a smooth descent period by the definition." + }, + { + "example_num": 2, + "expected_input": "prices = [8,6,7,7]", + "expected_output": "4", + "explanation": "There are 4 smooth descent periods: [8], [6], [7], and [7]\nNote that [8,6] is not a smooth descent period as 8 - 6 ≠ 1." + }, + { + "example_num": 3, + "expected_input": "prices = [1]", + "expected_output": "1", + "explanation": "There is 1 smooth descent period: [1]" + } + ] + }, + { + "_id": "66f925defdfb8e1665720ee5", + "questionid": 1050, + "title": "Check if All A's Appears Before All B's", + "slug": "check-if-all-as-appears-before-all-bs", + "description": "Given a string s consisting of only the characters 'a' and 'b', return true if every 'a' appears before every 'b' in the string. Otherwise, return false. ", + "category": [ + "String" + ], + "complexity": "Easy", + "successrate": 72.5, + "totalsubmissions": 38380, + "totalaccepted": 27813, + "likes": 283, + "dislikes": 3, + "hints": "You can check the opposite: check if there is a €˜b€™ before an €˜a€™. Then, negate and return that answer. s should not have any occurrences of €œba€ as a substring.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "aaabbb"", + "expected_output": "true", + "explanation": "The 'a's are at indices 0, 1, and 2, while the 'b's are at indices 3, 4, and 5.\nHence, every 'a' appears before every 'b' and we return true." + }, + { + "example_num": 2, + "expected_input": "s = "abab"", + "expected_output": "false", + "explanation": "There is an 'a' at index 2 and a 'b' at index 1.\nHence, not every 'a' appears before every 'b' and we return false." + }, + { + "example_num": 3, + "expected_input": "s = "bbb"", + "expected_output": "true", + "explanation": "There are no 'a's, hence, every 'a' appears before every 'b' and we return true." + } + ] + }, + { + "_id": "66f925defdfb8e1665720eed", + "questionid": 1058, + "title": "Solving Questions With Brainpower", + "slug": "solving-questions-with-brainpower", + "description": "You are given a 0-indexed 2D integer array questions where questions[i] = [pointsi, brainpoweri]. The array describes the questions of an exam, where you have to process the questions in order (i.e., starting from question 0) and make a decision whether to solve or skip each question. Solving question i will earn you pointsi points but you will be unable to solve each of the next brainpoweri questions. If you skip question i, you get to make the decision on the next question. Return the maximum points you can earn for the exam. ", + "category": [ + "Array", + "Dynamic Programming" + ], + "complexity": "Medium", + "successrate": 44.3, + "totalsubmissions": 40097, + "totalaccepted": 17782, + "likes": 532, + "dislikes": 7, + "hints": "For each question, we can either solve it or skip it. How can we use Dynamic Programming to decide the most optimal option for each problem? We store for each question the maximum points we can earn if we started the exam on that question. If we skip a question, then the answer for it will be the same as the answer for the next question. If we solve a question, then the answer for it will be the points of the current question plus the answer for the next solvable question. The maximum of these two values will be the answer to the current question.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "questions = [[3,2],[4,3],[4,4],[2,5]]", + "expected_output": "5", + "explanation": "The maximum points can be earned by solving questions 0 and 3.\n- Solve question 0: Earn 3 points, will be unable to solve the next 2 questions\n- Unable to solve questions 1 and 2\n- Solve question 3: Earn 2 points\nTotal points earned: 3 + 2 = 5. There is no other way to earn 5 or more points." + }, + { + "example_num": 2, + "expected_input": "questions = [[1,1],[2,2],[3,3],[4,4],[5,5]]", + "expected_output": "7", + "explanation": "The maximum points can be earned by solving questions 1 and 4.\n- Skip question 0\n- Solve question 1: Earn 2 points, will be unable to solve the next 2 questions\n- Unable to solve questions 2 and 3\n- Solve question 4: Earn 5 points\nTotal points earned: 2 + 5 = 7. There is no other way to earn 7 or more points." + } + ] + }, + { + "_id": "66f925defdfb8e1665720eee", + "questionid": 1059, + "title": "Maximum Running Time of N Computers", + "slug": "maximum-running-time-of-n-computers", + "description": "You have n computers. You are given the integer n and a 0-indexed integer array batteries where the ith battery can run a computer for batteries[i] minutes. You are interested in running all n computers simultaneously using the given batteries. Initially, you can insert at most one battery into each computer. After that and at any integer time moment, you can remove a battery from a computer and insert another battery any number of times. The inserted battery can be a totally new battery or a battery from another computer. You may assume that the removing and inserting processes take no time. Note that the batteries cannot be recharged. Return the maximum number of minutes you can run all the n computers simultaneously. ", + "category": [ + "Array", + "Binary Search", + "Greedy", + "Sorting" + ], + "complexity": "Hard", + "successrate": 37.5, + "totalsubmissions": 20733, + "totalaccepted": 7779, + "likes": 437, + "dislikes": 10, + "hints": "For a given running time, can you determine if it is possible to run all n computers simultaneously? Try to use Binary Search to find the maximal running time", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 2, batteries = [3,3,3]", + "expected_output": "4", + "explanation": "Initially, insert battery 0 into the first computer and battery 1 into the second computer.\nAfter two minutes, remove battery 1 from the second computer and insert battery 2 instead. Note that battery 1 can still run for one minute.\nAt the end of the third minute, battery 0 is drained, and you need to remove it from the first computer and insert battery 1 instead.\nBy the end of the fourth minute, battery 1 is also drained, and the first computer is no longer running.\nWe can run the two computers simultaneously for at most 4 minutes, so we return 4." + }, + { + "example_num": 2, + "expected_input": "n = 2, batteries = [1,1,1,1]", + "expected_output": "2", + "explanation": "Initially, insert battery 0 into the first computer and battery 2 into the second computer. \nAfter one minute, battery 0 and battery 2 are drained so you need to remove them and insert battery 1 into the first computer and battery 3 into the second computer. \nAfter another minute, battery 1 and battery 3 are also drained so the first and second computers are no longer running.\nWe can run the two computers simultaneously for at most 2 minutes, so we return 2." + } + ] + }, + { + "_id": "66f925defdfb8e1665720eef", + "questionid": 1060, + "title": "Minimum Sum of Four Digit Number After Splitting Digits", + "slug": "minimum-sum-of-four-digit-number-after-splitting-digits", + "description": "You are given a positive integer num consisting of exactly four digits. Split num into two new integers new1 and new2 by using the digits found in num. Leading zeros are allowed in new1 and new2, and all the digits found in num must be used. Return the minimum possible sum of new1 and new2. ", + "category": [ + "Math", + "Greedy", + "Sorting" + ], + "complexity": "Easy", + "successrate": 88, + "totalsubmissions": 30322, + "totalaccepted": 26673, + "likes": 295, + "dislikes": 36, + "hints": "Notice that the most optimal way to obtain the minimum possible sum using 4 digits is by summing up two 2-digit numbers. We can use the two smallest digits out of the four as the digits found in the tens place respectively. Similarly, we use the final 2 larger digits as the digits found in the ones place.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "num = 2932", + "expected_output": "52", + "explanation": "Some possible pairs [new1, new2] are [29, 23], [223, 9], etc.\nThe minimum sum can be obtained by the pair [29, 23]: 29 + 23 = 52." + }, + { + "example_num": 2, + "expected_input": "num = 4009", + "expected_output": "13", + "explanation": "Some possible pairs [new1, new2] are [0, 49], [490, 0], etc. \nThe minimum sum can be obtained by the pair [4, 9]: 4 + 9 = 13." + } + ] + }, + { + "_id": "66f925defdfb8e1665720ef1", + "questionid": 1062, + "title": "Find All Lonely Numbers in the Array", + "slug": "find-all-lonely-numbers-in-the-array", + "description": "You are given an integer array nums. A number x is lonely when it appears only once, and no adjacent numbers (i.e. x + 1 and x - 1) appear in the array. Return all lonely numbers in nums. You may return the answer in any order. ", + "category": [ + "Array", + "Hash Table", + "Counting" + ], + "complexity": "Medium", + "successrate": 60.6, + "totalsubmissions": 37637, + "totalaccepted": 22804, + "likes": 212, + "dislikes": 31, + "hints": "For a given element x, how can you quickly check if x - 1 and x + 1 are present in the array without reiterating through the entire array? Use a set or a hash map.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [10,6,5,8]", + "expected_output": "[10,8]", + "explanation": "- 10 is a lonely number since it appears exactly once and 9 and 11 does not appear in nums.\n- 8 is a lonely number since it appears exactly once and 7 and 9 does not appear in nums.\n- 5 is not a lonely number since 6 appears in nums and vice versa.\nHence, the lonely numbers in nums are [10, 8].\nNote that [8, 10] may also be returned." + }, + { + "example_num": 2, + "expected_input": "nums = [1,3,5,3]", + "expected_output": "[1,5]", + "explanation": "- 1 is a lonely number since it appears exactly once and 0 and 2 does not appear in nums.\n- 5 is a lonely number since it appears exactly once and 4 and 6 does not appear in nums.\n- 3 is not a lonely number since it appears twice.\nHence, the lonely numbers in nums are [1, 5].\nNote that [5, 1] may also be returned." + } + ] + }, + { + "_id": "66f925defdfb8e1665720ef2", + "questionid": 1063, + "title": "Find Three Consecutive Integers That Sum to a Given Number", + "slug": "find-three-consecutive-integers-that-sum-to-a-given-number", + "description": "Given an integer num, return three consecutive integers (as a sorted array) that sum to num. If num cannot be expressed as the sum of three consecutive integers, return an empty array. ", + "category": [ + "Math", + "Simulation" + ], + "complexity": "Medium", + "successrate": 60.4, + "totalsubmissions": 30561, + "totalaccepted": 18456, + "likes": 234, + "dislikes": 60, + "hints": "Notice that if a solution exists, we can represent them as x-1, x, x+1. What does this tell us about the number? Notice the sum of the numbers will be 3x. Can you solve for x?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "num = 33", + "expected_output": "[10,11,12]", + "explanation": "33 can be expressed as 10 + 11 + 12 = 33.\n10, 11, 12 are 3 consecutive integers, so we return [10, 11, 12]." + }, + { + "example_num": 2, + "expected_input": "num = 4", + "expected_output": "[]", + "explanation": "There is no way to express 4 as the sum of 3 consecutive integers." + } + ] + }, + { + "_id": "66f925defdfb8e1665720ef3", + "questionid": 1064, + "title": "Maximum Split of Positive Even Integers", + "slug": "maximum-split-of-positive-even-integers", + "description": "You are given an integer finalSum. Split it into a sum of a maximum number of unique positive even integers. Return a list of integers that represent a valid split containing a maximum number of integers. If no valid split exists for finalSum, return an empty list. You may return the integers in any order. ", + "category": [ + "Math", + "Greedy" + ], + "complexity": "Medium", + "successrate": 54.6, + "totalsubmissions": 26382, + "totalaccepted": 14415, + "likes": 331, + "dislikes": 38, + "hints": "First, check if finalSum is divisible by 2. If it isn€™t, then we cannot split it into even integers. Let k be the number of elements in our split. As we want the maximum number of elements, we should try to use the first k - 1 even elements to grow our sum as slowly as possible. Thus, we find the maximum sum of the first k - 1 even elements which is less than finalSum. We then add the difference over to the kth element.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "finalSum = 12", + "expected_output": "[2,4,6]", + "explanation": "The following are valid splits: (12), (2 + 10), (2 + 4 + 6), and (4 + 8).\n(2 + 4 + 6) has the maximum number of integers, which is 3. Thus, we return [2,4,6].\nNote that [2,6,4], [6,2,4], etc. are also accepted." + }, + { + "example_num": 2, + "expected_input": "finalSum = 7", + "expected_output": "[]", + "explanation": "There are no valid splits for the given finalSum.\nThus, we return an empty array." + }, + { + "example_num": 3, + "expected_input": "finalSum = 28", + "expected_output": "[6,8,2,12]", + "explanation": "The following are valid splits: (2 + 26), (6 + 8 + 2 + 12), and (4 + 24). \n(6 + 8 + 2 + 12) has the maximum number of integers, which is 4. Thus, we return [6,8,2,12].\nNote that [10,2,4,12], [6,2,4,16], etc. are also accepted." + } + ] + }, + { + "_id": "66f925defdfb8e1665720ef4", + "questionid": 1065, + "title": "Count Good Triplets in an Array", + "slug": "count-good-triplets-in-an-array", + "description": "You are given two 0-indexed arrays nums1 and nums2 of length n, both of which are permutations of [0, 1, ..., n - 1]. A good triplet is a set of 3 distinct values which are present in increasing order by position both in nums1 and nums2. In other words, if we consider pos1v as the index of the value v in nums1 and pos2v as the index of the value v in nums2, then a good triplet will be a set (x, y, z) where 0 <= x, y, z <= n - 1, such that pos1x < pos1y < pos1z and pos2x < pos2y < pos2z. Return the total number of good triplets. ", + "category": [ + "Array", + "Binary Search", + "Divide and Conquer", + "Binary Indexed Tree", + "Segment Tree", + "Merge Sort", + "Ordered Set" + ], + "complexity": "Hard", + "successrate": 34, + "totalsubmissions": 10057, + "totalaccepted": 3422, + "likes": 257, + "dislikes": 10, + "hints": "For every value y, how can you find the number of values x (0 ‰¤ x, y ‰¤ n - 1) such that x appears before y in both of the arrays? Similarly, for every value y, try finding the number of values z (0 ‰¤ y, z ‰¤ n - 1) such that z appears after y in both of the arrays. Now, for every value y, count the number of good triplets that can be formed if y is considered as the middle element.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums1 = [2,0,1,3], nums2 = [0,1,2,3]", + "expected_output": "1", + "explanation": "There are 4 triplets (x,y,z) such that pos1x < pos1y < pos1z. They are (2,0,1), (2,0,3), (2,1,3), and (0,1,3). \nOut of those triplets, only the triplet (0,1,3) satisfies pos2x < pos2y < pos2z. Hence, there is only 1 good triplet." + }, + { + "example_num": 2, + "expected_input": "nums1 = [4,0,1,3,2], nums2 = [4,1,0,2,3]", + "expected_output": "4", + "explanation": "The 4 good triplets are (4,0,3), (4,0,2), (4,1,3), and (4,1,2)." + } + ] + }, + { + "_id": "66f925defdfb8e1665720ef8", + "questionid": 1069, + "title": "Maximum AND Sum of Array", + "slug": "maximum-and-sum-of-array", + "description": "You are given an integer array nums of length n and an integer numSlots such that 2 * numSlots >= n. There are numSlots slots numbered from 1 to numSlots. You have to place all n integers into the slots such that each slot contains at most two numbers. The AND sum of a given placement is the sum of the bitwise AND of every number with its respective slot number. Return the maximum possible AND sum of nums given numSlots slots. ", + "category": [ + "Array", + "Dynamic Programming", + "Bit Manipulation", + "Bitmask" + ], + "complexity": "Hard", + "successrate": 43.1, + "totalsubmissions": 12204, + "totalaccepted": 5263, + "likes": 220, + "dislikes": 11, + "hints": "Can you think of a dynamic programming solution to this problem? Can you use a bitmask to represent the state of the slots?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,2,3,4,5,6], numSlots = 3", + "expected_output": "9", + "explanation": "One possible placement is [1, 4] into slot 1, [2, 6] into slot 2, and [3, 5] into slot 3. \nThis gives the maximum AND sum of (1 AND 1) + (4 AND 1) + (2 AND 2) + (6 AND 2) + (3 AND 3) + (5 AND 3) = 1 + 0 + 2 + 2 + 3 + 1 = 9." + }, + { + "example_num": 2, + "expected_input": "nums = [1,3,10,4,7,1], numSlots = 9", + "expected_output": "24", + "explanation": "One possible placement is [1, 1] into slot 1, [3] into slot 3, [4] into slot 4, [7] into slot 7, and [10] into slot 9.\nThis gives the maximum AND sum of (1 AND 1) + (1 AND 1) + (3 AND 3) + (4 AND 4) + (7 AND 7) + (10 AND 9) = 1 + 1 + 3 + 4 + 7 + 8 = 24.\nNote that slots 2, 5, 6, and 8 are empty which is permitted." + } + ] + }, + { + "_id": "66f925defdfb8e1665720f01", + "questionid": 1078, + "title": "Create Binary Tree From Descriptions", + "slug": "create-binary-tree-from-descriptions", + "description": "You are given a 2D integer array descriptions where descriptions[i] = [parenti, childi, isLefti] indicates that parenti is the parent of childi in a binary tree of unique values. Furthermore, Construct the binary tree described by descriptions and return its root. The test cases will be generated such that the binary tree is valid. ", + "category": [ + "Array", + "Hash Table", + "Tree", + "Depth-First Search", + "Breadth-First Search", + "Binary Tree" + ], + "complexity": "Medium", + "successrate": 70.3, + "totalsubmissions": 19891, + "totalaccepted": 13986, + "likes": 334, + "dislikes": 7, + "hints": "Could you represent and store the descriptions more efficiently? Could you find the root node? The node that is not a child in any of the descriptions is the root node.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "descriptions = [[20,15,1],[20,17,0],[50,20,1],[50,80,0],[80,19,1]]", + "expected_output": "[50,20,80,15,17,19]", + "explanation": "The root node is the node with value 50 since it has no parent.\nThe resulting binary tree is shown in the diagram." + }, + { + "example_num": 2, + "expected_input": "descriptions = [[1,2,1],[2,3,0],[3,4,1]]", + "expected_output": "[1,2,null,null,3,4]", + "explanation": "The root node is the node with value 1 since it has no parent.\nThe resulting binary tree is shown in the diagram." + } + ] + }, + { + "_id": "66f925defdfb8e1665720f07", + "questionid": 1084, + "title": "Minimum Weighted Subgraph With the Required Paths", + "slug": "minimum-weighted-subgraph-with-the-required-paths", + "description": "You are given an integer n denoting the number of nodes of a weighted directed graph. The nodes are numbered from 0 to n - 1. You are also given a 2D integer array edges where edges[i] = [fromi, toi, weighti] denotes that there exists a directed edge from fromi to toi with weight weighti. Lastly, you are given three distinct integers src1, src2, and dest denoting three distinct nodes of the graph. Return the minimum weight of a subgraph of the graph such that it is possible to reach dest from both src1 and src2 via a set of edges of this subgraph. In case such a subgraph does not exist, return -1. A subgraph is a graph whose vertices and edges are subsets of the original graph. The weight of a subgraph is the sum of weights of its constituent edges. ", + "category": [ + "Graph", + "Shortest Path" + ], + "complexity": "Hard", + "successrate": 35.1, + "totalsubmissions": 16637, + "totalaccepted": 5834, + "likes": 369, + "dislikes": 11, + "hints": "Consider what the paths from src1 to dest and src2 to dest would look like in the optimal solution. It can be shown that in an optimal solution, the two paths from src1 and src2 will coincide at one node, and the remaining part to dest will be the same for both paths. Now consider how to find the node where the paths will coincide. How can algorithms for finding the shortest path between two nodes help us?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 6, edges = [[0,2,2],[0,5,6],[1,0,3],[1,4,5],[2,1,1],[2,3,3],[2,3,4],[3,4,2],[4,5,1]], src1 = 0, src2 = 1, dest = 5", + "expected_output": "9", + "explanation": "The above figure represents the input graph.\nThe blue edges represent one of the subgraphs that yield the optimal answer.\nNote that the subgraph [[1,0,3],[0,5,6]] also yields the optimal answer. It is not possible to get a subgraph with less weight satisfying all the constraints." + }, + { + "example_num": 2, + "expected_input": "n = 3, edges = [[0,1,1],[2,1,1]], src1 = 0, src2 = 1, dest = 2", + "expected_output": "-1", + "explanation": "The above figure represents the input graph.\nIt can be seen that there does not exist any path from node 1 to node 2, hence there are no subgraphs satisfying all the constraints." + } + ] + }, + { + "_id": "66f925defdfb8e1665720f0b", + "questionid": 1088, + "title": "Minimize Result by Adding Parentheses to Expression", + "slug": "minimize-result-by-adding-parentheses-to-expression", + "description": "You are given a 0-indexed string expression of the form \"+\" where and represent positive integers. Add a pair of parentheses to expression such that after the addition of parentheses, expression is a valid mathematical expression and evaluates to the smallest possible value. The left parenthesis must be added to the left of '+' and the right parenthesis must be added to the right of '+'. Return expression after adding a pair of parentheses such that expression evaluates to the smallest possible value. If there are multiple answers that yield the same result, return any of them. The input has been generated such that the original value of expression, and the value of expression after adding any pair of parentheses that meets the requirements fits within a signed 32-bit integer. ", + "category": [ + "String", + "Enumeration" + ], + "complexity": "Medium", + "successrate": 63.6, + "totalsubmissions": 14828, + "totalaccepted": 9438, + "likes": 102, + "dislikes": 210, + "hints": "The maximum length of expression is very low. We can try every possible spot to place the parentheses. Every possibility of expression is of the form a * (b + c) * d where a, b, c, d represent integers. Note the edge cases where a and/or d do not exist, in which case use 1 instead of them.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "expression = "247+38"", + "expected_output": ""2(47+38)"", + "explanation": "The expression evaluates to 2 * (47 + 38) = 2 * 85 = 170.\nNote that "2(4)7+38" is invalid because the right parenthesis must be to the right of the '+'.\nIt can be shown that 170 is the smallest possible value." + }, + { + "example_num": 2, + "expected_input": "expression = "12+34"", + "expected_output": ""1(2+3)4"", + "explanation": "The expression evaluates to 1 * (2 + 3) * 4 = 1 * 5 * 4 = 20." + }, + { + "example_num": 3, + "expected_input": "expression = "999+999"", + "expected_output": ""(999+999)"", + "explanation": "The expression evaluates to 999 + 999 = 1998." + } + ] + }, + { + "_id": "66f925defdfb8e1665720eb4", + "questionid": 1001, + "title": "Smallest Missing Genetic Value in Each Subtree", + "slug": "smallest-missing-genetic-value-in-each-subtree", + "description": "There is a family tree rooted at 0 consisting of n nodes numbered 0 to n - 1. You are given a 0-indexed integer array parents, where parents[i] is the parent for node i. Since node 0 is the root, parents[0] == -1. There are 105 genetic values, each represented by an integer in the inclusive range [1, 105]. You are given a 0-indexed integer array nums, where nums[i] is a distinct genetic value for node i. Return an array ans of length n where ans[i] is the smallest genetic value that is missing from the subtree rooted at node i. The subtree rooted at a node x contains node x and all of its descendant nodes. ", + "category": [ + "Dynamic Programming", + "Tree", + "Depth-First Search", + "Union Find" + ], + "complexity": "Hard", + "successrate": 42.3, + "totalsubmissions": 11335, + "totalaccepted": 4799, + "likes": 266, + "dislikes": 16, + "hints": "If the subtree doesn't contain 1, then the missing value will always be 1. What data structure allows us to dynamically update the values that are currently not present?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "parents = [-1,0,0,2], nums = [1,2,3,4]", + "expected_output": "[5,1,1,1]", + "explanation": "The answer for each subtree is calculated as follows:\n- 0: The subtree contains nodes [0,1,2,3] with values [1,2,3,4]. 5 is the smallest missing value.\n- 1: The subtree contains only node 1 with value 2. 1 is the smallest missing value.\n- 2: The subtree contains nodes [2,3] with values [3,4]. 1 is the smallest missing value.\n- 3: The subtree contains only node 3 with value 4. 1 is the smallest missing value." + }, + { + "example_num": 2, + "expected_input": "parents = [-1,0,1,0,3,3], nums = [5,4,6,2,1,3]", + "expected_output": "[7,1,1,4,2,1]", + "explanation": "The answer for each subtree is calculated as follows:\n- 0: The subtree contains nodes [0,1,2,3,4,5] with values [5,4,6,2,1,3]. 7 is the smallest missing value.\n- 1: The subtree contains nodes [1,2] with values [4,6]. 1 is the smallest missing value.\n- 2: The subtree contains only node 2 with value 6. 1 is the smallest missing value.\n- 3: The subtree contains nodes [3,4,5] with values [2,1,3]. 4 is the smallest missing value.\n- 4: The subtree contains only node 4 with value 1. 2 is the smallest missing value.\n- 5: The subtree contains only node 5 with value 3. 1 is the smallest missing value." + }, + { + "example_num": 3, + "expected_input": "parents = [-1,2,3,0,2,4,1], nums = [2,3,4,5,6,7,8]", + "expected_output": "[1,1,1,1,1,1,1]", + "explanation": "The value 1 is missing from all the subtrees." + } + ] + }, + { + "_id": "66f925defdfb8e1665720eb5", + "questionid": 1002, + "title": "Convert 1D Array Into 2D Array", + "slug": "convert-1d-array-into-2d-array", + "description": "You are given a 0-indexed 1-dimensional (1D) integer array original, and two integers, m and n. You are tasked with creating a 2-dimensional (2D) array with m rows and n columns using all the elements from original. The elements from indices 0 to n - 1 (inclusive) of original should form the first row of the constructed 2D array, the elements from indices n to 2 * n - 1 (inclusive) should form the second row of the constructed 2D array, and so on. Return an m x n 2D array constructed according to the above procedure, or an empty 2D array if it is impossible. ", + "category": [ + "Array", + "Matrix", + "Simulation" + ], + "complexity": "Easy", + "successrate": 59.2, + "totalsubmissions": 49401, + "totalaccepted": 29235, + "likes": 292, + "dislikes": 20, + "hints": "When is it possible to convert original into a 2D array and when is it impossible? It is possible if and only if m * n == original.length If it is possible to convert original to a 2D array, keep an index i such that original[i] is the next element to add to the 2D array.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "original = [1,2,3,4], m = 2, n = 2", + "expected_output": "[[1,2],[3,4]]", + "explanation": "The constructed 2D array should contain 2 rows and 2 columns.\nThe first group of n=2 elements in original, [1,2], becomes the first row in the constructed 2D array.\nThe second group of n=2 elements in original, [3,4], becomes the second row in the constructed 2D array." + }, + { + "example_num": 2, + "expected_input": "original = [1,2,3], m = 1, n = 3", + "expected_output": "[[1,2,3]]", + "explanation": "The constructed 2D array should contain 1 row and 3 columns.\nPut all three elements in original into the first row of the constructed 2D array." + }, + { + "example_num": 3, + "expected_input": "original = [1,2], m = 1, n = 1", + "expected_output": "[]", + "explanation": "There are 2 elements in original.\nIt is impossible to fit 2 elements in a 1x1 2D array, so return an empty 2D array." + } + ] + }, + { + "_id": "66f925defdfb8e1665720eb9", + "questionid": 1006, + "title": "Grid Game", + "slug": "grid-game", + "description": "You are given a 0-indexed 2D array grid of size 2 x n, where grid[r][c] represents the number of points at position (r, c) on the matrix. Two robots are playing a game on this matrix. Both robots initially start at (0, 0) and want to reach (1, n-1). Each robot may only move to the right ((r, c) to (r, c + 1)) or down ((r, c) to (r + 1, c)). At the start of the game, the first robot moves from (0, 0) to (1, n-1), collecting all the points from the cells on its path. For all cells (r, c) traversed on the path, grid[r][c] is set to 0. Then, the second robot moves from (0, 0) to (1, n-1), collecting the points on its path. Note that their paths may intersect with one another. The first robot wants to minimize the number of points collected by the second robot. In contrast, the second robot wants to maximize the number of points it collects. If both robots play optimally, return the number of points collected by the second robot. ", + "category": [ + "Array", + "Matrix", + "Prefix Sum" + ], + "complexity": "Medium", + "successrate": 41.5, + "totalsubmissions": 24373, + "totalaccepted": 10126, + "likes": 430, + "dislikes": 12, + "hints": "There are n choices for when the first robot moves to the second row. Can we use prefix sums to help solve this problem?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "grid = [[2,5,4],[1,5,1]]", + "expected_output": "4", + "explanation": "The optimal path taken by the first robot is shown in red, and the optimal path taken by the second robot is shown in blue.\nThe cells visited by the first robot are set to 0.\nThe second robot will collect 0 + 0 + 4 + 0 = 4 points." + }, + { + "example_num": 2, + "expected_input": "grid = [[3,3,1],[8,5,2]]", + "expected_output": "4", + "explanation": "The optimal path taken by the first robot is shown in red, and the optimal path taken by the second robot is shown in blue.\nThe cells visited by the first robot are set to 0.\nThe second robot will collect 0 + 3 + 1 + 0 = 4 points." + }, + { + "example_num": 3, + "expected_input": "grid = [[1,3,1,15],[1,3,3,1]]", + "expected_output": "7\nExplanation: The optimal path taken by the first robot is shown in red, and the optimal path taken by the second robot is shown in blue.\nThe cells visited by the first robot are set to 0.\nThe second robot will collect 0 + 1 + 3 + 3 + 0 = 7 points.", + "explanation": "" + } + ] + }, + { + "_id": "66f925defdfb8e1665720eba", + "questionid": 1007, + "title": "Remove Colored Pieces if Both Neighbors are the Same Color", + "slug": "remove-colored-pieces-if-both-neighbors-are-the-same-color", + "description": "There are n pieces arranged in a line, and each piece is colored either by 'A' or by 'B'. You are given a string colors of length n where colors[i] is the color of the ith piece. Alice and Bob are playing a game where they take alternating turns removing pieces from the line. In this game, Alice moves first. Assuming Alice and Bob play optimally, return true if Alice wins, or return false if Bob wins. ", + "category": [ + "Math", + "String", + "Greedy", + "Game Theory" + ], + "complexity": "Medium", + "successrate": 56.1, + "totalsubmissions": 20174, + "totalaccepted": 11320, + "likes": 209, + "dislikes": 18, + "hints": "Does the number of moves a player can make depend on what the other player does? No How many moves can Alice make if colors == \"AAAAAA\" If a group of n consecutive pieces has the same color, the player can take n - 2 of those pieces if n is greater than or equal to 3", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "colors = "AAABABB"", + "expected_output": "true", + "explanation": "AAABABB -> AABABB\nAlice moves first.\nShe removes the second 'A' from the left since that is the only 'A' whose neighbors are both 'A'.\n\nNow it's Bob's turn.\nBob cannot make a move on his turn since there are no 'B's whose neighbors are both 'B'.\nThus, Alice wins, so return true." + }, + { + "example_num": 2, + "expected_input": "colors = "AA"", + "expected_output": "false", + "explanation": "Alice has her turn first.\nThere are only two 'A's and both are on the edge of the line, so she cannot move on her turn.\nThus, Bob wins, so return false." + }, + { + "example_num": 3, + "expected_input": "colors = "ABBBBBBBAAA"", + "expected_output": "false", + "explanation": "ABBBBBBBAAA -> ABBBBBBBAA\nAlice moves first.\nHer only option is to remove the second to last 'A' from the right.\n\nABBBBBBBAA -> ABBBBBBAA\nNext is Bob's turn.\nHe has many options for which 'B' piece to remove. He can pick any.\n\nOn Alice's second turn, she has no more pieces that she can remove.\nThus, Bob wins, so return false." + } + ] + }, + { + "_id": "66f925defdfb8e1665720ec0", + "questionid": 1013, + "title": "Partition Array Into Two Arrays to Minimize Sum Difference", + "slug": "partition-array-into-two-arrays-to-minimize-sum-difference", + "description": "You are given an integer array nums of 2 * n integers. You need to partition nums into two arrays of length n to minimize the absolute difference of the sums of the arrays. To partition nums, put each element of nums into one of the two arrays. Return the minimum possible absolute difference. ", + "category": [ + "Array", + "Two Pointers", + "Binary Search", + "Dynamic Programming", + "Bit Manipulation", + "Ordered Set", + "Bitmask" + ], + "complexity": "Hard", + "successrate": 21.7, + "totalsubmissions": 24142, + "totalaccepted": 5249, + "likes": 579, + "dislikes": 36, + "hints": "The target sum for the two partitions is sum(nums) / 2. Could you reduce the time complexity if you arbitrarily divide nums into two halves (two arrays)? Meet-in-the-Middle? For both halves, pre-calculate a 2D array where the kth index will store all possible sum values if only k elements from this half are added. For each sum of k elements in the first half, find the best sum of n-k elements in the second half such that the two sums add up to a value closest to the target sum from hint 1. These two subsets will form one array of the partition.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [3,9,7,3]", + "expected_output": "2", + "explanation": "One optimal partition is: [3,9] and [7,3].\nThe absolute difference between the sums of the arrays is abs((3 + 9) - (7 + 3)) = 2." + }, + { + "example_num": 2, + "expected_input": "nums = [-36,36]", + "expected_output": "72", + "explanation": "One optimal partition is: [-36] and [36].\nThe absolute difference between the sums of the arrays is abs((-36) - (36)) = 72." + }, + { + "example_num": 3, + "expected_input": "nums = [2,-1,0,4,-2,-9]", + "expected_output": "0", + "explanation": "One optimal partition is: [2,4,-9] and [-1,0,-2].\nThe absolute difference between the sums of the arrays is abs((2 + 4 + -9) - (-1 + 0 + -2)) = 0." + } + ] + }, + { + "_id": "66f925defdfb8e1665720ec3", + "questionid": 1016, + "title": "Check if Numbers Are Ascending in a Sentence", + "slug": "check-if-numbers-are-ascending-in-a-sentence", + "description": "A sentence is a list of tokens separated by a single space with no leading or trailing spaces. Every token is either a positive number consisting of digits 0-9 with no leading zeros, or a word consisting of lowercase English letters. Given a string s representing a sentence, you need to check if all the numbers in s are strictly increasing from left to right (i.e., other than the last number, each number is strictly smaller than the number on its right in s). Return true if so, or false otherwise. ", + "category": [ + "String" + ], + "complexity": "Easy", + "successrate": 67.8, + "totalsubmissions": 33814, + "totalaccepted": 22931, + "likes": 236, + "dislikes": 11, + "hints": "Use string tokenization of your language to extract all the tokens of the string easily. For each token extracted, how can you tell if it is a number? Does the first letter being a digit mean something? Compare the number with the previously occurring number to check if ascending order is maintained.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "1 box has 3 blue 4 red 6 green and 12 yellow marbles"", + "expected_output": "true", + "explanation": "The numbers in s are: 1, 3, 4, 6, 12.\nThey are strictly increasing from left to right: 1 < 3 < 4 < 6 < 12." + }, + { + "example_num": 2, + "expected_input": "s = "hello world 5 x 5"", + "expected_output": "false", + "explanation": "The numbers in s are: 5, 5. They are not strictly increasing." + }, + { + "example_num": 3, + "expected_input": "s = "sunset is at 7 51 pm overnight lows will be in the low 50 and 60 s"", + "expected_output": "false", + "explanation": "The numbers in s are: 7, 51, 50, 60. They are not strictly increasing." + } + ] + }, + { + "_id": "66f925defdfb8e1665720ec6", + "questionid": 1019, + "title": "Count Nodes With the Highest Score", + "slug": "count-nodes-with-the-highest-score", + "description": "There is a binary tree rooted at 0 consisting of n nodes. The nodes are labeled from 0 to n - 1. You are given a 0-indexed integer array parents representing the tree, where parents[i] is the parent of node i. Since node 0 is the root, parents[0] == -1. Each node has a score. To find the score of a node, consider if the node and the edges connected to it were removed. The tree would become one or more non-empty subtrees. The size of a subtree is the number of the nodes in it. The score of the node is the product of the sizes of all those subtrees. Return the number of nodes that have the highest score. ", + "category": [ + "Array", + "Tree", + "Depth-First Search", + "Binary Tree" + ], + "complexity": "Medium", + "successrate": 46.3, + "totalsubmissions": 20564, + "totalaccepted": 9513, + "likes": 389, + "dislikes": 24, + "hints": "For each node, you need to find the sizes of the subtrees rooted in each of its children. Maybe DFS? How to determine the number of nodes in the rest of the tree? Can you subtract the size of the subtree rooted at the node from the total number of nodes of the tree? Use these values to compute the score of the node. Track the maximum score, and how many nodes achieve such score.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "parents = [-1,2,0,2,0]", + "expected_output": "3", + "explanation": "- The score of node 0 is: 3 * 1 = 3\n- The score of node 1 is: 4 = 4\n- The score of node 2 is: 1 * 1 * 2 = 2\n- The score of node 3 is: 4 = 4\n- The score of node 4 is: 4 = 4\nThe highest score is 4, and three nodes (node 1, node 3, and node 4) have the highest score." + }, + { + "example_num": 2, + "expected_input": "parents = [-1,2,0]", + "expected_output": "2", + "explanation": "- The score of node 0 is: 2 = 2\n- The score of node 1 is: 2 = 2\n- The score of node 2 is: 1 * 1 = 1\nThe highest score is 2, and two nodes (node 0 and node 1) have the highest score." + } + ] + }, + { + "_id": "66f925defdfb8e1665720ec8", + "questionid": 1021, + "title": "Most Beautiful Item for Each Query", + "slug": "most-beautiful-item-for-each-query", + "description": "You are given a 2D integer array items where items[i] = [pricei, beautyi] denotes the price and beauty of an item respectively. You are also given a 0-indexed integer array queries. For each queries[j], you want to determine the maximum beauty of an item whose price is less than or equal to queries[j]. If no such item exists, then the answer to this query is 0. Return an array answer of the same length as queries where answer[j] is the answer to the jth query. ", + "category": [ + "Array", + "Binary Search", + "Sorting" + ], + "complexity": "Medium", + "successrate": 48.4, + "totalsubmissions": 16619, + "totalaccepted": 8040, + "likes": 290, + "dislikes": 8, + "hints": "Can we process the queries in a smart order to avoid repeatedly checking the same items? How can we use the answer to a query for other queries?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "items = [[1,2],[3,2],[2,4],[5,6],[3,5]], queries = [1,2,3,4,5,6]", + "expected_output": "[2,4,5,5,6,6]", + "explanation": "- For queries[0]=1, [1,2] is the only item which has price <= 1. Hence, the answer for this query is 2.\n- For queries[1]=2, the items which can be considered are [1,2] and [2,4]. \n The maximum beauty among them is 4.\n- For queries[2]=3 and queries[3]=4, the items which can be considered are [1,2], [3,2], [2,4], and [3,5].\n The maximum beauty among them is 5.\n- For queries[4]=5 and queries[5]=6, all items can be considered.\n Hence, the answer for them is the maximum beauty of all items, i.e., 6." + }, + { + "example_num": 2, + "expected_input": "items = [[1,2],[1,2],[1,3],[1,4]], queries = [1]", + "expected_output": "[4]", + "explanation": "The price of every item is equal to 1, so we choose the item with the maximum beauty 4. \nNote that multiple items can have the same price and/or beauty." + }, + { + "example_num": 3, + "expected_input": "items = [[10,1000]], queries = [5]", + "expected_output": "[0]", + "explanation": "No item has a price less than or equal to 5, so no item can be chosen.\nHence, the answer to the query is 0." + } + ] + }, + { + "_id": "66f925defdfb8e1665720ec9", + "questionid": 1022, + "title": "Maximum Number of Tasks You Can Assign", + "slug": "maximum-number-of-tasks-you-can-assign", + "description": "You have n tasks and m workers. Each task has a strength requirement stored in a 0-indexed integer array tasks, with the ith task requiring tasks[i] strength to complete. The strength of each worker is stored in a 0-indexed integer array workers, with the jth worker having workers[j] strength. Each worker can only be assigned to a single task and must have a strength greater than or equal to the task's strength requirement (i.e., workers[j] >= tasks[i]). Additionally, you have pills magical pills that will increase a worker's strength by strength. You can decide which workers receive the magical pills, however, you may only give each worker at most one magical pill. Given the 0-indexed integer arrays tasks and workers and the integers pills and strength, return the maximum number of tasks that can be completed. ", + "category": [ + "Array", + "Binary Search", + "Greedy", + "Queue", + "Sorting", + "Monotonic Queue" + ], + "complexity": "Hard", + "successrate": 36.9, + "totalsubmissions": 12449, + "totalaccepted": 4592, + "likes": 233, + "dislikes": 12, + "hints": "Is it possible to assign the first k smallest tasks to the workers? How can you efficiently try every k?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "tasks = [3,2,1], workers = [0,3,3], pills = 1, strength = 1", + "expected_output": "3", + "explanation": "We can assign the magical pill and tasks as follows:\n- Give the magical pill to worker 0.\n- Assign worker 0 to task 2 (0 + 1 >= 1)\n- Assign worker 1 to task 1 (3 >= 2)\n- Assign worker 2 to task 0 (3 >= 3)" + }, + { + "example_num": 2, + "expected_input": "tasks = [5,4], workers = [0,0,0], pills = 1, strength = 5", + "expected_output": "1", + "explanation": "We can assign the magical pill and tasks as follows:\n- Give the magical pill to worker 0.\n- Assign worker 0 to task 0 (0 + 5 >= 5)" + }, + { + "example_num": 3, + "expected_input": "tasks = [10,15,30], workers = [0,10,10,10,10], pills = 3, strength = 10", + "expected_output": "2", + "explanation": "We can assign the magical pills and tasks as follows:\n- Give the magical pill to worker 0 and worker 1.\n- Assign worker 0 to task 0 (0 + 10 >= 10)\n- Assign worker 1 to task 1 (10 + 10 >= 15)\nThe last pill is not given because it will not make any worker strong enough for the last task." + } + ] + }, + { + "_id": "66f925defdfb8e1665720ecc", + "questionid": 1025, + "title": "Count Vowel Substrings of a String", + "slug": "count-vowel-substrings-of-a-string", + "description": "A substring is a contiguous (non-empty) sequence of characters within a string. A vowel substring is a substring that only consists of vowels ('a', 'e', 'i', 'o', and 'u') and has all five vowels present in it. Given a string word, return the number of vowel substrings in word. ", + "category": [ + "Hash Table", + "String" + ], + "complexity": "Easy", + "successrate": 65.8, + "totalsubmissions": 24749, + "totalaccepted": 16283, + "likes": 362, + "dislikes": 109, + "hints": "While generating substrings starting at any index, do you need to continue generating larger substrings if you encounter a consonant? Can you store the count of characters to avoid generating substrings altogether?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "word = "aeiouu"", + "expected_output": "2", + "explanation": "The vowel substrings of word are as follows (underlined):\n- "aeiouu"\n- "aeiouu"" + }, + { + "example_num": 2, + "expected_input": "word = "unicornarihan"", + "expected_output": "0", + "explanation": "Not all 5 vowels are present, so there are no vowel substrings." + }, + { + "example_num": 3, + "expected_input": "word = "cuaieuouac"", + "expected_output": "7", + "explanation": "The vowel substrings of word are as follows (underlined):\n- "cuaieuouac"\n- "cuaieuouac"\n- "cuaieuouac"\n- "cuaieuouac"\n- "cuaieuouac"\n- "cuaieuouac"\n- "cuaieuouac"" + } + ] + }, + { + "_id": "66f925defdfb8e1665720ed0", + "questionid": 1029, + "title": "Reverse Nodes in Even Length Groups", + "slug": "reverse-nodes-in-even-length-groups", + "description": "You are given the head of a linked list. The nodes in the linked list are sequentially assigned to non-empty groups whose lengths form the sequence of the natural numbers (1, 2, 3, 4, ...). The length of a group is the number of nodes assigned to it. In other words, Note that the length of the last group may be less than or equal to 1 + the length of the second to last group. Reverse the nodes in each group with an even length, and return the head of the modified linked list. ", + "category": [ + "Linked List" + ], + "complexity": "Medium", + "successrate": 50.3, + "totalsubmissions": 18680, + "totalaccepted": 9388, + "likes": 177, + "dislikes": 189, + "hints": "Consider the list structure ...A †’ (B †’ ... †’ C) †’ D..., where the nodes between B and C (inclusive) form a group, A is the last node of the previous group, and D is the first node of the next group. How can you utilize this structure? Suppose you have B †’ ... †’ C reversed (because it was of even length) so that it is now C †’ ... †’ B. What references do you need to fix so that the transitions between the previous, current, and next groups are correct? A.next should be set to C, and B.next should be set to D. Once the current group is finished being modified, you need to find the new A, B, C, and D nodes for the next group. How can you use the old A, B, C, and D nodes to find the new ones? The new A is either the old B or old C depending on if the group was of even or odd length. The new B is always the old D. The new C and D can be found based on the new B and the next group's length. You can set the initial values of A, B, C, and D to A = null, B = head, C = head, D = head.next. Repeat the steps from the previous hints until D is null.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "head = [5,2,6,3,9,1,7,3,8,4]", + "expected_output": "[5,6,2,3,9,1,4,8,3,7]", + "explanation": "- The length of the first group is 1, which is odd, hence no reversal occurs.\n- The length of the second group is 2, which is even, hence the nodes are reversed.\n- The length of the third group is 3, which is odd, hence no reversal occurs.\n- The length of the last group is 4, which is even, hence the nodes are reversed." + }, + { + "example_num": 2, + "expected_input": "head = [1,1,0,6]", + "expected_output": "[1,0,1,6]", + "explanation": "- The length of the first group is 1. No reversal occurs.\n- The length of the second group is 2. The nodes are reversed.\n- The length of the last group is 1. No reversal occurs." + }, + { + "example_num": 3, + "expected_input": "head = [1,1,0,6,5]", + "expected_output": "[1,0,1,5,6]", + "explanation": "- The length of the first group is 1. No reversal occurs.\n- The length of the second group is 2. The nodes are reversed.\n- The length of the last group is 2. The nodes are reversed." + } + ] + }, + { + "_id": "66f925defdfb8e1665720ed3", + "questionid": 1032, + "title": "Find Subsequence of Length K With the Largest Sum", + "slug": "find-subsequence-of-length-k-with-the-largest-sum", + "description": "You are given an integer array nums and an integer k. You want to find a subsequence of nums of length k that has the largest sum. Return any such subsequence as an integer array of length k. A subsequence is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements. ", + "category": [ + "Array", + "Hash Table", + "Sorting", + "Heap (Priority Queue)" + ], + "complexity": "Easy", + "successrate": 43.6, + "totalsubmissions": 34727, + "totalaccepted": 15145, + "likes": 412, + "dislikes": 39, + "hints": "From a greedy perspective, what k elements should you pick? Could you sort the array while maintaining the index?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [2,1,3,3], k = 2", + "expected_output": "[3,3]", + "explanation": "The subsequence has the largest sum of 3 + 3 = 6." + }, + { + "example_num": 2, + "expected_input": "nums = [-1,-2,3,4], k = 3", + "expected_output": "[-1,3,4]", + "explanation": "The subsequence has the largest sum of -1 + 3 + 4 = 6." + }, + { + "example_num": 3, + "expected_input": "nums = [3,4,3,3], k = 2", + "expected_output": "[3,4]", + "explanation": "The subsequence has the largest sum of 3 + 4 = 7. \nAnother possible subsequence is [4, 3]." + } + ] + }, + { + "_id": "66f925defdfb8e1665720ed7", + "questionid": 1036, + "title": "Removing Minimum and Maximum From Array", + "slug": "removing-minimum-and-maximum-from-array", + "description": "You are given a 0-indexed array of distinct integers nums. There is an element in nums that has the lowest value and an element that has the highest value. We call them the minimum and maximum respectively. Your goal is to remove both these elements from the array. A deletion is defined as either removing an element from the front of the array or removing an element from the back of the array. Return the minimum number of deletions it would take to remove both the minimum and maximum element from the array. ", + "category": [ + "Array", + "Greedy" + ], + "complexity": "Medium", + "successrate": 57.6, + "totalsubmissions": 28027, + "totalaccepted": 16157, + "likes": 314, + "dislikes": 16, + "hints": "There can only be three scenarios for deletions such that both minimum and maximum elements are removed: Scenario 1: Both elements are removed by only deleting from the front. Scenario 2: Both elements are removed by only deleting from the back. Scenario 3: Delete from the front to remove one of the elements, and delete from the back to remove the other element. Compare which of the three scenarios results in the minimum number of moves.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [2,10,7,5,4,1,8,6]", + "expected_output": "5", + "explanation": "The minimum element in the array is nums[5], which is 1.\nThe maximum element in the array is nums[1], which is 10.\nWe can remove both the minimum and maximum by removing 2 elements from the front and 3 elements from the back.\nThis results in 2 + 3 = 5 deletions, which is the minimum number possible." + }, + { + "example_num": 2, + "expected_input": "nums = [0,-4,19,1,8,-2,-3,5]", + "expected_output": "3", + "explanation": "The minimum element in the array is nums[1], which is -4.\nThe maximum element in the array is nums[2], which is 19.\nWe can remove both the minimum and maximum by removing 3 elements from the front.\nThis results in only 3 deletions, which is the minimum number possible." + }, + { + "example_num": 3, + "expected_input": "nums = [101]", + "expected_output": "1", + "explanation": "There is only one element in the array, which makes it both the minimum and maximum element.\nWe can remove it with 1 deletion." + } + ] + }, + { + "_id": "66f925defdfb8e1665720ed8", + "questionid": 1037, + "title": "Find All People With Secret", + "slug": "find-all-people-with-secret", + "description": "You are given an integer n indicating there are n people numbered from 0 to n - 1. You are also given a 0-indexed 2D integer array meetings where meetings[i] = [xi, yi, timei] indicates that person xi and person yi have a meeting at timei. A person may attend multiple meetings at the same time. Finally, you are given an integer firstPerson. Person 0 has a secret and initially shares the secret with a person firstPerson at time 0. This secret is then shared every time a meeting takes place with a person that has the secret. More formally, for every meeting, if a person xi has the secret at timei, then they will share the secret with person yi, and vice versa. The secrets are shared instantaneously. That is, a person may receive the secret and share it with people in other meetings within the same time frame. Return a list of all the people that have the secret after all the meetings have taken place. You may return the answer in any order. ", + "category": [ + "Depth-First Search", + "Breadth-First Search", + "Union Find", + "Graph", + "Sorting" + ], + "complexity": "Hard", + "successrate": 32.8, + "totalsubmissions": 38441, + "totalaccepted": 12595, + "likes": 423, + "dislikes": 20, + "hints": "Could you model all the meetings happening at the same time as a graph? What data structure can you use to efficiently share the secret? You can use the union-find data structure to quickly determine who knows the secret and share the secret.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 6, meetings = [[1,2,5],[2,3,8],[1,5,10]], firstPerson = 1", + "expected_output": "[0,1,2,3,5]\nExplanation:\nAt time 0, person 0 shares the secret with person 1.\nAt time 5, person 1 shares the secret with person 2.\nAt time 8, person 2 shares the secret with person 3.\nAt time 10, person 1 shares the secret with person 5.​​​​\nThus, people 0, 1, 2, 3, and 5 know the secret after all the meetings.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "n = 4, meetings = [[3,1,3],[1,2,2],[0,3,3]], firstPerson = 3", + "expected_output": "[0,1,3]", + "explanation": "At time 0, person 0 shares the secret with person 3.\nAt time 2, neither person 1 nor person 2 know the secret.\nAt time 3, person 3 shares the secret with person 0 and person 1.\nThus, people 0, 1, and 3 know the secret after all the meetings." + }, + { + "example_num": 3, + "expected_input": "n = 5, meetings = [[3,4,2],[1,2,1],[2,3,1]], firstPerson = 1", + "expected_output": "[0,1,2,3,4]", + "explanation": "At time 0, person 0 shares the secret with person 1.\nAt time 1, person 1 shares the secret with person 2, and person 2 shares the secret with person 3.\nNote that person 2 can share the secret at the same time as receiving it.\nAt time 2, person 3 shares the secret with person 4.\nThus, people 0, 1, 2, 3, and 4 know the secret after all the meetings." + } + ] + }, + { + "_id": "66f925defdfb8e1665720ed9", + "questionid": 1038, + "title": "Delete the Middle Node of a Linked List", + "slug": "delete-the-middle-node-of-a-linked-list", + "description": "You are given the head of a linked list. Delete the middle node, and return the head of the modified linked list. The middle node of a linked list of size n is the n / 2 th node from the start using 0-based indexing, where x denotes the largest integer less than or equal to x. ", + "category": [ + "Linked List", + "Two Pointers" + ], + "complexity": "Medium", + "successrate": 57.2, + "totalsubmissions": 72447, + "totalaccepted": 41449, + "likes": 693, + "dislikes": 22, + "hints": "If a point with a speed s moves n units in a given time, a point with speed 2 * s will move 2 * n units at the same time. Can you use this to find the middle node of a linked list? If you are given the middle node, the node before it, and the node after it, how can you modify the linked list?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "head = [1,3,4,7,1,2,6]", + "expected_output": "[1,3,4,1,2,6]", + "explanation": "The above figure represents the given linked list. The indices of the nodes are written below.\nSince n = 7, node 3 with value 7 is the middle node, which is marked in red.\nWe return the new list after removing this node." + }, + { + "example_num": 2, + "expected_input": "head = [1,2,3,4]", + "expected_output": "[1,2,4]", + "explanation": "The above figure represents the given linked list.\nFor n = 4, node 2 with value 3 is the middle node, which is marked in red." + }, + { + "example_num": 3, + "expected_input": "head = [2,1]", + "expected_output": "[2]", + "explanation": "The above figure represents the given linked list.\nFor n = 2, node 1 with value 1 is the middle node, which is marked in red.\nNode 0 with value 2 is the only node remaining after removing node 1." + } + ] + }, + { + "_id": "66f925defdfb8e1665720edb", + "questionid": 1040, + "title": "Find All Possible Recipes from Given Supplies", + "slug": "find-all-possible-recipes-from-given-supplies", + "description": "You have information about n different recipes. You are given a string array recipes and a 2D string array ingredients. The ith recipe has the name recipes[i], and you can create it if you have all the needed ingredients from ingredients[i]. Ingredients to a recipe may need to be created from other recipes, i.e., ingredients[i] may contain a string that is in recipes. You are also given a string array supplies containing all the ingredients that you initially have, and you have an infinite supply of all of them. Return a list of all the recipes that you can create. You may return the answer in any order. Note that two recipes may contain each other in their ingredients. ", + "category": [ + "Array", + "Hash Table", + "String", + "Graph", + "Topological Sort" + ], + "complexity": "Medium", + "successrate": 42.7, + "totalsubmissions": 49865, + "totalaccepted": 21290, + "likes": 600, + "dislikes": 46, + "hints": "Can we use a data structure to quickly query whether we have a certain ingredient? Once we verify that we can make a recipe, we can add it to our ingredient data structure. We can then check if we can make more recipes as a result of this.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "recipes = ["bread"], ingredients = [["yeast","flour"]], supplies = ["yeast","flour","corn"]", + "expected_output": "["bread"]", + "explanation": "We can create "bread" since we have the ingredients "yeast" and "flour"." + }, + { + "example_num": 2, + "expected_input": "recipes = ["bread","sandwich"], ingredients = [["yeast","flour"],["bread","meat"]], supplies = ["yeast","flour","meat"]", + "expected_output": "["bread","sandwich"]", + "explanation": "We can create "bread" since we have the ingredients "yeast" and "flour".\nWe can create "sandwich" since we have the ingredient "meat" and can create the ingredient "bread"." + }, + { + "example_num": 3, + "expected_input": "recipes = ["bread","sandwich","burger"], ingredients = [["yeast","flour"],["bread","meat"],["sandwich","meat","bread"]], supplies = ["yeast","flour","meat"]", + "expected_output": "["bread","sandwich","burger"]", + "explanation": "We can create "bread" since we have the ingredients "yeast" and "flour".\nWe can create "sandwich" since we have the ingredient "meat" and can create the ingredient "bread".\nWe can create "burger" since we have the ingredient "meat" and can create the ingredients "bread" and "sandwich"." + } + ] + }, + { + "_id": "66f925defdfb8e1665720edf", + "questionid": 1044, + "title": "Adding Spaces to a String", + "slug": "adding-spaces-to-a-string", + "description": "You are given a 0-indexed string s and a 0-indexed integer array spaces that describes the indices in the original string where spaces will be added. Each space should be inserted before the character at the given index. Return the modified string after the spaces have been added. ", + "category": [ + "Array", + "String", + "Simulation" + ], + "complexity": "Medium", + "successrate": 56, + "totalsubmissions": 36845, + "totalaccepted": 20644, + "likes": 248, + "dislikes": 26, + "hints": "Create a new string, initially empty, as the modified string. Iterate through the original string and append each character of the original string to the new string. However, each time you reach a character that requires a space before it, append a space before appending the character. Since the array of indices for the space locations is sorted, use a pointer to keep track of the next index to place a space. Only increment the pointer once a space has been appended. Ensure that your append operation can be done in O(1).", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "LeetcodeHelpsMeLearn", spaces = [8,13,15]", + "expected_output": ""Leetcode Helps Me Learn"", + "explanation": "The indices 8, 13, and 15 correspond to the underlined characters in "LeetcodeHelpsMeLearn".\nWe then place spaces before those characters." + }, + { + "example_num": 2, + "expected_input": "s = "icodeinpython", spaces = [1,5,7,9]", + "expected_output": ""i code in py thon"", + "explanation": "The indices 1, 5, 7, and 9 correspond to the underlined characters in "icodeinpython".\nWe then place spaces before those characters." + }, + { + "example_num": 3, + "expected_input": "s = "spacing", spaces = [0,1,2,3,4,5,6]", + "expected_output": "" s p a c i n g"", + "explanation": "We are also able to place spaces before the first character of the string." + } + ] + }, + { + "_id": "66f925defdfb8e1665720ee2", + "questionid": 1047, + "title": "Maximum Twin Sum of a Linked List", + "slug": "maximum-twin-sum-of-a-linked-list", + "description": "In a linked list of size n, where n is even, the ith node (0-indexed) of the linked list is known as the twin of the (n-1-i)th node, if 0 <= i <= (n / 2) - 1. The twin sum is defined as the sum of a node and its twin. Given the head of a linked list with even length, return the maximum twin sum of the linked list. ", + "category": [ + "Linked List", + "Two Pointers", + "Stack" + ], + "complexity": "Medium", + "successrate": 82.2, + "totalsubmissions": 34349, + "totalaccepted": 28247, + "likes": 485, + "dislikes": 21, + "hints": "How can \"reversing\" a part of the linked list help find the answer? We know that the nodes of the first half are twins of nodes in the second half, so try dividing the linked list in half and reverse the second half. How can two pointers be used to find every twin sum optimally? Use two different pointers pointing to the first nodes of the two halves of the linked list. The second pointer will point to the first node of the reversed half, which is the (n-1-i)th node in the original linked list. By moving both pointers forward at the same time, we find all twin sums.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "head = [5,4,2,1]", + "expected_output": "6", + "explanation": "Nodes 0 and 1 are the twins of nodes 3 and 2, respectively. All have twin sum = 6.\nThere are no other nodes with twins in the linked list.\nThus, the maximum twin sum of the linked list is 6." + }, + { + "example_num": 2, + "expected_input": "head = [4,2,2,3]", + "expected_output": "7", + "explanation": "The nodes with twins present in this linked list are:\n- Node 0 is the twin of node 3 having a twin sum of 4 + 3 = 7.\n- Node 1 is the twin of node 2 having a twin sum of 2 + 2 = 4.\nThus, the maximum twin sum of the linked list is max(7, 4) = 7." + }, + { + "example_num": 3, + "expected_input": "head = [1,100000]", + "expected_output": "100001", + "explanation": "There is only one node with a twin in the linked list having twin sum of 1 + 100000 = 100001." + } + ] + }, + { + "_id": "66f925defdfb8e1665720ee4", + "questionid": 1049, + "title": "A Number After a Double Reversal", + "slug": "a-number-after-a-double-reversal", + "description": "Reversing an integer means to reverse all its digits. Given an integer num, reverse num to get reversed1, then reverse reversed1 to get reversed2. Return true if reversed2 equals num. Otherwise return false. ", + "category": [ + "Math" + ], + "complexity": "Easy", + "successrate": 76.9, + "totalsubmissions": 34908, + "totalaccepted": 26859, + "likes": 224, + "dislikes": 14, + "hints": "Other than the number 0 itself, any number that ends with 0 would lose some digits permanently when reversed.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "num = 526", + "expected_output": "true", + "explanation": "Reverse num to get 625, then reverse 625 to get 526, which equals num." + }, + { + "example_num": 2, + "expected_input": "num = 1800", + "expected_output": "false", + "explanation": "Reverse num to get 81, then reverse 81 to get 18, which does not equal num." + }, + { + "example_num": 3, + "expected_input": "num = 0", + "expected_output": "true", + "explanation": "Reverse num to get 0, then reverse 0 to get 0, which equals num." + } + ] + }, + { + "_id": "66f925defdfb8e1665720eea", + "questionid": 1055, + "title": "Number of Ways to Divide a Long Corridor", + "slug": "number-of-ways-to-divide-a-long-corridor", + "description": "Along a long library corridor, there is a line of seats and decorative plants. You are given a 0-indexed string corridor of length n consisting of letters 'S' and 'P' where each 'S' represents a seat and each 'P' represents a plant. One room divider has already been installed to the left of index 0, and another to the right of index n - 1. Additional room dividers can be installed. For each position between indices i - 1 and i (1 <= i <= n - 1), at most one divider can be installed. Divide the corridor into non-overlapping sections, where each section has exactly two seats with any number of plants. There may be multiple ways to perform the division. Two ways are different if there is a position with a room divider installed in the first way but not in the second way. Return the number of ways to divide the corridor. Since the answer may be very large, return it modulo 109 + 7. If there is no way, return 0. ", + "category": [ + "Math", + "String", + "Dynamic Programming" + ], + "complexity": "Hard", + "successrate": 40, + "totalsubmissions": 16228, + "totalaccepted": 6485, + "likes": 178, + "dislikes": 17, + "hints": "Divide the corridor into segments. Each segment has two seats, starts precisely with one seat, and ends precisely with the other seat. How many dividers can you install between two adjacent segments? You must install precisely one. Otherwise, you would have created a section with not exactly two seats. If there are k plants between two adjacent segments, there are k + 1 positions (ways) you could install the divider you must install. The problem now becomes: Find the product of all possible positions between every two adjacent segments.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "corridor = "SSPPSPS"", + "expected_output": "3", + "explanation": "There are 3 different ways to divide the corridor.\nThe black bars in the above image indicate the two room dividers already installed.\nNote that in each of the ways, each section has exactly two seats." + }, + { + "example_num": 2, + "expected_input": "corridor = "PPSPSP"", + "expected_output": "1", + "explanation": "There is only 1 way to divide the corridor, by not installing any additional dividers.\nInstalling any would create some section that does not have exactly two seats." + }, + { + "example_num": 3, + "expected_input": "corridor = "S"", + "expected_output": "0", + "explanation": "There is no way to divide the corridor because there will always be a section that does not have exactly two seats." + } + ] + }, + { + "_id": "66f925defdfb8e1665720eec", + "questionid": 1057, + "title": "Minimum Swaps to Group All 1's Together II", + "slug": "minimum-swaps-to-group-all-1s-together-ii", + "description": "A swap is defined as taking two distinct positions in an array and swapping the values in them. A circular array is defined as an array where we consider the first element and the last element to be adjacent. Given a binary circular array nums, return the minimum number of swaps required to group all 1's present in the array together at any location. ", + "category": [ + "Array", + "Sliding Window" + ], + "complexity": "Medium", + "successrate": 47.6, + "totalsubmissions": 27620, + "totalaccepted": 13137, + "likes": 547, + "dislikes": 6, + "hints": "Notice that the number of 1€™s to be grouped together is fixed. It is the number of 1's the whole array has. Call this number total. We should then check for every subarray of size total (possibly wrapped around), how many swaps are required to have the subarray be all 1€™s. The number of swaps required is the number of 0€™s in the subarray. To eliminate the circular property of the array, we can append the original array to itself. Then, we check each subarray of length total. How do we avoid recounting the number of 0€™s in the subarray each time? The Sliding Window technique can help.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [0,1,0,1,1,0,0]", + "expected_output": "1", + "explanation": "Here are a few of the ways to group all the 1's together:\n[0,0,1,1,1,0,0] using 1 swap.\n[0,1,1,1,0,0,0] using 1 swap.\n[1,1,0,0,0,0,1] using 2 swaps (using the circular property of the array).\nThere is no way to group all 1's together with 0 swaps.\nThus, the minimum number of swaps required is 1." + }, + { + "example_num": 2, + "expected_input": "nums = [0,1,1,1,0,0,1,1,0]", + "expected_output": "2", + "explanation": "Here are a few of the ways to group all the 1's together:\n[1,1,1,0,0,0,0,1,1] using 2 swaps (using the circular property of the array).\n[1,1,1,1,1,0,0,0,0] using 2 swaps.\nThere is no way to group all 1's together with 0 or 1 swaps.\nThus, the minimum number of swaps required is 2." + }, + { + "example_num": 3, + "expected_input": "nums = [1,1,0,0,1]", + "expected_output": "0", + "explanation": "All the 1's are already grouped together due to the circular property of the array.\nThus, the minimum number of swaps required is 0." + } + ] + }, + { + "_id": "66f925defdfb8e1665720ef9", + "questionid": 1070, + "title": "Counting Words With a Given Prefix", + "slug": "counting-words-with-a-given-prefix", + "description": "You are given an array of strings words and a string pref. Return the number of strings in words that contain pref as a prefix. A prefix of a string s is any leading contiguous substring of s. ", + "category": [ + "Array", + "String" + ], + "complexity": "Easy", + "successrate": 77.7, + "totalsubmissions": 35648, + "totalaccepted": 27707, + "likes": 190, + "dislikes": 3, + "hints": "Go through each word in words and increment the answer if pref is a prefix of the word.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "words = ["pay","attention","practice","attend"], pref = "at"", + "expected_output": "2", + "explanation": "The 2 strings that contain "at" as a prefix are: "attention" and "attend"." + }, + { + "example_num": 2, + "expected_input": "words = ["leetcode","win","loops","success"], pref = "code"", + "expected_output": "0", + "explanation": "There are no strings that contain "code" as a prefix." + } + ] + }, + { + "_id": "66f925defdfb8e1665720efb", + "questionid": 1072, + "title": "Minimum Time to Complete Trips", + "slug": "minimum-time-to-complete-trips", + "description": "You are given an array time where time[i] denotes the time taken by the ith bus to complete one trip. Each bus can make multiple trips successively; that is, the next trip can start immediately after completing the current trip. Also, each bus operates independently; that is, the trips of one bus do not influence the trips of any other bus. You are also given an integer totalTrips, which denotes the number of trips all buses should make in total. Return the minimum time required for all buses to complete at least totalTrips trips. ", + "category": [ + "Array", + "Binary Search" + ], + "complexity": "Medium", + "successrate": 29.6, + "totalsubmissions": 64231, + "totalaccepted": 19043, + "likes": 517, + "dislikes": 24, + "hints": "For a given amount of time, how can we count the total number of trips completed by all buses within that time? Consider using binary search.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "time = [1,2,3], totalTrips = 5", + "expected_output": "3", + "explanation": "- At time t = 1, the number of trips completed by each bus are [1,0,0]. \n The total number of trips completed is 1 + 0 + 0 = 1.\n- At time t = 2, the number of trips completed by each bus are [2,1,0]. \n The total number of trips completed is 2 + 1 + 0 = 3.\n- At time t = 3, the number of trips completed by each bus are [3,1,1]. \n The total number of trips completed is 3 + 1 + 1 = 5.\nSo the minimum time needed for all buses to complete at least 5 trips is 3." + }, + { + "example_num": 2, + "expected_input": "time = [2], totalTrips = 1", + "expected_output": "2", + "explanation": "There is only one bus, and it will complete its first trip at t = 2.\nSo the minimum time needed to complete 1 trip is 2." + } + ] + }, + { + "_id": "66f925defdfb8e1665720efe", + "questionid": 1075, + "title": "Merge Nodes in Between Zeros", + "slug": "merge-nodes-in-between-zeros", + "description": "You are given the head of a linked list, which contains a series of integers separated by 0's. The beginning and end of the linked list will have Node.val == 0. For every two consecutive 0's, merge all the nodes lying in between them into a single node whose value is the sum of all the merged nodes. The modified list should not contain any 0's. Return the head of the modified linked list. ", + "category": [ + "Linked List", + "Simulation" + ], + "complexity": "Medium", + "successrate": 87.1, + "totalsubmissions": 31121, + "totalaccepted": 27114, + "likes": 380, + "dislikes": 9, + "hints": "How can you use two pointers to modify the original list into the new list? Have a pointer traverse the entire linked list, while another pointer looks at a node that is currently being modified. Keep on summing the values of the nodes between the traversal pointer and the modifying pointer until the former comes across a €˜0€™. In that case, the modifying pointer is incremented to modify the next node. Do not forget to have the next pointer of the final node of the modified list point to null.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "head = [0,3,1,0,4,5,2,0]", + "expected_output": "[4,11]", + "explanation": "The above figure represents the given linked list. The modified list contains\n- The sum of the nodes marked in green: 3 + 1 = 4.\n- The sum of the nodes marked in red: 4 + 5 + 2 = 11." + }, + { + "example_num": 2, + "expected_input": "head = [0,1,0,3,0,2,2,0]", + "expected_output": "[1,3,4]", + "explanation": "The above figure represents the given linked list. The modified list contains\n- The sum of the nodes marked in green: 1 = 1.\n- The sum of the nodes marked in red: 3 = 3.\n- The sum of the nodes marked in yellow: 2 + 2 = 4." + } + ] + }, + { + "_id": "66f925defdfb8e1665720f05", + "questionid": 1082, + "title": "Longest Substring of One Repeating Character", + "slug": "longest-substring-of-one-repeating-character", + "description": "You are given a 0-indexed string s. You are also given a 0-indexed string queryCharacters of length k and a 0-indexed array of integer indices queryIndices of length k, both of which are used to describe k queries. The ith query updates the character in s at index queryIndices[i] to the character queryCharacters[i]. Return an array lengths of length k where lengths[i] is the length of the longest substring of s consisting of only one repeating character after the ith query is performed. ", + "category": [ + "Array", + "String", + "Segment Tree", + "Ordered Set" + ], + "complexity": "Hard", + "successrate": 28.5, + "totalsubmissions": 6683, + "totalaccepted": 1906, + "likes": 97, + "dislikes": 66, + "hints": "Use a segment tree to perform fast point updates and range queries. We need each segment tree node to store the length of the longest substring of that segment consisting of only 1 repeating character. We will also have each segment tree node store the leftmost and rightmost character of the segment, the max length of a prefix substring consisting of only 1 repeating character, and the max length of a suffix substring consisting of only 1 repeating character. Use this information to properly merge the two segment tree nodes together.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "babacc", queryCharacters = "bcb", queryIndices = [1,3,3]", + "expected_output": "[3,3,4]", + "explanation": "- 1st query updates s = "bbbacc". The longest substring consisting of one repeating character is "bbb" with length 3.\n- 2nd query updates s = "bbbccc". \n The longest substring consisting of one repeating character can be "bbb" or "ccc" with length 3.\n- 3rd query updates s = "bbbbcc". The longest substring consisting of one repeating character is "bbbb" with length 4.\nThus, we return [3,3,4]." + }, + { + "example_num": 2, + "expected_input": "s = "abyzz", queryCharacters = "aa", queryIndices = [2,1]", + "expected_output": "[2,3]", + "explanation": "- 1st query updates s = "abazz". The longest substring consisting of one repeating character is "zz" with length 2.\n- 2nd query updates s = "aaazz". The longest substring consisting of one repeating character is "aaa" with length 3.\nThus, we return [2,3]." + } + ] + }, + { + "_id": "66f925defdfb8e1665720f06", + "questionid": 1083, + "title": "Find All K-Distant Indices in an Array", + "slug": "find-all-k-distant-indices-in-an-array", + "description": "You are given a 0-indexed integer array nums and two integers key and k. A k-distant index is an index i of nums for which there exists at least one index j such that |i - j| <= k and nums[j] == key. Return a list of all k-distant indices sorted in increasing order. ", + "category": [ + "Array" + ], + "complexity": "Easy", + "successrate": 64.4, + "totalsubmissions": 32898, + "totalaccepted": 21198, + "likes": 177, + "dislikes": 26, + "hints": "For every occurrence of key in nums, find all indices within distance k from it. Use a hash table to remove duplicate indices.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [3,4,9,1,3,9,5], key = 9, k = 1", + "expected_output": "[1,2,3,4,5,6]", + "explanation": "Here, nums[2] == key and nums[5] == key.\n- For index 0, |0 - 2| > k and |0 - 5| > k, so there is no j where |0 - j| <= k and nums[j] == key. Thus, 0 is not a k-distant index.\n- For index 1, |1 - 2| <= k and nums[2] == key, so 1 is a k-distant index.\n- For index 2, |2 - 2| <= k and nums[2] == key, so 2 is a k-distant index.\n- For index 3, |3 - 2| <= k and nums[2] == key, so 3 is a k-distant index.\n- For index 4, |4 - 5| <= k and nums[5] == key, so 4 is a k-distant index.\n- For index 5, |5 - 5| <= k and nums[5] == key, so 5 is a k-distant index.\n- For index 6, |6 - 5| <= k and nums[5] == key, so 6 is a k-distant index.\nThus, we return [1,2,3,4,5,6] which is sorted in increasing order." + }, + { + "example_num": 2, + "expected_input": "nums = [2,2,2,2,2], key = 2, k = 2", + "expected_output": "[0,1,2,3,4]", + "explanation": "For all indices i in nums, there exists some index j such that |i - j| <= k and nums[j] == key, so every index is a k-distant index. \nHence, we return [0,1,2,3,4]." + } + ] + }, + { + "_id": "66f925defdfb8e1665720ebd", + "questionid": 1010, + "title": "Stone Game IX", + "slug": "stone-game-ix", + "description": "Alice and Bob continue their games with stones. There is a row of n stones, and each stone has an associated value. You are given an integer array stones, where stones[i] is the value of the ith stone. Alice and Bob take turns, with Alice starting first. On each turn, the player may remove any stone from stones. The player who removes a stone loses if the sum of the values of all removed stones is divisible by 3. Bob will win automatically if there are no remaining stones (even if it is Alice's turn). Assuming both players play optimally, return true if Alice wins and false if Bob wins. ", + "category": [ + "Array", + "Math", + "Greedy", + "Counting", + "Game Theory" + ], + "complexity": "Medium", + "successrate": 24.8, + "totalsubmissions": 19252, + "totalaccepted": 4771, + "likes": 140, + "dislikes": 202, + "hints": "There are limited outcomes given the current sum and the stones remaining. Can we greedily simulate starting with taking a stone with remainder 1 or 2 divided by 3?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "stones = [2,1]", + "expected_output": "true", + "explanation": " The game will be played as follows:\n- Turn 1: Alice can remove either stone.\n- Turn 2: Bob removes the remaining stone. \nThe sum of the removed stones is 1 + 2 = 3 and is divisible by 3. Therefore, Bob loses and Alice wins the game." + }, + { + "example_num": 2, + "expected_input": "stones = [2]", + "expected_output": "false", + "explanation": " Alice will remove the only stone, and the sum of the values on the removed stones is 2. \nSince all the stones are removed and the sum of values is not divisible by 3, Bob wins the game." + }, + { + "example_num": 3, + "expected_input": "stones = [5,1,2,4,3]", + "expected_output": "false", + "explanation": "Bob will always win. One possible way for Bob to win is shown below:\n- Turn 1: Alice can remove the second stone with value 1. Sum of removed stones = 1.\n- Turn 2: Bob removes the fifth stone with value 3. Sum of removed stones = 1 + 3 = 4.\n- Turn 3: Alices removes the fourth stone with value 4. Sum of removed stones = 1 + 3 + 4 = 8.\n- Turn 4: Bob removes the third stone with value 2. Sum of removed stones = 1 + 3 + 4 + 2 = 10.\n- Turn 5: Alice removes the first stone with value 5. Sum of removed stones = 1 + 3 + 4 + 2 + 5 = 15.\nAlice loses the game because the sum of the removed stones (15) is divisible by 3. Bob wins the game." + } + ] + }, + { + "_id": "66f925defdfb8e1665720ebe", + "questionid": 1011, + "title": "Smallest K-Length Subsequence With Occurrences of a Letter", + "slug": "smallest-k-length-subsequence-with-occurrences-of-a-letter", + "description": "You are given a string s, an integer k, a letter letter, and an integer repetition. Return the lexicographically smallest subsequence of s of length k that has the letter letter appear at least repetition times. The test cases are generated so that the letter appears in s at least repetition times. A subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters. A string a is lexicographically smaller than a string b if in the first position where a and b differ, string a has a letter that appears earlier in the alphabet than the corresponding letter in b. ", + "category": [ + "String", + "Stack", + "Greedy", + "Monotonic Stack" + ], + "complexity": "Hard", + "successrate": 38.7, + "totalsubmissions": 11283, + "totalaccepted": 4365, + "likes": 244, + "dislikes": 6, + "hints": "Use stack. For every character to be appended, decide how many character(s) from the stack needs to get popped based on the stack length and the count of the required character. Pop the extra characters out from the stack and return the characters in the stack (reversed).", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "leet", k = 3, letter = "e", repetition = 1", + "expected_output": ""eet"", + "explanation": "There are four subsequences of length 3 that have the letter 'e' appear at least 1 time:\n- "lee" (from "leet")\n- "let" (from "leet")\n- "let" (from "leet")\n- "eet" (from "leet")\nThe lexicographically smallest subsequence among them is "eet"." + }, + { + "example_num": 2, + "expected_input": "s = "leetcode", k = 4, letter = "e", repetition = 2", + "expected_output": ""ecde"", + "explanation": ""ecde" is the lexicographically smallest subsequence of length 4 that has the letter "e" appear at least 2 times." + }, + { + "example_num": 3, + "expected_input": "s = "bb", k = 2, letter = "b", repetition = 2", + "expected_output": ""bb"", + "explanation": ""bb" is the only subsequence of length 2 that has the letter "b" appear at least 2 times." + } + ] + }, + { + "_id": "66f925defdfb8e1665720ebf", + "questionid": 1012, + "title": "Minimum Operations to Make a Uni-Value Grid", + "slug": "minimum-operations-to-make-a-uni-value-grid", + "description": "You are given a 2D integer grid of size m x n and an integer x. In one operation, you can add x to or subtract x from any element in the grid. A uni-value grid is a grid where all the elements of it are equal. Return the minimum number of operations to make the grid uni-value. If it is not possible, return -1. ", + "category": [ + "Array", + "Math", + "Sorting", + "Matrix" + ], + "complexity": "Medium", + "successrate": 50.5, + "totalsubmissions": 26429, + "totalaccepted": 13355, + "likes": 304, + "dislikes": 29, + "hints": "Is it possible to make two integers a and b equal if they have different remainders dividing by x? If it is possible, which number should you select to minimize the number of operations? What if the elements are sorted?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "grid = [[2,4],[6,8]], x = 2", + "expected_output": "4", + "explanation": "We can make every element equal to 4 by doing the following: \n- Add x to 2 once.\n- Subtract x from 6 once.\n- Subtract x from 8 twice.\nA total of 4 operations were used." + }, + { + "example_num": 2, + "expected_input": "grid = [[1,5],[2,3]], x = 1", + "expected_output": "5", + "explanation": "We can make every element equal to 3." + }, + { + "example_num": 3, + "expected_input": "grid = [[1,2],[3,4]], x = 2", + "expected_output": "-1", + "explanation": "It is impossible to make every element equal." + } + ] + }, + { + "_id": "66f925defdfb8e1665720ec5", + "questionid": 1018, + "title": "Next Greater Numerically Balanced Number", + "slug": "next-greater-numerically-balanced-number", + "description": "An integer x is numerically balanced if for every digit d in the number x, there are exactly d occurrences of that digit in x. Given an integer n, return the smallest numerically balanced number strictly greater than n. ", + "category": [ + "Math", + "Backtracking", + "Enumeration" + ], + "complexity": "Medium", + "successrate": 46.2, + "totalsubmissions": 17965, + "totalaccepted": 8293, + "likes": 95, + "dislikes": 218, + "hints": "How far away can the next greater numerically balanced number be from n? With the given constraints, what is the largest numerically balanced number?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 1", + "expected_output": "22", + "explanation": "22 is numerically balanced since:\n- The digit 2 occurs 2 times. \nIt is also the smallest numerically balanced number strictly greater than 1." + }, + { + "example_num": 2, + "expected_input": "n = 1000", + "expected_output": "1333", + "explanation": "1333 is numerically balanced since:\n- The digit 1 occurs 1 time.\n- The digit 3 occurs 3 times. \nIt is also the smallest numerically balanced number strictly greater than 1000.\nNote that 1022 cannot be the answer because 0 appeared more than 0 times." + }, + { + "example_num": 3, + "expected_input": "n = 3000", + "expected_output": "3133", + "explanation": "3133 is numerically balanced since:\n- The digit 1 occurs 1 time.\n- The digit 3 occurs 3 times.\nIt is also the smallest numerically balanced number strictly greater than 3000." + } + ] + }, + { + "_id": "66f925defdfb8e1665720ec7", + "questionid": 1020, + "title": "Check Whether Two Strings are Almost Equivalent", + "slug": "check-whether-two-strings-are-almost-equivalent", + "description": "Two strings word1 and word2 are considered almost equivalent if the differences between the frequencies of each letter from 'a' to 'z' between word1 and word2 is at most 3. Given two strings word1 and word2, each of length n, return true if word1 and word2 are almost equivalent, or false otherwise. The frequency of a letter x is the number of times it occurs in the string. ", + "category": [ + "Hash Table", + "String", + "Counting" + ], + "complexity": "Easy", + "successrate": 66.4, + "totalsubmissions": 24735, + "totalaccepted": 16420, + "likes": 193, + "dislikes": 6, + "hints": "What data structure can we use to count the frequency of each character? Are there edge cases where a character is present in one string but not the other?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "word1 = "aaaa", word2 = "bccb"", + "expected_output": "false", + "explanation": "There are 4 'a's in "aaaa" but 0 'a's in "bccb".\nThe difference is 4, which is more than the allowed 3." + }, + { + "example_num": 2, + "expected_input": "word1 = "abcdeef", word2 = "abaaacc"", + "expected_output": "true", + "explanation": "The differences between the frequencies of each letter in word1 and word2 are at most 3:\n- 'a' appears 1 time in word1 and 4 times in word2. The difference is 3.\n- 'b' appears 1 time in word1 and 1 time in word2. The difference is 0.\n- 'c' appears 1 time in word1 and 2 times in word2. The difference is 1.\n- 'd' appears 1 time in word1 and 0 times in word2. The difference is 1.\n- 'e' appears 2 times in word1 and 0 times in word2. The difference is 2.\n- 'f' appears 1 time in word1 and 0 times in word2. The difference is 1." + }, + { + "example_num": 3, + "expected_input": "word1 = "cccddabba", word2 = "babababab"", + "expected_output": "true", + "explanation": "The differences between the frequencies of each letter in word1 and word2 are at most 3:\n- 'a' appears 2 times in word1 and 4 times in word2. The difference is 2.\n- 'b' appears 2 times in word1 and 5 times in word2. The difference is 3.\n- 'c' appears 3 times in word1 and 0 times in word2. The difference is 3.\n- 'd' appears 2 times in word1 and 0 times in word2. The difference is 2." + } + ] + }, + { + "_id": "66f925defdfb8e1665720ecd", + "questionid": 1026, + "title": "Count Common Words With One Occurrence", + "slug": "count-common-words-with-one-occurrence", + "description": "Given two string arrays words1 and words2, return the number of strings that appear exactly once in each of the two arrays. ", + "category": [ + "Array", + "Hash Table", + "String", + "Counting" + ], + "complexity": "Easy", + "successrate": 70.5, + "totalsubmissions": 31015, + "totalaccepted": 21864, + "likes": 295, + "dislikes": 6, + "hints": "Could you try every word? Could you use a hash map to achieve a good complexity?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "words1 = ["leetcode","is","amazing","as","is"], words2 = ["amazing","leetcode","is"]", + "expected_output": "2", + "explanation": "- "leetcode" appears exactly once in each of the two arrays. We count this string.\n- "amazing" appears exactly once in each of the two arrays. We count this string.\n- "is" appears in each of the two arrays, but there are 2 occurrences of it in words1. We do not count this string.\n- "as" appears once in words1, but does not appear in words2. We do not count this string.\nThus, there are 2 strings that appear exactly once in each of the two arrays." + }, + { + "example_num": 2, + "expected_input": "words1 = ["b","bb","bbb"], words2 = ["a","aa","aaa"]", + "expected_output": "0", + "explanation": "There are no strings that appear in each of the two arrays." + }, + { + "example_num": 3, + "expected_input": "words1 = ["a","ab"], words2 = ["a","a","a","ab"]", + "expected_output": "1", + "explanation": "The only string that appears exactly once in each of the two arrays is "ab"." + } + ] + }, + { + "_id": "66f925defdfb8e1665720ed1", + "questionid": 1030, + "title": "Two Furthest Houses With Different Colors", + "slug": "two-furthest-houses-with-different-colors", + "description": "There are n houses evenly lined up on the street, and each house is beautifully painted. You are given a 0-indexed integer array colors of length n, where colors[i] represents the color of the ith house. Return the maximum distance between two houses with different colors. The distance between the ith and jth houses is abs(i - j), where abs(x) is the absolute value of x. ", + "category": [ + "Array", + "Greedy" + ], + "complexity": "Easy", + "successrate": 68.6, + "totalsubmissions": 33973, + "totalaccepted": 23298, + "likes": 378, + "dislikes": 11, + "hints": "The constraints are small. Can you try the combination of every two houses? Greedily, the maximum distance will come from either the pair of the leftmost house and possibly some house on the right with a different color, or the pair of the rightmost house and possibly some house on the left with a different color.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "colors = [1,1,1,6,1,1,1]", + "expected_output": "3", + "explanation": "In the above image, color 1 is blue, and color 6 is red.\nThe furthest two houses with different colors are house 0 and house 3.\nHouse 0 has color 1, and house 3 has color 6. The distance between them is abs(0 - 3) = 3.\nNote that houses 3 and 6 can also produce the optimal answer." + }, + { + "example_num": 2, + "expected_input": "colors = [1,8,3,8,3]", + "expected_output": "4", + "explanation": "In the above image, color 1 is blue, color 8 is yellow, and color 3 is green.\nThe furthest two houses with different colors are house 0 and house 4.\nHouse 0 has color 1, and house 4 has color 3. The distance between them is abs(0 - 4) = 4." + }, + { + "example_num": 3, + "expected_input": "colors = [0,1]", + "expected_output": "1", + "explanation": "The furthest two houses with different colors are house 0 and house 1.\nHouse 0 has color 0, and house 1 has color 1. The distance between them is abs(0 - 1) = 1." + } + ] + }, + { + "_id": "66f925defdfb8e1665720ed2", + "questionid": 1031, + "title": "Sum of k-Mirror Numbers", + "slug": "sum-of-k-mirror-numbers", + "description": "A k-mirror number is a positive integer without leading zeros that reads the same both forward and backward in base-10 as well as in base-k. Given the base k and the number n, return the sum of the n smallest k-mirror numbers. ", + "category": [ + "Math", + "Enumeration" + ], + "complexity": "Hard", + "successrate": 41.2, + "totalsubmissions": 12203, + "totalaccepted": 5030, + "likes": 80, + "dislikes": 117, + "hints": "Since we need to reduce search space, instead of checking if every number is a palindrome in base-10, can we try to \"generate\" the palindromic numbers? If you are provided with a d digit number, how can you generate a palindrome with 2*d or 2*d - 1 digit? Try brute-forcing and checking if the palindrome you generated is a \"k-Mirror\" number.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "k = 2, n = 5", + "expected_output": "25\nExplanation:\nThe 5 smallest 2-mirror numbers and their representations in base-2 are listed as follows:\n base-10 base-2\n 1 1\n 3 11\n 5 101\n 7 111\n 9 1001\nTheir sum = 1 + 3 + 5 + 7 + 9 = 25.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "k = 3, n = 7", + "expected_output": "499\nExplanation:\nThe 7 smallest 3-mirror numbers are and their representations in base-3 are listed as follows:\n base-10 base-3\n 1 1\n 2 2\n 4 11\n 8 22\n 121 11111\n 151 12121\n 212 21212\nTheir sum = 1 + 2 + 4 + 8 + 121 + 151 + 212 = 499.", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "k = 7, n = 17", + "expected_output": "20379000", + "explanation": "The 17 smallest 7-mirror numbers are:\n1, 2, 3, 4, 5, 6, 8, 121, 171, 242, 292, 16561, 65656, 2137312, 4602064, 6597956, 6958596" + } + ] + }, + { + "_id": "66f925defdfb8e1665720ed5", + "questionid": 1034, + "title": "Find Target Indices After Sorting Array", + "slug": "find-target-indices-after-sorting-array", + "description": "You are given a 0-indexed integer array nums and a target element target. A target index is an index i such that nums[i] == target. Return a list of the target indices of nums after sorting nums in non-decreasing order. If there are no target indices, return an empty list. The returned list must be sorted in increasing order. ", + "category": [ + "Array", + "Binary Search", + "Sorting" + ], + "complexity": "Easy", + "successrate": 79.1, + "totalsubmissions": 63516, + "totalaccepted": 50251, + "likes": 568, + "dislikes": 28, + "hints": "Try \"sorting\" the array first. Now find all indices in the array whose values are equal to target.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,2,5,2,3], target = 2", + "expected_output": "[1,2]", + "explanation": "After sorting, nums is [1,2,2,3,5].\nThe indices where nums[i] == 2 are 1 and 2." + }, + { + "example_num": 2, + "expected_input": "nums = [1,2,5,2,3], target = 3", + "expected_output": "[3]", + "explanation": "After sorting, nums is [1,2,2,3,5].\nThe index where nums[i] == 3 is 3." + }, + { + "example_num": 3, + "expected_input": "nums = [1,2,5,2,3], target = 5", + "expected_output": "[4]", + "explanation": "After sorting, nums is [1,2,2,3,5].\nThe index where nums[i] == 5 is 4." + } + ] + }, + { + "_id": "66f925defdfb8e1665720ed6", + "questionid": 1035, + "title": "K Radius Subarray Averages", + "slug": "k-radius-subarray-averages", + "description": "You are given a 0-indexed array nums of n integers, and an integer k. The k-radius average for a subarray of nums centered at some index i with the radius k is the average of all elements in nums between the indices i - k and i + k (inclusive). If there are less than k elements before or after the index i, then the k-radius average is -1. Build and return an array avgs of length n where avgs[i] is the k-radius average for the subarray centered at index i. The average of x elements is the sum of the x elements divided by x, using integer division. The integer division truncates toward zero, which means losing its fractional part. ", + "category": [ + "Array", + "Sliding Window" + ], + "complexity": "Medium", + "successrate": 40.6, + "totalsubmissions": 34633, + "totalaccepted": 14048, + "likes": 260, + "dislikes": 10, + "hints": "To calculate the average of a subarray, you need the sum and the K. K is already given. How could you quickly calculate the sum of a subarray? Use the Prefix Sums method to calculate the subarray sums. It is possible that the sum of all the elements does not fit in a 32-bit integer type. Be sure to use a 64-bit integer type for the prefix sum array.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [7,4,3,9,1,8,5,2,6], k = 3", + "expected_output": "[-1,-1,-1,5,4,4,-1,-1,-1]", + "explanation": "- avg[0], avg[1], and avg[2] are -1 because there are less than k elements before each index.\n- The sum of the subarray centered at index 3 with radius 3 is: 7 + 4 + 3 + 9 + 1 + 8 + 5 = 37.\n Using integer division, avg[3] = 37 / 7 = 5.\n- For the subarray centered at index 4, avg[4] = (4 + 3 + 9 + 1 + 8 + 5 + 2) / 7 = 4.\n- For the subarray centered at index 5, avg[5] = (3 + 9 + 1 + 8 + 5 + 2 + 6) / 7 = 4.\n- avg[6], avg[7], and avg[8] are -1 because there are less than k elements after each index." + }, + { + "example_num": 2, + "expected_input": "nums = [100000], k = 0", + "expected_output": "[100000]", + "explanation": "- The sum of the subarray centered at index 0 with radius 0 is: 100000.\n avg[0] = 100000 / 1 = 100000." + }, + { + "example_num": 3, + "expected_input": "nums = [8], k = 100000", + "expected_output": "[-1]", + "explanation": "- avg[0] is -1 because there are less than k elements before and after index 0." + } + ] + }, + { + "_id": "66f925defdfb8e1665720edd", + "questionid": 1042, + "title": "Maximum Fruits Harvested After at Most K Steps", + "slug": "maximum-fruits-harvested-after-at-most-k-steps", + "description": "Fruits are available at some positions on an infinite x-axis. You are given a 2D integer array fruits where fruits[i] = [positioni, amounti] depicts amounti fruits at the position positioni. fruits is already sorted by positioni in ascending order, and each positioni is unique. You are also given an integer startPos and an integer k. Initially, you are at the position startPos. From any position, you can either walk to the left or right. It takes one step to move one unit on the x-axis, and you can walk at most k steps in total. For every position you reach, you harvest all the fruits at that position, and the fruits will disappear from that position. Return the maximum total number of fruits you can harvest. ", + "category": [ + "Array", + "Binary Search", + "Sliding Window", + "Prefix Sum" + ], + "complexity": "Hard", + "successrate": 35.1, + "totalsubmissions": 17447, + "totalaccepted": 6129, + "likes": 253, + "dislikes": 15, + "hints": "Does an optimal path have very few patterns? For example, could a path that goes left, turns and goes right, then turns again and goes left be any better than a path that simply goes left, turns, and goes right? The optimal path turns at most once. That is, the optimal path is one of these: to go left only; to go right only; to go left, turn and go right; or to go right, turn and go left. Moving x steps left then k-x steps right gives you a range of positions that you can reach. Use prefix sums to get the sum of all fruits for each possible range. Use a similar strategy for all the paths that go right, then turn and go left.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "fruits = [[2,8],[6,3],[8,6]], startPos = 5, k = 4", + "expected_output": "9", + "explanation": "The optimal way is to:\n- Move right to position 6 and harvest 3 fruits\n- Move right to position 8 and harvest 6 fruits\nYou moved 3 steps and harvested 3 + 6 = 9 fruits in total." + }, + { + "example_num": 2, + "expected_input": "fruits = [[0,9],[4,1],[5,7],[6,2],[7,4],[10,9]], startPos = 5, k = 4", + "expected_output": "14", + "explanation": "You can move at most k = 4 steps, so you cannot reach position 0 nor 10.\nThe optimal way is to:\n- Harvest the 7 fruits at the starting position 5\n- Move left to position 4 and harvest 1 fruit\n- Move right to position 6 and harvest 2 fruits\n- Move right to position 7 and harvest 4 fruits\nYou moved 1 + 3 = 4 steps and harvested 7 + 1 + 2 + 4 = 14 fruits in total." + }, + { + "example_num": 3, + "expected_input": "fruits = [[0,3],[6,4],[8,5]], startPos = 3, k = 2", + "expected_output": "0", + "explanation": "You can move at most k = 2 steps and cannot reach any position with fruits." + } + ] + }, + { + "_id": "66f925defdfb8e1665720ede", + "questionid": 1043, + "title": "Find First Palindromic String in the Array", + "slug": "find-first-palindromic-string-in-the-array", + "description": "Given an array of strings words, return the first palindromic string in the array. If there is no such string, return an empty string \"\". A string is palindromic if it reads the same forward and backward. ", + "category": [ + "Array", + "Two Pointers", + "String" + ], + "complexity": "Easy", + "successrate": 79.5, + "totalsubmissions": 50602, + "totalaccepted": 40250, + "likes": 347, + "dislikes": 12, + "hints": "Iterate through the elements in order. As soon as the current element is a palindrome, return it. To check if an element is a palindrome, can you reverse the string?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "words = ["abc","car","ada","racecar","cool"]", + "expected_output": ""ada"", + "explanation": "The first string that is palindromic is "ada".\nNote that "racecar" is also palindromic, but it is not the first." + }, + { + "example_num": 2, + "expected_input": "words = ["notapalindrome","racecar"]", + "expected_output": ""racecar"", + "explanation": "The first and only string that is palindromic is "racecar"." + }, + { + "example_num": 3, + "expected_input": "words = ["def","ghi"]", + "expected_output": """", + "explanation": "There are no palindromic strings, so the empty string is returned." + } + ] + }, + { + "_id": "66f925defdfb8e1665720ee7", + "questionid": 1052, + "title": "Maximum Employees to Be Invited to a Meeting", + "slug": "maximum-employees-to-be-invited-to-a-meeting", + "description": "A company is organizing a meeting and has a list of n employees, waiting to be invited. They have arranged for a large circular table, capable of seating any number of employees. The employees are numbered from 0 to n - 1. Each employee has a favorite person and they will attend the meeting only if they can sit next to their favorite person at the table. The favorite person of an employee is not themself. Given a 0-indexed integer array favorite, where favorite[i] denotes the favorite person of the ith employee, return the maximum number of employees that can be invited to the meeting. ", + "category": [ + "Depth-First Search", + "Graph", + "Topological Sort" + ], + "complexity": "Hard", + "successrate": 29.9, + "totalsubmissions": 15292, + "totalaccepted": 4578, + "likes": 471, + "dislikes": 6, + "hints": "From the given array favorite, create a graph where for every index i, there is a directed edge from favorite[i] to i. The graph will be a combination of cycles and chains of acyclic edges. Now, what are the ways in which we can choose employees to sit at the table? The first way by which we can choose employees is by selecting a cycle of the graph. It can be proven that in this case, the employees that do not lie in the cycle can never be seated at the table. The second way is by combining acyclic chains. At most two chains can be combined by a cycle of length 2, where each chain ends on one of the employees in the cycle.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "favorite = [2,2,1,2]", + "expected_output": "3", + "explanation": "The above figure shows how the company can invite employees 0, 1, and 2, and seat them at the round table.\nAll employees cannot be invited because employee 2 cannot sit beside employees 0, 1, and 3, simultaneously.\nNote that the company can also invite employees 1, 2, and 3, and give them their desired seats.\nThe maximum number of employees that can be invited to the meeting is 3." + }, + { + "example_num": 2, + "expected_input": "favorite = [1,2,0]", + "expected_output": "3", + "explanation": "Each employee is the favorite person of at least one other employee, and the only way the company can invite them is if they invite every employee.\nThe seating arrangement will be the same as that in the figure given in example 1:\n- Employee 0 will sit between employees 2 and 1.\n- Employee 1 will sit between employees 0 and 2.\n- Employee 2 will sit between employees 1 and 0.\nThe maximum number of employees that can be invited to the meeting is 3." + }, + { + "example_num": 3, + "expected_input": "favorite = [3,0,1,4,1]", + "expected_output": "4", + "explanation": "The above figure shows how the company will invite employees 0, 1, 3, and 4, and seat them at the round table.\nEmployee 2 cannot be invited because the two spots next to their favorite employee 1 are taken.\nSo the company leaves them out of the meeting.\nThe maximum number of employees that can be invited to the meeting is 4." + } + ] + }, + { + "_id": "66f925defdfb8e1665720ee8", + "questionid": 1053, + "title": "Minimum Cost of Buying Candies With Discount", + "slug": "minimum-cost-of-buying-candies-with-discount", + "description": "A shop is selling candies at a discount. For every two candies sold, the shop gives a third candy for free. The customer can choose any candy to take away for free as long as the cost of the chosen candy is less than or equal to the minimum cost of the two candies bought. Given a 0-indexed integer array cost, where cost[i] denotes the cost of the ith candy, return the minimum cost of buying all the candies. ", + "category": [ + "Array", + "Greedy", + "Sorting" + ], + "complexity": "Easy", + "successrate": 60.6, + "totalsubmissions": 34300, + "totalaccepted": 20777, + "likes": 224, + "dislikes": 8, + "hints": "If we consider costs from high to low, what is the maximum cost of a single candy that we can get for free? How can we generalize this approach to maximize the costs of the candies we get for free? Can €œsorting€ the array help us find the minimum cost? If we consider costs from high to low, what is the maximum cost of a single candy that we can get for free? How can we generalize this approach to maximize the costs of the candies we get for free? Can €œsorting€ the array help us find the minimum cost?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "cost = [1,2,3]", + "expected_output": "5", + "explanation": "We buy the candies with costs 2 and 3, and take the candy with cost 1 for free.\nThe total cost of buying all candies is 2 + 3 = 5. This is the only way we can buy the candies.\nNote that we cannot buy candies with costs 1 and 3, and then take the candy with cost 2 for free.\nThe cost of the free candy has to be less than or equal to the minimum cost of the purchased candies." + }, + { + "example_num": 2, + "expected_input": "cost = [6,5,7,9,2,2]", + "expected_output": "23", + "explanation": "The way in which we can get the minimum cost is described below:\n- Buy candies with costs 9 and 7\n- Take the candy with cost 6 for free\n- We buy candies with costs 5 and 2\n- Take the last remaining candy with cost 2 for free\nHence, the minimum cost to buy all candies is 9 + 7 + 5 + 2 = 23." + }, + { + "example_num": 3, + "expected_input": "cost = [5,5]", + "expected_output": "10", + "explanation": "Since there are only 2 candies, we buy both of them. There is not a third candy we can take for free.\nHence, the minimum cost to buy all candies is 5 + 5 = 10." + } + ] + }, + { + "_id": "66f925defdfb8e1665720efa", + "questionid": 1071, + "title": "Minimum Number of Steps to Make Two Strings Anagram II", + "slug": "minimum-number-of-steps-to-make-two-strings-anagram-ii", + "description": "You are given two strings s and t. In one step, you can append any character to either s or t. Return the minimum number of steps to make s and t anagrams of each other. An anagram of a string is a string that contains the same characters with a different (or the same) ordering. ", + "category": [ + "Hash Table", + "String", + "Counting" + ], + "complexity": "Medium", + "successrate": 70.4, + "totalsubmissions": 29879, + "totalaccepted": 21044, + "likes": 223, + "dislikes": 4, + "hints": "Notice that for anagrams, the order of the letters is irrelevant. For each letter, we can count its frequency in s and t. For each letter, its contribution to the answer is the absolute difference between its frequency in s and t.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "leetcode", t = "coats"", + "expected_output": "7", + "explanation": "- In 2 steps, we can append the letters in "as" onto s = "leetcode", forming s = "leetcodeas".\n- In 5 steps, we can append the letters in "leede" onto t = "coats", forming t = "coatsleede".\n"leetcodeas" and "coatsleede" are now anagrams of each other.\nWe used a total of 2 + 5 = 7 steps.\nIt can be shown that there is no way to make them anagrams of each other with less than 7 steps." + }, + { + "example_num": 2, + "expected_input": "s = "night", t = "thing"", + "expected_output": "0", + "explanation": "The given strings are already anagrams of each other. Thus, we do not need any further steps." + } + ] + }, + { + "_id": "66f925defdfb8e1665720eff", + "questionid": 1076, + "title": "Construct String With Repeat Limit", + "slug": "construct-string-with-repeat-limit", + "description": "You are given a string s and an integer repeatLimit. Construct a new string repeatLimitedString using the characters of s such that no letter appears more than repeatLimit times in a row. You do not have to use all characters from s. Return the lexicographically largest repeatLimitedString possible. A string a is lexicographically larger than a string b if in the first position where a and b differ, string a has a letter that appears later in the alphabet than the corresponding letter in b. If the first min(a.length, b.length) characters do not differ, then the longer string is the lexicographically larger one. ", + "category": [ + "String", + "Greedy", + "Heap (Priority Queue)", + "Counting" + ], + "complexity": "Medium", + "successrate": 51, + "totalsubmissions": 24894, + "totalaccepted": 12699, + "likes": 367, + "dislikes": 20, + "hints": "Start constructing the string in descending order of characters. When repeatLimit is reached, pick the next largest character.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "cczazcc", repeatLimit = 3", + "expected_output": ""zzcccac"", + "explanation": "We use all of the characters from s to construct the repeatLimitedString "zzcccac".\nThe letter 'a' appears at most 1 time in a row.\nThe letter 'c' appears at most 3 times in a row.\nThe letter 'z' appears at most 2 times in a row.\nHence, no letter appears more than repeatLimit times in a row and the string is a valid repeatLimitedString.\nThe string is the lexicographically largest repeatLimitedString possible so we return "zzcccac".\nNote that the string "zzcccca" is lexicographically larger but the letter 'c' appears more than 3 times in a row, so it is not a valid repeatLimitedString." + }, + { + "example_num": 2, + "expected_input": "s = "aababab", repeatLimit = 2", + "expected_output": ""bbabaa"", + "explanation": "We use only some of the characters from s to construct the repeatLimitedString "bbabaa". \nThe letter 'a' appears at most 2 times in a row.\nThe letter 'b' appears at most 2 times in a row.\nHence, no letter appears more than repeatLimit times in a row and the string is a valid repeatLimitedString.\nThe string is the lexicographically largest repeatLimitedString possible so we return "bbabaa".\nNote that the string "bbabaaa" is lexicographically larger but the letter 'a' appears more than 2 times in a row, so it is not a valid repeatLimitedString." + } + ] + }, + { + "_id": "66f925defdfb8e1665720f03", + "questionid": 1080, + "title": "Minimum Operations to Halve Array Sum", + "slug": "minimum-operations-to-halve-array-sum", + "description": "You are given an array nums of positive integers. In one operation, you can choose any number from nums and reduce it to exactly half the number. (Note that you may choose this reduced number in future operations.) Return the minimum number of operations to reduce the sum of nums by at least half. ", + "category": [ + "Array", + "Greedy", + "Heap (Priority Queue)" + ], + "complexity": "Medium", + "successrate": 43.3, + "totalsubmissions": 25848, + "totalaccepted": 11199, + "likes": 200, + "dislikes": 9, + "hints": "It is always optimal to halve the largest element. What data structure allows for an efficient query of the maximum element? Use a heap or priority queue to maintain the current elements.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [5,19,8,1]", + "expected_output": "3", + "explanation": "The initial sum of nums is equal to 5 + 19 + 8 + 1 = 33.\nThe following is one of the ways to reduce the sum by at least half:\nPick the number 19 and reduce it to 9.5.\nPick the number 9.5 and reduce it to 4.75.\nPick the number 8 and reduce it to 4.\nThe final array is [5, 4.75, 4, 1] with a total sum of 5 + 4.75 + 4 + 1 = 14.75. \nThe sum of nums has been reduced by 33 - 14.75 = 18.25, which is at least half of the initial sum, 18.25 >= 33/2 = 16.5.\nOverall, 3 operations were used so we return 3.\nIt can be shown that we cannot reduce the sum by at least half in less than 3 operations." + }, + { + "example_num": 2, + "expected_input": "nums = [3,8,20]", + "expected_output": "3", + "explanation": "The initial sum of nums is equal to 3 + 8 + 20 = 31.\nThe following is one of the ways to reduce the sum by at least half:\nPick the number 20 and reduce it to 10.\nPick the number 10 and reduce it to 5.\nPick the number 3 and reduce it to 1.5.\nThe final array is [1.5, 8, 5] with a total sum of 1.5 + 8 + 5 = 14.5. \nThe sum of nums has been reduced by 31 - 14.5 = 16.5, which is at least half of the initial sum, 16.5 >= 31/2 = 15.5.\nOverall, 3 operations were used so we return 3.\nIt can be shown that we cannot reduce the sum by at least half in less than 3 operations." + } + ] + }, + { + "_id": "66f925defdfb8e1665720f08", + "questionid": 1085, + "title": "Minimum Bit Flips to Convert Number", + "slug": "minimum-bit-flips-to-convert-number", + "description": "A bit flip of a number x is choosing a bit in the binary representation of x and flipping it from either 0 to 1 or 1 to 0. Given two integers start and goal, return the minimum number of bit flips to convert start to goal. ", + "category": [ + "Bit Manipulation" + ], + "complexity": "Easy", + "successrate": 81.1, + "totalsubmissions": 17915, + "totalaccepted": 14525, + "likes": 111, + "dislikes": 2, + "hints": "If the value of a bit in start and goal differ, then we need to flip that bit. Consider using the XOR operation to determine which bits need a bit flip.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "start = 10, goal = 7", + "expected_output": "3", + "explanation": "The binary representation of 10 and 7 are 1010 and 0111 respectively. We can convert 10 to 7 in 3 steps:\n- Flip the first bit from the right: 1010 -> 1011.\n- Flip the third bit from the right: 1011 -> 1111.\n- Flip the fourth bit from the right: 1111 -> 0111.\nIt can be shown we cannot convert 10 to 7 in less than 3 steps. Hence, we return 3." + }, + { + "example_num": 2, + "expected_input": "start = 3, goal = 4", + "expected_output": "3", + "explanation": "The binary representation of 3 and 4 are 011 and 100 respectively. We can convert 3 to 4 in 3 steps:\n- Flip the first bit from the right: 011 -> 010.\n- Flip the second bit from the right: 010 -> 000.\n- Flip the third bit from the right: 000 -> 100.\nIt can be shown we cannot convert 3 to 4 in less than 3 steps. Hence, we return 3." + } + ] + }, + { + "_id": "66f925defdfb8e1665720f0c", + "questionid": 1089, + "title": "Maximum Product After K Increments", + "slug": "maximum-product-after-k-increments", + "description": "You are given an array of non-negative integers nums and an integer k. In one operation, you may choose any element from nums and increment it by 1. Return the maximum product of nums after at most k operations. Since the answer may be very large, return it modulo 109 + 7. Note that you should maximize the product before taking the modulo. ", + "category": [ + "Array", + "Greedy", + "Heap (Priority Queue)" + ], + "complexity": "Medium", + "successrate": 39, + "totalsubmissions": 32222, + "totalaccepted": 12569, + "likes": 248, + "dislikes": 23, + "hints": "If you can increment only once, which number should you increment? We should always prioritize the smallest number. What kind of data structure could we use? Use a min heap to hold all the numbers. Each time we do an operation, replace the top of the heap x by x + 1.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [0,4], k = 5", + "expected_output": "20", + "explanation": "Increment the first number 5 times.\nNow nums = [5, 4], with a product of 5 * 4 = 20.\nIt can be shown that 20 is maximum product possible, so we return 20.\nNote that there may be other ways to increment nums to have the maximum product." + }, + { + "example_num": 2, + "expected_input": "nums = [6,3,3,2], k = 2", + "expected_output": "216", + "explanation": "Increment the second number 1 time and increment the fourth number 1 time.\nNow nums = [6, 4, 3, 3], with a product of 6 * 4 * 3 * 3 = 216.\nIt can be shown that 216 is maximum product possible, so we return 216.\nNote that there may be other ways to increment nums to have the maximum product." + } + ] + } +] \ No newline at end of file diff --git a/backend/question/tools/qn_full_with_soln.json b/backend/question/tools/qn_full_with_soln.json new file mode 100644 index 0000000000..03c23479ff --- /dev/null +++ b/backend/question/tools/qn_full_with_soln.json @@ -0,0 +1,40681 @@ +[ + { + "_id": "66f925ddfdfb8e1665720acc", + "questionid": 1, + "title": "Two Sum", + "slug": "two-sum", + "description": "Given an array of integers nums\u00a0and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not use the same element twice. You can return the answer in any order. ", + "category": [ + "Array", + "Hash Table" + ], + "complexity": "Easy", + "successrate": 48.5, + "totalsubmissions": 13207990, + "totalaccepted": 6403821, + "likes": 31242, + "dislikes": 988, + "hints": "A really brute force way would be to search for all possible pairs of numbers but that would be too slow. Again, it's best to try out brute force solutions for just for completeness. It is from these brute force solutions that you can come up with optimizations. So, if we fix one of the numbers, say x, we have to scan the entire array to find the next number y which is value - x where value is the input parameter. Can we change our array somehow so that this search becomes faster? The second train of thought is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [2,7,11,15], target = 9", + "expected_output": "[0,1]", + "explanation": "Because nums[0] + nums[1] == 9, we return [0, 1]." + }, + { + "example_num": 2, + "expected_input": "nums = [3,2,4], target = 6", + "expected_output": "[1,2]", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "nums = [3,3], target = 6", + "expected_output": "[0,1]", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} nums\n * @param {number} target\n * @return {number[]}\n */\nconst twoSum = function(nums, target) {\n const myObject = {};\n for (let i = 0; i < nums.length; i++) {\n const complement = target - nums[i];\n if (myObject.hasOwnProperty(complement)) {\n return [myObject[complement], i];\n }\n myObject[nums[i]] = i;\n }\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720acf", + "questionid": 4, + "title": "Median of Two Sorted Arrays", + "slug": "median-of-two-sorted-arrays", + "description": "Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)). ", + "category": [ + "Array", + "Binary Search", + "Divide and Conquer" + ], + "complexity": "Hard", + "successrate": 34, + "totalsubmissions": 3941694, + "totalaccepted": 1340565, + "likes": 15987, + "dislikes": 1964, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums1 = [1,3], nums2 = [2]", + "expected_output": "2.00000", + "explanation": "merged array = [1,2,3] and median is 2." + }, + { + "example_num": 2, + "expected_input": "nums1 = [1,2], nums2 = [3,4]", + "expected_output": "2.50000", + "explanation": "merged array = [1,2,3,4] and median is (2 + 3) / 2 = 2.5." + } + ], + "solution": "/**\n * @param {number[]} nums1\n * @param {number[]} nums2\n * @return {number}\n */\nconst findMedianSortedArrays = function(nums1, nums2) {\n if(nums1.length > nums2.length) return findMedianSortedArrays(nums2, nums1)\n const m = nums1.length, n = nums2.length\n let low = 0, high = m\n while(low <= high) {\n \n const px = Math.floor((low + high) / 2)\n const py = Math.floor(( m + n + 1 ) / 2) - px\n \n const maxLeft1 = px === 0 ? -Infinity : nums1[px - 1]\n const minRight1 = px === m ? Infinity : nums1[px]\n \n const maxLeft2 = py === 0 ? -Infinity : nums2[py - 1]\n const minRight2 = py === n ? Infinity : nums2[py]\n \n if(maxLeft1 <= minRight2 && maxLeft2 <= minRight1) {\n if((m + n) % 2 === 0) {\n return (Math.max(maxLeft1, maxLeft2) + Math.min(minRight1, minRight2)) / 2\n } else {\n return Math.max(maxLeft1, maxLeft2)\n }\n } else if(maxLeft1 > minRight2) {\n high = px - 1 \n } else {\n low = px + 1\n }\n \n }\n};\n\n// another\n\n/**\n * @param {number[]} A\n * @param {number[]} B\n * @return {number}\n */\n\nconst findMedianSortedArrays = function(A, B) {\n let m = A.length,\n n = B.length;\n\n if (m > n) {\n return findMedianSortedArrays(B, A);\n }\n\n let imin = 0,\n imax = m,\n i,\n j;\n while (imin <= imax) {\n i = (imin + imax) >> 1;\n j = ((m + n + 1) >> 1) - i;\n if (j > 0 && i < m && B[j - 1] > A[i]) {\n imin = i + 1;\n } else if (i > 0 && j < n && A[i - 1] > B[j]) {\n imax = i - 1;\n } else {\n if (i === 0) {\n num1 = B[j - 1];\n } else if (j === 0) {\n num1 = A[i - 1];\n } else {\n num1 = Math.max(A[i - 1], B[j - 1]);\n }\n\n if ((m + n) & 1) {\n return num1;\n }\n\n if (i === m) {\n num2 = B[j];\n } else if (j === n) {\n num2 = A[i];\n } else {\n num2 = Math.min(A[i], B[j]);\n }\n return (num1 + num2) / 2.0;\n }\n }\n};\n\n// another\n\n/**\n * @param {number[]} nums1\n * @param {number[]} nums2\n * @return {number}\n */\nconst findMedianSortedArrays = function (nums1, nums2) {\n if (nums1.length > nums2.length) {\n return findMedianSortedArrays(nums2, nums1)\n }\n const x = nums1.length\n const y = nums2.length\n\n let low = 0\n let high = x\n\n while (low <= high) {\n const partX = Math.floor((low + high) / 2)\n const partY = Math.floor((x + y + 1) / 2) - partX\n\n const maxX = partX === 0 ? Number.NEGATIVE_INFINITY : nums1[partX - 1]\n const maxY = partY === 0 ? Number.NEGATIVE_INFINITY : nums2[partY - 1]\n\n const minX =\n partX === nums1.length ? Number.POSITIVE_INFINITY : nums1[partX]\n const minY =\n partY === nums2.length ? Number.POSITIVE_INFINITY : nums2[partY]\n\n if (maxX <= minY && maxY <= minX) {\n const lowMax = Math.max(maxX, maxY)\n\n if ((x + y) % 2 == 1) {\n return Math.max(maxX, maxY)\n } else {\n return (Math.max(maxX, maxY) + Math.min(minX, minY)) / 2\n }\n } else if (maxX < minY) {\n low = partX + 1\n } else {\n high = partX - 1\n }\n }\n}\n\n\n" + }, + { + "_id": "66f925ddfdfb8e1665720ad2", + "questionid": 7, + "title": "Palindrome Number", + "slug": "palindrome-number", + "description": "Given an integer x, return true if x is palindrome integer. An integer is a palindrome when it reads the same backward as forward. ", + "category": [ + "Math" + ], + "complexity": "Easy", + "successrate": 52.3, + "totalsubmissions": 3823313, + "totalaccepted": 2000757, + "likes": 5593, + "dislikes": 2094, + "hints": "Beware of overflow when you reverse the integer.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "x = 121", + "expected_output": "true", + "explanation": "121 reads as 121 from left to right and from right to left." + }, + { + "example_num": 2, + "expected_input": "x = -121", + "expected_output": "false", + "explanation": "From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome." + }, + { + "example_num": 3, + "expected_input": "x = 10", + "expected_output": "false", + "explanation": "Reads 01 from right to left. Therefore it is not a palindrome." + } + ], + "solution": "/**\n * @param {number} x\n * @return {boolean}\n */\nconst isPalindrome = function(x) {\n if (x < 0) return false;\n const rev = reverseNum(x);\n return x === rev;\n};\n\nfunction reverseNum(num) {\n let n = num;\n let rev = 0;\n let dig;\n while (num > 0) {\n dig = num % 10;\n rev = rev * 10 + dig;\n num = Math.floor(num / 10);\n }\n return rev;\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720ad6", + "questionid": 11, + "title": "3Sum Closest", + "slug": "3sum-closest", + "description": "Given an integer array nums of length n and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution. ", + "category": [ + "Array", + "Two Pointers", + "Sorting" + ], + "complexity": "Medium", + "successrate": 47.1, + "totalsubmissions": 1665933, + "totalaccepted": 784188, + "likes": 5673, + "dislikes": 242, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [-1,2,1,-4], target = 1", + "expected_output": "2", + "explanation": "The sum that is closest to the target is 2. (-1 + 2 + 1 = 2)." + }, + { + "example_num": 2, + "expected_input": "nums = [0,0,0], target = 1", + "expected_output": "0", + "explanation": "The sum that is closest to the target is 0. (0 + 0 + 0 = 0)." + } + ], + "solution": "/**\n * @param {number[]} nums\n * @param {number} target\n * @return {number}\n */\nconst threeSumClosest = function(nums, target) {\n let n = nums.length, {abs, min, max} = Math\n let res = nums[0] + nums[1] + nums[2]\n nums.sort((a, b) => a - b)\n for(let i = 0; i < n - 2; i++) {\n let e = nums[i]\n let l = i + 1, r = n - 1\n if(i > 0 && nums[i] === nums[i - 1]) continue\n while(l < r) {\n const tmp = e + nums[l] + nums[r]\n if(abs(tmp - target) < abs(res - target)) {\n res = tmp\n }\n if(tmp > target) r--\n else if (tmp < target) l++\n else return tmp\n }\n }\n \n \n return res\n};\n\n// another\n\n/**\n * @param {number[]} nums\n * @param {number} target\n * @return {number}\n */\nconst threeSumClosest = function(nums, target) {\n const nums = nums.sort((a, b) => a - b);\n let result;\n let lo;\n let hi;\n let sum;\n result = nums[0] + nums[1] + nums[nums.length - 1];\n for (let i = 0; i < nums.length - 2; i++) {\n lo = i + 1;\n hi = nums.length - 1;\n while (lo < hi) {\n sum = nums[i] + nums[lo] + nums[hi];\n if (sum < target) {\n while (lo < hi && nums[lo] === nums[lo + 1]) {\n lo += 1;\n }\n lo += 1;\n } else if (sum > target) {\n while (lo < hi && nums[hi] === nums[hi - 1]) {\n hi -= 1;\n }\n hi -= 1;\n } else {\n return sum;\n }\n\n if (Math.abs(target - sum) < Math.abs(target - result)) {\n result = sum;\n }\n }\n }\n\n return result;\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720ada", + "questionid": 15, + "title": "Generate Parentheses", + "slug": "generate-parentheses", + "description": "Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. ", + "category": [ + "String", + "Dynamic Programming", + "Backtracking" + ], + "complexity": "Medium", + "successrate": 69.9, + "totalsubmissions": 1475969, + "totalaccepted": 1032134, + "likes": 12456, + "dislikes": 483, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 3", + "expected_output": "[\"((()))\",\"(()())\",\"(())()\",\"()(())\",\"()()()\"]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "n = 1", + "expected_output": "[\"()\"]", + "explanation": "" + } + ], + "solution": "/**\n * @param {number} n\n * @return {string[]}\n */\nconst generateParenthesis = function(n) {\n const res = [];\n backtrack(res, \"\", 0, 0, n);\n return res;\n};\nfunction backtrack(arr, cur, open, close, max) {\n if (cur.length === max * 2) {\n arr.push(cur);\n return;\n }\n if (open < max) backtrack(arr, cur + \"(\", open + 1, close, max);\n if (close < open) backtrack(arr, cur + \")\", open, close + 1, max);\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720ae1", + "questionid": 22, + "title": "Search in Rotated Sorted Array", + "slug": "search-in-rotated-sorted-array", + "description": "There is an integer array nums sorted in ascending order (with distinct values). Prior to being passed to your function, nums is possibly rotated at an unknown pivot index k (1 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed). For example, [0,1,2,4,5,6,7] might be rotated at pivot index 3 and become [4,5,6,7,0,1,2]. Given the array nums after the possible rotation and an integer target, return the index of target if it is in nums, or -1 if it is not in nums. You must write an algorithm with O(log n) runtime complexity. ", + "category": [ + "Array", + "Binary Search" + ], + "complexity": "Medium", + "successrate": 37.7, + "totalsubmissions": 3795739, + "totalaccepted": 1431906, + "likes": 13769, + "dislikes": 879, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [4,5,6,7,0,1,2], target = 0", + "expected_output": "4", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "nums = [4,5,6,7,0,1,2], target = 3", + "expected_output": "-1", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "nums = [1], target = 0", + "expected_output": "-1", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} nums\n * @param {number} target\n * @return {number}\n */\nconst search = function(nums, target) {\n const len = nums.length\n let r = false\n let ridx = 0\n if(len === 0) return -1\n if(nums[0] === target) return 0\n for(let i = 1; i < len; i++) {\n if(nums[i] === target) return i\n if(nums[i] < nums[i - 1]) {\n r = true\n ridx = i\n break\n }\n }\n \n if(r === true) {\n for(let i = len - 1; i >= ridx; i--) {\n if(nums[i] === target) return i\n }\n }\n \n return -1\n};\n\n// another\n\nconst search = function(nums, target) {\n const len = nums.length\n for(let i = 0; nums[i] <= target; i++){\n if(nums[i] === target){\n return i\n }\n }\n for(let j = len - 1; nums[j] >= target; j--){\n if(nums[j] === target){\n return j\n }\n }\n return -1 \n};\n\n// another \nconst search = function(nums, target) {\n let low = 0\n let high = nums.length - 1\n while (low <= high) {\n let mid = low + ((high - low) >> 1)\n if (nums[mid] === target) return mid\n\n if (nums[low] <= nums[mid] ) {\n if (target < nums[mid] && target >= nums[low]) {\n high = mid - 1\n } else {\n low = mid + 1\n }\n } else {\n if (target > nums[mid] && target <= nums[high]) {\n low = mid + 1\n } else {\n high = mid - 1\n }\n }\n\n }\n return -1\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720ae2", + "questionid": 23, + "title": "Find First and Last Position of Element in Sorted Array", + "slug": "find-first-and-last-position-of-element-in-sorted-array", + "description": "Given an array of integers nums sorted in non-decreasing order, find the starting and ending position of a given target value. If target is not found in the array, return [-1, -1]. You must\u00a0write an algorithm with\u00a0O(log n) runtime complexity. ", + "category": [ + "Array", + "Binary Search" + ], + "complexity": "Medium", + "successrate": 40, + "totalsubmissions": 2648073, + "totalaccepted": 1058127, + "likes": 10191, + "dislikes": 284, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [5,7,7,8,8,10], target = 8", + "expected_output": "[3,4]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "nums = [5,7,7,8,8,10], target = 6", + "expected_output": "[-1,-1]", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "nums = [], target = 0", + "expected_output": "[-1,-1]", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} nums\n * @param {number} target\n * @return {number[]}\n */\nconst searchRange = function(nums, target) {\n let len = nums.length;\n let start = 0;\n let end = len - 1;\n let res = [];\n let idx;\n while (start <= end) {\n let mid = Math.floor((start + end) / 2);\n if (target === nums[mid]) {\n idx = mid;\n break;\n } else if (target < nums[mid]) end = mid - 1;\n else start = mid + 1;\n }\n if (idx == null) return [-1, -1];\n let li = idx;\n let hi = idx;\n while (nums[li - 1] === target) {\n li--;\n }\n while (nums[hi + 1] === target) {\n hi++;\n }\n res = [li, hi];\n return res;\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720ae4", + "questionid": 25, + "title": "Combination Sum", + "slug": "combination-sum", + "description": "Given an array of distinct integers candidates and a target integer target, return a list of all unique combinations of candidates where the chosen numbers sum to target. You may return the combinations in any order. The same number may be chosen from candidates an unlimited number of times. Two combinations are unique if the frequency of at least one of the chosen numbers is different. It is guaranteed that the number of unique combinations that sum up to target is less than 150 combinations for the given input. ", + "category": [ + "Array", + "Backtracking" + ], + "complexity": "Medium", + "successrate": 65.3, + "totalsubmissions": 1614657, + "totalaccepted": 1054189, + "likes": 10510, + "dislikes": 224, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "candidates = [2,3,6,7], target = 7", + "expected_output": "[[2,2,3],[7]]", + "explanation": "2 and 3 are candidates, and 2 + 2 + 3 = 7. Note that 2 can be used multiple times.\n7 is a candidate, and 7 = 7.\nThese are the only two combinations." + }, + { + "example_num": 2, + "expected_input": "candidates = [2,3,5], target = 8", + "expected_output": "[[2,2,2,2],[2,3,3],[3,5]]", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "candidates = [2], target = 1", + "expected_output": "[]", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} candidates\n * @param {number} target\n * @return {number[][]}\n */\nconst combinationSum = function(candidates, target) {\n candidates.sort((a, b) => a - b);\n const res = [];\n bt(candidates, target, res, [], 0);\n return res;\n};\n\nfunction bt(candidates, target, res, combination, start) {\n if (target === 0) {\n res.push(combination.slice(0));\n return;\n }\n for (let i = start; i < candidates.length && target >= candidates[i]; i++) {\n combination.push(candidates[i]);\n bt(candidates, target - candidates[i], res, combination, i);\n combination.pop();\n }\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720ae5", + "questionid": 26, + "title": "First Missing Positive", + "slug": "first-missing-positive", + "description": "Given an unsorted integer array nums, return the smallest missing positive integer. You must implement an algorithm that runs in O(n) time and uses constant extra space. ", + "category": [ + "Array", + "Hash Table" + ], + "complexity": "Hard", + "successrate": 35.9, + "totalsubmissions": 1845590, + "totalaccepted": 662571, + "likes": 9261, + "dislikes": 1303, + "hints": "Think about how you would solve the problem in non-constant space. Can you apply that logic to the existing space? We don't care about duplicates or non-positive integers Remember that O(2n) = O(n)", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,2,0]", + "expected_output": "3", + "explanation": "The numbers in the range [1,2] are all in the array." + }, + { + "example_num": 2, + "expected_input": "nums = [3,4,-1,1]", + "expected_output": "2", + "explanation": "1 is in the array but 2 is missing." + }, + { + "example_num": 3, + "expected_input": "nums = [7,8,9,11,12]", + "expected_output": "1", + "explanation": "The smallest positive integer 1 is missing." + } + ], + "solution": "/**\n * @param {number[]} nums\n * @return {number}\n */\nconst firstMissingPositive = function(nums) {\n if(nums.length === 0) return 1\n const arr = []\n let max = Number.MIN_SAFE_INTEGER\n for(let i = 0, len = nums.length; i < len; i++) {\n if(nums[i] > 0) arr[nums[i]] = nums[i]\n if(nums[i] > max) max = nums[i]\n }\n for(let i = 1; i < max; i++) {\n if(arr[i] == null) return i\n }\n return max < 0 ? 1 : max + 1\n};\n\n// another\n\n/**\n * @param {number[]} nums\n * @return {number}\n */\nfunction firstMissingPositive(nums) {\n const n = nums.length\n for (let i = 0; i < n; i++) {\n while (nums[i] > 0 && nums[i] <= n && nums[nums[i] - 1] !== nums[i])\n swap(nums, i, nums[i] - 1)\n }\n\n for (let i = 0; i < n; i++) {\n if (nums[i] !== i + 1) return i + 1\n }\n return n + 1\n}\n\nfunction swap(arr, i, j) {\n const tmp = arr[i]\n arr[i] = arr[j]\n arr[j] = tmp\n}\n\n\n// another\n\n/**\n * @param {number[]} nums\n * @return {number}\n */\nconst firstMissingPositive = function(nums) {\n const n = nums.length\n for(let i = 0; i < n; i++) {\n while(nums[i] < n && nums[nums[i] - 1] !== nums[i]) {\n swap(nums, i, nums[i] - 1)\n }\n }\n \n for(let i = 0; i < n; i++) {\n if(nums[i] !== i + 1) return i + 1\n }\n \n return n + 1\n};\n\nfunction swap(arr, i, j) {\n const tmp = arr[i]\n arr[i] = arr[j]\n arr[j] = tmp\n}\n\n// another\n\n/**\n * @param {number[]} nums\n * @return {number}\n */\nconst firstMissingPositive = function(nums) {\n const n = nums.length\n for(let i = 0; i < n; i++) {\n while(nums[i] > 0 && nums[i] !== nums[nums[i] - 1] && nums[i] <= n) {\n swap(i, nums[i] - 1) \n }\n }\n\n // console.log(nums)\n for(let i = 0; i < n; i++) {\n if(nums[i] !== i + 1) return i + 1\n }\n \n return n + 1\n \n \n function swap(i, j) {\n const tmp = nums[j]\n nums[j] = nums[i]\n nums[i] = tmp\n }\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720ae6", + "questionid": 27, + "title": "Trapping Rain Water", + "slug": "trapping-rain-water", + "description": "Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining. ", + "category": [ + "Array", + "Two Pointers", + "Dynamic Programming", + "Stack", + "Monotonic Stack" + ], + "complexity": "Hard", + "successrate": 56.3, + "totalsubmissions": 1933682, + "totalaccepted": 1089492, + "likes": 17879, + "dislikes": 252, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "height = [0,1,0,2,1,0,1,3,2,1,2,1]", + "expected_output": "6", + "explanation": "The above elevation map (black section) is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped." + }, + { + "example_num": 2, + "expected_input": "height = [4,2,0,3,2,5]", + "expected_output": "9", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} height\n * @return {number}\n */\nconst trap = function(height) {\n \n let s = height.length\n if(s === 0) return 0\n let res = 0\n const left_max = [height[0]]\n const right_max = []\n right_max[s - 1] = height[s - 1]\n for(let i = 1; i < s; i++) {\n left_max[i] = Math.max(height[i], left_max[i - 1])\n }\n for(let i = s - 2; i >= 0; i--) {\n right_max[i] = Math.max(height[i], right_max[i + 1])\n }\n for(let i = 1; i < s - 1; i++) {\n res += Math.min(left_max[i], right_max[i]) - height[i] \n }\n return res\n};\n\n// another\n\n/**\n * @param {number[]} height\n * @return {number}\n */\nconst trap = function(height) {\n const len = height.length\n if (len === 0) return 0\n const leftMax = [height[0]]\n const rightMax = []\n rightMax[len - 1] = height[len - 1]\n for (let i = len - 2; i >= 0; i--) {\n rightMax[i] = Math.max(height[i], rightMax[i + 1])\n }\n let res = 0\n for (let i = 1; i < len; i++) {\n leftMax[i] = Math.max(height[i], leftMax[i - 1])\n res += Math.min(leftMax[i], rightMax[i]) - height[i]\n }\n return res\n}\n\n// another\n\n/**\n * @param {number[]} height\n * @return {number}\n */\nconst trap = function(height) {\n const n = height.length\n let l = 0, r = n - 1, res = 0, leftMax = 0, rightMax = 0\n while(l <= r) {\n if(height[l] <= height[r]) {\n if(height[l] >= leftMax) leftMax = height[l]\n else res += leftMax - height[l]\n l++\n } else {\n if(height[r] >= rightMax) rightMax = height[r]\n else res += rightMax - height[r]\n r--\n }\n }\n return res\n};\n\n// another\n\n/**\n * @param {number[]} height\n * @return {number}\n */\nconst trap = function(height) {\n const n = height.length\n if(n === 0) return 0\n let res = 0\n let l = 0, r = n - 1, leftMax = height[l], rightMax = height[r]\n while(l < r) {\n if(height[l] <= height[r]) {\n l++\n leftMax = Math.max(leftMax, height[l])\n res += (leftMax - height[l]) \n } else {\n r--\n rightMax = Math.max(rightMax, height[r])\n res += rightMax - height[r]\n }\n }\n\n return res\n};\n\n// another\n\n/**\n * @param {number[]} height\n * @return {number}\n */\nconst trap = function(height) {\n const n = height.length, { max } = Math\n let res = 0, l = 0, r = n - 1, leftMax = height[0], rightMax = height[n - 1]\n while(l <= r) {\n if(leftMax < rightMax) {\n leftMax = max(leftMax, height[l])\n res += leftMax - height[l]\n l++\n } else {\n rightMax = max(rightMax, height[r])\n res += rightMax - height[r]\n r--\n }\n }\n\n return res\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720ae7", + "questionid": 28, + "title": "Jump Game II", + "slug": "jump-game-ii", + "description": "Given an array of non-negative integers nums, you are initially positioned at the first index of the array. Each element in the array represents your maximum jump length at that position. Your goal is to reach the last index in the minimum number of jumps. You can assume that you can always reach the last index. ", + "category": [ + "Array", + "Dynamic Programming", + "Greedy" + ], + "complexity": "Medium", + "successrate": 37, + "totalsubmissions": 1576789, + "totalaccepted": 583374, + "likes": 7769, + "dislikes": 291, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [2,3,1,1,4]", + "expected_output": "2", + "explanation": "The minimum number of jumps to reach the last index is 2. Jump 1 step from index 0 to 1, then 3 steps to the last index." + }, + { + "example_num": 2, + "expected_input": "nums = [2,3,0,1,4]", + "expected_output": "2", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} nums\n * @return {number}\n */\nconst jump = function(nums) {\n if (nums.length <= 1) return 0;\n let curMax = 0; // to mark the last element in a level\n let level = 0, i = 0;\n while (i <= curMax) { \n let furthest = curMax; // to mark the last element in the next level\n for (; i <= curMax; i++) {\n furthest = Math.max(furthest, nums[i] + i);\n if (furthest >= nums.length - 1) return level + 1;\n }\n level++;\n curMax = furthest;\n }\n return -1; // if i < curMax, i can't move forward anymore (the last element in the array can't be reached)\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720ae8", + "questionid": 29, + "title": "Permutations", + "slug": "permutations", + "description": "Given an array nums of distinct integers, return all the possible permutations. You can return the answer in any order. ", + "category": [ + "Array", + "Backtracking" + ], + "complexity": "Medium", + "successrate": 72.1, + "totalsubmissions": 1572570, + "totalaccepted": 1133403, + "likes": 9957, + "dislikes": 181, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,2,3]", + "expected_output": "[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "nums = [0,1]", + "expected_output": "[[0,1],[1,0]]", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "nums = [1]", + "expected_output": "[[1]]", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} nums\n * @return {number[][]}\n */\nfunction permute(nums) {\n const list = [];\n // Arrays.sort(nums); // not necessary\n backtrack(list, [], nums);\n return list;\n}\n\nfunction backtrack(list, tempList, nums) {\n if (tempList.length == nums.length) {\n list.push(tempList.slice(0));\n } else {\n for (let i = 0; i < nums.length; i++) {\n if (tempList.includes(nums[i])) continue; // element already exists, skip\n tempList.push(nums[i]);\n backtrack(list, tempList, nums);\n tempList.pop();\n }\n }\n}\n\n// another\n\n/**\n * @param {number[]} nums\n * @return {number[][]}\n */\nconst permute = function(nums) {\n const res = []\n bt(nums, 0, [], res)\n return res\n};\n\nfunction bt(nums, idx, cur, res) {\n if(idx === nums.length) {\n res.push(cur.slice())\n return\n }\n for(let i = 0; i < nums.length; i++) {\n if(cur.indexOf(nums[i]) !== -1) continue\n cur.push(nums[i])\n bt(nums, idx + 1, cur, res)\n cur.pop()\n }\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720af0", + "questionid": 37, + "title": "Spiral Matrix", + "slug": "spiral-matrix", + "description": "Given an m x n matrix, return all elements of the matrix in spiral order. ", + "category": [ + "Array", + "Matrix", + "Simulation" + ], + "complexity": "Medium", + "successrate": 41.2, + "totalsubmissions": 1729035, + "totalaccepted": 713051, + "likes": 6929, + "dislikes": 818, + "hints": "Well for some problems, the best way really is to come up with some algorithms for simulation. Basically, you need to simulate what the problem asks us to do. We go boundary by boundary and move inwards. That is the essential operation. First row, last column, last row, first column and then we move inwards by 1 and then repeat. That's all, that is all the simulation that we need. Think about when you want to switch the progress on one of the indexes. If you progress on i out of [i, j], you'd be shifting in the same column. Similarly, by changing values for j, you'd be shifting in the same row.\r\nAlso, keep track of the end of a boundary so that you can move inwards and then keep repeating. It's always best to run the simulation on edge cases like a single column or a single row to see if anything breaks or not.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "matrix = [[1,2,3],[4,5,6],[7,8,9]]", + "expected_output": "[1,2,3,6,9,8,7,4,5]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]", + "expected_output": "[1,2,3,4,8,12,11,10,9,5,6,7]", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[][]} matrix\n * @return {number[]}\n */\nconst spiralOrder = function(matrix) {\n const res = []\n let dir = 'top'\n while(matrix.length) {\n switch (dir) {\n case 'top':\n res.push(...matrix.shift())\n dir = 'right'\n break;\n case 'right':\n for(let i = 0; i < matrix.length - 1; ) {\n res.push(matrix[i].pop())\n if (matrix[i].length === 0) {\n matrix.splice(i, 1)\n } else {\n i++\n }\n }\n dir = 'bottom'\n break;\n case 'bottom':\n res.push(...matrix.pop().reverse())\n dir = 'left'\n break;\n case 'left':\n for(let i = matrix.length - 1; i >= 0; i--) {\n res.push(matrix[i].shift())\n if (matrix[i].length === 0) {\n matrix.splice(i, 1)\n }\n }\n dir = 'top'\n break;\n }\n }\n return res\n};\n\n// another\n\n/**\n * @param {number[][]} matrix\n * @return {number[]}\n */\nconst spiralOrder = function(matrix) {\n const res = [], m = matrix.length, n = matrix[0].length\n const dirs = [[0, 1], [1, 0], [0, -1], [-1, 0]]\n let di = 0, i = 0, j = 0, nx = 0, ny = 1\n while(true) {\n res.push(matrix[i][j])\n matrix[i][j] = Infinity\n if(chk(i, j)) {\n if(di === 0 && (j + 1 >= n || matrix[i][j + 1] === Infinity)) {\n i++\n di = 1\n } else if(di === 1 && (i + 1 >= m || matrix[i + 1][j] === Infinity)) {\n j--\n di = 2\n } else if(di === 2 && (j - 1 < 0 || matrix[i][j - 1] === Infinity)) {\n i--\n di = 3\n } else if(di === 3 && (i - 1 < 0 || matrix[i - 1][j] === Infinity)) {\n j++\n di = 0\n } else {\n i += dirs[di][0]\n j += dirs[di][1]\n }\n } else break\n }\n return res\n\n function chk(i, j) {\n for(let dir of dirs) {\n const nx = i + dir[0], ny = j + dir[1]\n if(nx >= 0 && nx < matrix.length && ny >= 0 && ny < matrix[0].length && matrix[nx][ny] !== Infinity) return true\n }\n return false\n } \n};\n \n\n" + }, + { + "_id": "66f925ddfdfb8e1665720af2", + "questionid": 39, + "title": "Merge Intervals", + "slug": "merge-intervals", + "description": "Given an array\u00a0of intervals\u00a0where intervals[i] = [starti, endi], merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input. ", + "category": [ + "Array", + "Sorting" + ], + "complexity": "Medium", + "successrate": 44.8, + "totalsubmissions": 3102911, + "totalaccepted": 1390388, + "likes": 13083, + "dislikes": 513, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "intervals = [[1,3],[2,6],[8,10],[15,18]]", + "expected_output": "[[1,6],[8,10],[15,18]]", + "explanation": "Since intervals [1,3] and [2,6] overlap, merge them into [1,6]." + }, + { + "example_num": 2, + "expected_input": "intervals = [[1,4],[4,5]]", + "expected_output": "[[1,5]]", + "explanation": "Intervals [1,4] and [4,5] are considered overlapping." + } + ], + "solution": "/**\n * @param {number[][]} intervals\n * @return {number[][]}\n */\nconst merge = function(intervals) {\n intervals.sort((a, b) => a[0] - b[0])\n const res = []\n let cur = intervals[0]\n const n = intervals.length\n res.push(cur)\n for(let i = 1; i < n; i++) {\n const e = intervals[i]\n if(e[0] <= cur[1]) {\n cur[1] = Math.max(e[1], cur[1])\n } else {\n res.push(e)\n cur = e\n }\n }\n \n return res\n};\n\n// another\n\n/**\n * @param {number[][]} intervals\n * @return {number[][]}\n */\nconst merge = function(intervals) {\n intervals.sort((a, b) => a[0] - b[0] || a[1] - b[1])\n const res = [intervals[0]]\n for(let i = 1, n = intervals.length; i < n; i++) {\n const [s, e] = intervals[i]\n const pre = res[res.length - 1]\n if(s <= pre[1]) {\n pre[1] = Math.max(pre[1], e)\n } else {\n res.push(intervals[i])\n }\n }\n return res\n};\n\n// another\n\n\n/**\n * @param {number[][]} intervals\n * @return {number[][]}\n */\nconst merge = function(intervals) {\n if(intervals == null || intervals.length === 0) return []\n intervals.sort((a, b) => a[0] === b[0] ? a[1] - b[1] : a[0] - b[0])\n const res = [intervals[0]]\n for(let i = 1, n = intervals.length; i < n; i++) {\n const last = res[res.length - 1]\n const lastEnd = last[1]\n const [s, e] = intervals[i]\n if(s > lastEnd) {\n res.push(intervals[i])\n } else {\n last[1] = Math.max(last[1], e)\n }\n }\n return res\n};\n\n// another\n\n/**\n * Definition for an interval.\n * function Interval(start, end) {\n * this.start = start;\n * this.end = end;\n * }\n */\n/**\n * @param {Interval[]} intervals\n * @return {Interval[]}\n */\nconst merge = function(intervals) {\n const hash = {}\n intervals.forEach(el => {\n if (hash.hasOwnProperty(el.start)) {\n hash[el.start][1] = Math.max(hash[el.start][1], el.end)\n } else {\n hash[el.start] = [el.start, el.end]\n }\n })\n\n const startArr = Object.keys(hash).sort((a, b) => +a - +b)\n const res = []\n\n while(startArr.length) {\n let start = startArr.shift()\n let end = hash[start][1]\n \n for(let i = 0; i < startArr.length; ) {\n if (+startArr[i] <= end) {\n end = Math.max(end, hash[startArr[i]][1])\n startArr.shift()\n } else {\n break\n }\n }\n let ins = new Interval(+start, end)\n res.push(ins)\n\n }\n return res\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720af3", + "questionid": 40, + "title": "Insert Interval", + "slug": "insert-interval", + "description": "You are given an array of non-overlapping intervals intervals where intervals[i] = [starti, endi] represent the start and the end of the ith interval and intervals is sorted in ascending order by starti. You are also given an interval newInterval = [start, end] that represents the start and end of another interval. Insert newInterval into intervals such that intervals is still sorted in ascending order by starti and intervals still does not have any overlapping intervals (merge overlapping intervals if necessary). Return intervals after the insertion. ", + "category": [ + "Array" + ], + "complexity": "Medium", + "successrate": 37.3, + "totalsubmissions": 1314450, + "totalaccepted": 490838, + "likes": 4631, + "dislikes": 334, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "intervals = [[1,3],[6,9]], newInterval = [2,5]", + "expected_output": "[[1,5],[6,9]]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8]", + "expected_output": "[[1,2],[3,10],[12,16]]", + "explanation": "Because the new interval [4,8] overlaps with [3,5],[6,7],[8,10]." + } + ], + "solution": "/**\n * @param {number[][]} intervals\n * @param {number[]} newInterval\n * @return {number[][]}\n */\nconst insert = function(intervals, newInterval) {\n const res = [], n = intervals.length\n let i = 0\n while(i < n && intervals[i][1] < newInterval[0]) {\n res.push(intervals[i])\n i++\n }\n while(i < n && intervals[i][0] <= newInterval[1]) {\n newInterval[0] = Math.min(newInterval[0], intervals[i][0])\n newInterval[1] = Math.max(newInterval[1], intervals[i][1])\n i++\n }\n res.push(newInterval)\n while(i < n) {\n res.push(intervals[i])\n i++\n }\n\n return res\n};\n\n// another\n/**\n * @param {number[][]} intervals\n * @param {number[]} newInterval\n * @return {number[][]}\n */\nconst insert = function(intervals, newInterval) {\n let i = 0\n while (i < intervals.length && intervals[i][1] < newInterval[0]) i++\n while (i < intervals.length && intervals[i][0] <= newInterval[1]) {\n newInterval[0] = Math.min(newInterval[0], intervals[i][0])\n newInterval[1] = Math.max(newInterval[1], intervals[i][1])\n intervals.splice(i, 1)\n }\n intervals.splice(i, 0, newInterval)\n return intervals\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720af7", + "questionid": 44, + "title": "Unique Paths", + "slug": "unique-paths", + "description": "There is a robot on an m x n grid. The robot is initially located at the top-left corner (i.e., grid[0][0]). The robot tries to move to the bottom-right corner (i.e., grid[m - 1][n - 1]). The robot can only move either down or right at any point in time. Given the two integers m and n, return the number of possible unique paths that the robot can take to reach the bottom-right corner. The test cases are generated so that the answer will be less than or equal to 2 * 109. ", + "category": [ + "Math", + "Dynamic Programming", + "Combinatorics" + ], + "complexity": "Medium", + "successrate": 59.9, + "totalsubmissions": 1523012, + "totalaccepted": 912411, + "likes": 8532, + "dislikes": 294, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "m = 3, n = 7", + "expected_output": "28", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "m = 3, n = 2", + "expected_output": "3", + "explanation": "From the top-left corner, there are a total of 3 ways to reach the bottom-right corner:\n1. Right -> Down -> Down\n2. Down -> Down -> Right\n3. Down -> Right -> Down" + } + ], + "solution": "/**\n * @param {number} m\n * @param {number} n\n * @return {number}\n */\nconst uniquePaths = function(m, n) {\n if(m === 0 || n === 0) return 0\n const dp = Array.from({length: m+1}, () => new Array(n+1).fill(1))\n dp[0][1] = dp[1][0] = 1\n for(let i = 1; i <= m; i++) {\n for(let j = 1; j <= n; j++) {\n dp[i][j] = dp[i - 1][j] + dp[i][j - 1]\n }\n }\n return dp[m - 1][n - 1]\n};\n\n// another\n\n/**\n * @param {number} m\n * @param {number} n\n * @return {number}\n */\nconst uniquePaths = function(m, n) {\n const dp = Array(m).fill(0)\n for(let i = 0; i < n; i++) {\n dp[0] = 1\n for(let j = 1; j < m; j++) {\n dp[j] += dp[j - 1]\n }\n }\n return dp[m - 1]\n};\n\n// another\n\n/**\n * @param {number} m\n * @param {number} n\n * @return {number}\n */\nconst uniquePaths = function(m, n) {\n return factorial(m+n-2)/(factorial(m - 1) * factorial(n - 1))\n};\n\nfunction factorial(n) {\n let res = 1\n while(n > 0) {\n res *= n\n n--\n }\n return res\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720af9", + "questionid": 46, + "title": "Plus One", + "slug": "plus-one", + "description": "You are given a large integer represented as an integer array digits, where each digits[i] is the ith digit of the integer. The digits are ordered from most significant to least significant in left-to-right order. The large integer does not contain any leading 0's. Increment the large integer by one and return the resulting array of digits. ", + "category": [ + "Array", + "Math" + ], + "complexity": "Easy", + "successrate": 42.8, + "totalsubmissions": 2719690, + "totalaccepted": 1162902, + "likes": 4014, + "dislikes": 4072, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "digits = [1,2,3]", + "expected_output": "[1,2,4]", + "explanation": "The array represents the integer 123.\nIncrementing by one gives 123 + 1 = 124.\nThus, the result should be [1,2,4]." + }, + { + "example_num": 2, + "expected_input": "digits = [4,3,2,1]", + "expected_output": "[4,3,2,2]", + "explanation": "The array represents the integer 4321.\nIncrementing by one gives 4321 + 1 = 4322.\nThus, the result should be [4,3,2,2]." + }, + { + "example_num": 3, + "expected_input": "digits = [9]", + "expected_output": "[1,0]", + "explanation": "The array represents the integer 9.\nIncrementing by one gives 9 + 1 = 10.\nThus, the result should be [1,0]." + } + ], + "solution": "/**\n * @param {number[]} digits\n * @return {number[]}\n */\nconst plusOne = function (digits) {\n for (let i = digits.length - 1; i >= 0; i--) {\n if (digits[i] !== 9) {\n digits[i]++\n return digits\n } else {\n digits[i] = 0\n }\n }\n digits.unshift(1)\n return digits\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720afb", + "questionid": 48, + "title": "Climbing Stairs", + "slug": "climbing-stairs", + "description": "You are climbing a staircase. It takes n steps to reach the top. Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? ", + "category": [ + "Math", + "Dynamic Programming", + "Memoization" + ], + "complexity": "Easy", + "successrate": 51, + "totalsubmissions": 2952667, + "totalaccepted": 1504735, + "likes": 11310, + "dislikes": 350, + "hints": "To reach nth step, what could have been your previous steps? (Think about the step sizes)", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 2", + "expected_output": "2", + "explanation": "There are two ways to climb to the top.\n1. 1 step + 1 step\n2. 2 steps" + }, + { + "example_num": 2, + "expected_input": "n = 3", + "expected_output": "3", + "explanation": "There are three ways to climb to the top.\n1. 1 step + 1 step + 1 step\n2. 1 step + 2 steps\n3. 2 steps + 1 step" + } + ], + "solution": "/**\n * @param {number} n\n * @return {number}\n */\nconst climbStairs = function(n) {\n const hash = {};\n return single(n, hash);\n};\n\nfunction single(i, hash) {\n if (hash.hasOwnProperty(i)) {\n return hash[i];\n }\n if (i === 1) {\n hash[1] = 1;\n return 1;\n }\n if (i === 2) {\n hash[2] = 2;\n return 2;\n }\n hash[i] = single(i - 1, hash) + single(i - 2, hash);\n return hash[i];\n}\n\n// another\n\n/**\n * @param {number} n\n * @return {number}\n */\nconst climbStairs = function (n) {\n const dp = new Array(n + 1).fill(0)\n if (n === 1) {\n return 1\n }\n if (n === 2) {\n return 2\n }\n dp[0] = 0\n dp[1] = 1\n dp[2] = 2\n for (let i = 3; i <= n; i++) {\n dp[i] = dp[i - 1] + dp[i - 2]\n }\n return dp[n]\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720b00", + "questionid": 53, + "title": "Subsets", + "slug": "subsets", + "description": "Given an integer array nums of unique elements, return all possible subsets (the power set). The solution set must not contain duplicate subsets. Return the solution in any order. ", + "category": [ + "Array", + "Backtracking", + "Bit Manipulation" + ], + "complexity": "Medium", + "successrate": 71.2, + "totalsubmissions": 1493029, + "totalaccepted": 1063773, + "likes": 9680, + "dislikes": 153, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,2,3]", + "expected_output": "[[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "nums = [0]", + "expected_output": "[[],[0]]", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} nums\n * @return {number[][]}\n */\n\nfunction subsets(nums) {\n const list = [];\n const len = nums.length;\n const subsetNum = Math.pow(2, len);\n for (let n = 0; n < subsetNum; n++) {\n list[n] = [];\n }\n for (let i = 0; i < len; i++) {\n for (let j = 0; j < subsetNum; j++) {\n if ((j >> i) & 1) {\n list[j].push(nums[i]);\n }\n }\n }\n return list;\n}\n\nconsole.log(subsets([1, 2, 3]));\n\n// another\n\n/**\n * @param {number[]} nums\n * @return {number[][]}\n */\n\nfunction subsets(nums) {\n const subs = [[]]\n for (let num of nums) {\n const n = subs.length\n for (let i = 0; i < n; i++) {\n subs.push(subs[i].slice(0))\n subs[subs.length - 1].push(num)\n }\n }\n return subs\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720b02", + "questionid": 55, + "title": "Search in Rotated Sorted Array II", + "slug": "search-in-rotated-sorted-array-ii", + "description": "There is an integer array nums sorted in non-decreasing order (not necessarily with distinct values). Before being passed to your function, nums is rotated at an unknown pivot index k (0 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed). For example, [0,1,2,4,4,4,5,6,6,7] might be rotated at pivot index 5 and become [4,5,6,6,7,0,1,2,4,4]. Given the array nums after the rotation and an integer target, return true if target is in nums, or false if it is not in nums. You must decrease the overall operation steps as much as possible. ", + "category": [ + "Array", + "Binary Search" + ], + "complexity": "Medium", + "successrate": 35.5, + "totalsubmissions": 1179147, + "totalaccepted": 419141, + "likes": 4331, + "dislikes": 718, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [2,5,6,0,0,1,2], target = 0", + "expected_output": "true", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "nums = [2,5,6,0,0,1,2], target = 3", + "expected_output": "false", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} nums\n * @param {number} target\n * @return {boolean}\n */\nconst search = function(nums, target) {\n const len = nums.length\n if(len === 0) return false\n if(nums[0] === target) return true\n if(target > nums[0]) {\n for(let i = 1; i < len; i++) {\n if(nums[i] === target) {\n return true\n } else {\n if(nums[i] < nums[i - 1]) return false\n }\n }\n } else {\n for(let i = len - 1; i >= 0; i--) {\n if(nums[i] === target) {\n return true\n } else {\n if(nums[i] < nums[i - 1]) return false\n }\n }\n }\n return false\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720b05", + "questionid": 58, + "title": "Largest Rectangle in Histogram", + "slug": "largest-rectangle-in-histogram", + "description": "Given an array of integers heights representing the histogram's bar height where the width of each bar is 1, return the area of the largest rectangle in the histogram. ", + "category": [ + "Array", + "Stack", + "Monotonic Stack" + ], + "complexity": "Hard", + "successrate": 40.7, + "totalsubmissions": 1220391, + "totalaccepted": 496774, + "likes": 9616, + "dislikes": 142, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "heights = [2,1,5,6,2,3]", + "expected_output": "10", + "explanation": "The above is a histogram where width of each bar is 1.\nThe largest rectangle is shown in the red area, which has an area = 10 units." + }, + { + "example_num": 2, + "expected_input": "heights = [2,4]", + "expected_output": "4", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} heights\n * @return {number}\n */\nconst largestRectangleArea = function(heights) {\n let height = heights;\n if (height == null || height.length == 0) {\n return 0;\n }\n const lessFromLeft = new Array(height.length).fill(0);\n const lessFromRight = new Array(height.length).fill(0);\n lessFromRight[height.length - 1] = height.length;\n lessFromLeft[0] = -1;\n for (let i = 1; i < height.length; i++) {\n let p = i - 1;\n while (p >= 0 && height[p] >= height[i]) {\n p = lessFromLeft[p];\n }\n lessFromLeft[i] = p;\n }\n for (let i = height.length - 2; i >= 0; i--) {\n let p = i + 1;\n while (p < height.length && height[p] >= height[i]) {\n p = lessFromRight[p];\n }\n lessFromRight[i] = p;\n }\n let maxArea = 0;\n for (let i = 0; i < height.length; i++) {\n maxArea = Math.max(\n maxArea,\n height[i] * (lessFromRight[i] - lessFromLeft[i] - 1)\n );\n }\n return maxArea;\n};\n\n\n// another\n\n/**\n * @param {number[]} heights\n * @return {number}\n */\nconst largestRectangleArea = function(heights) {\n if (!heights.length) return 0;\n let stack = [];\n let max = 0;\n for (let i = 0, cur, len = heights.length; i <= len; i++) {\n cur = i === len ? -1 : heights[i];\n while (stack.length && cur < heights[stack[stack.length - 1]]) {\n let index = stack.pop();\n let h = heights[index];\n let w = !stack.length ? i : i - stack[stack.length - 1] - 1;\n max = Math.max(max, h * w);\n }\n stack.push(i);\n }\n return max;\n};\n\n// another\n\n/**\n * @param {number[]} heights\n * @return {number}\n */\nconst largestRectangleArea = function(heights) {\n heights.push(0)\n const st = [], n = heights.length\n let res = 0\n for(let i = 0; i <= n; i++) {\n while(st.length && heights[st[st.length - 1]] >= heights[i]) {\n const top = st.pop()\n const pre = st.length ? st[st.length - 1] : -1\n res = Math.max(res, heights[top] * (i - pre - 1))\n }\n st.push(i)\n }\n return res\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720b0a", + "questionid": 63, + "title": "Reverse Linked List II", + "slug": "reverse-linked-list-ii", + "description": "Given the head of a singly linked list and two integers left and right where left <= right, reverse the nodes of the list from position left to position right, and return the reversed list. ", + "category": [ + "Linked List" + ], + "complexity": "Medium", + "successrate": 43.3, + "totalsubmissions": 1088239, + "totalaccepted": 471279, + "likes": 5945, + "dislikes": 278, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "head = [1,2,3,4,5], left = 2, right = 4", + "expected_output": "[1,4,3,2,5]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "head = [5], left = 1, right = 1", + "expected_output": "[5]", + "explanation": "" + } + ], + "solution": "/**\n * Definition for singly-linked list.\n * function ListNode(val, next) {\n * this.val = (val===undefined ? 0 : val)\n * this.next = (next===undefined ? null : next)\n * }\n */\n/**\n * @param {ListNode} head\n * @param {number} left\n * @param {number} right\n * @return {ListNode}\n */\nconst reverseBetween = function(head, left, right) {\n if(head == null) return head\n const dummy = new ListNode(null, head)\n let num = 0, cur = head\n while (cur) {\n num++\n cur = cur.next\n }\n let idx = 0, pre = null\n cur = dummy\n while (idx < right && idx <= num) {\n if (idx === left - 1) pre = cur\n if (idx >= left) {\n const tmp = pre.next\n pre.next = cur.next\n cur.next = cur.next.next\n pre.next.next = tmp\n }\n\n if (idx < left) cur = cur.next\n idx++\n }\n return dummy.next\n};\n\n// another\n\n/**\n * Definition for singly-linked list.\n * function ListNode(val) {\n * this.val = val;\n * this.next = null;\n * }\n */\n/**\n * @param {ListNode} head\n * @param {number} m\n * @param {number} n\n * @return {ListNode}\n */\nconst reverseBetween = function(head, m, n) {\n // Empty list\n if (head == null) {\n return null;\n }\n\n // Move the two pointers until they reach the proper starting point\n // in the list.\n let cur = head, prev = null;\n while (m > 1) {\n prev = cur;\n cur = cur.next;\n m--;\n n--;\n }\n\n // The two pointers that will fix the final connections.\n let con = prev, tail = cur;\n\n // Iteratively reverse the nodes until n becomes 0.\n let third = null;\n while (n > 0) {\n third = cur.next;\n cur.next = prev;\n prev = cur;\n cur = third;\n n--;\n }\n\n // Adjust the final connections as explained in the algorithm\n if (con != null) {\n con.next = prev;\n } else {\n head = prev;\n }\n\n tail.next = cur;\n return head;\n};\n\n// another\n\n/**\n * Definition for singly-linked list.\n * function ListNode(val, next) {\n * this.val = (val===undefined ? 0 : val)\n * this.next = (next===undefined ? null : next)\n * }\n */\n/**\n * @param {ListNode} head\n * @param {number} m\n * @param {number} n\n * @return {ListNode}\n */\nconst reverseBetween = function(head, m, n) {\n if (!head) return null;\n const dummy = new ListNode(0);\n dummy.next = head;\n let pre = dummy;\n for (let i = 0; i < m-1; i++) pre = pre.next\n let start = pre.next;\n let then = start.next;\n \n for (let i = 0; i < n-m; i++) {\n start.next = then.next\n then.next = pre.next\n pre.next = then;\n then = start.next;\n }\n return dummy.next;\n};\n\n// another\n\n/**\n * Definition for singly-linked list.\n * function ListNode(val, next) {\n * this.val = (val===undefined ? 0 : val)\n * this.next = (next===undefined ? null : next)\n * }\n */\n/**\n * @param {ListNode} head\n * @param {number} left\n * @param {number} right\n * @return {ListNode}\n */\nconst reverseBetween = function(head, left, right) {\n if(head == null || left === right) return head\n const dummy = new ListNode()\n dummy.next = head\n let tail = null, p = dummy\n for(let i = 1; i < left; i++) {\n p = p.next\n } \n tail = p.next\n let tmp\n for(let i = 0; i < right - left; i++) {\n tmp = p.next\n p.next = tail.next\n tail.next = tail.next.next\n p.next.next = tmp\n }\n\n return dummy.next\n};\n\n// another\n\n/**\n * @param {ListNode} head\n * @param {number} left\n * @param {number} right\n * @return {ListNode}\n */\nconst reverseBetween = function(head, left, right) {\n if(head == null) return head\n if(left === right) return head\n let cur = head, prev = null\n let step = 1\n while(step !== left) {\n prev = cur\n cur = cur.next\n step++\n }\n let l = cur\n while(step !== right) {\n cur = cur.next\n step++\n }\n let r = cur, next = cur.next\n // reverse\n \n let start = l, p = null\n while(start !== r) {\n let n = start.next\n start.next = p\n p = start\n start = n\n }\n\n r.next = p\n l.next = next\n if(prev) prev.next = r\n\n return prev ? head : r\n};\n\n// another\n\n/**\n * Definition for singly-linked list.\n * function ListNode(val, next) {\n * this.val = (val===undefined ? 0 : val)\n * this.next = (next===undefined ? null : next)\n * }\n */\n/**\n * @param {ListNode} head\n * @param {number} left\n * @param {number} right\n * @return {ListNode}\n */\nconst reverseBetween = function(head, left, right) {\n if(head == null) return head\n const dummy = new ListNode()\n dummy.next = head\n\n let p = dummy\n for(let i = 0; i < left - 1; i++) {\n p = p.next\n }\n let tail = p.next, tmp = null\n for(let i = 0; i < right - left; i++) {\n tmp = p.next\n p.next = tail.next\n tail.next = tail.next.next\n p.next.next = tmp\n }\n \n return dummy.next\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720ad0", + "questionid": 5, + "title": "Longest Palindromic Substring", + "slug": "longest-palindromic-substring", + "description": "Given a string s, return the longest palindromic substring in s. ", + "category": [ + "String", + "Dynamic Programming" + ], + "complexity": "Medium", + "successrate": 31.8, + "totalsubmissions": 5618701, + "totalaccepted": 1784028, + "likes": 17097, + "dislikes": 1005, + "hints": "How can we reuse a previously computed palindrome to compute a larger palindrome? If \u20ac\u0153aba\u20ac\u009d is a palindrome, is \u20ac\u0153xabax\u20ac\u009d a palindrome? Similarly is \u20ac\u0153xabay\u20ac\u009d a palindrome? Complexity based hint:\r\nIf we use brute-force and check whether for every start and end position a substring is a palindrome we have O(n^2) start - end pairs and O(n) palindromic checks. Can we reduce the time for palindromic checks to O(1) by reusing some previous computation.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "babad"", + "expected_output": ""bab"", + "explanation": ""aba" is also a valid answer." + }, + { + "example_num": 2, + "expected_input": "s = "cbbd"", + "expected_output": ""bb"", + "explanation": "" + } + ], + "solution": "/**\n * @param {string} s\n * @return {string}\n */\nconst longestPalindrome = function(s) {\n let res = ''\n for(let i = 0, len = s.length; i < len; i++) {\n let s1 = chk(s,i,i), s2 = chk(s,i,i+1)\n if(s1.length > res.length) res = s1\n if(s2.length > res.length) res = s2\n }\n return res\n};\n\nfunction chk(s, i, j) {\n for(; i>= 0 && j < s.length; i--, j++) {\n if(s[i] !== s[j]) break\n }\n return s.slice(i+1, j)\n}\n\n// another\n\n/**\n * @param {string} s\n * @return {string}\n */\nconst longestPalindrome = function(s) {\n let T = preProcess(s);\n let n = T.length;\n let P = [];\n let C = 0,\n R = 0;\n let i_mirror;\n for (let i = 1; i < n - 1; i++) {\n i_mirror = 2 * C - i; // equals to i' = C - (i-C)\n\n P[i] = R > i ? Math.min(R - i, P[i_mirror]) : 0;\n\n // Attempt to expand palindrome centered at i\n while (T[i + 1 + P[i]] == T[i - 1 - P[i]]) P[i]++;\n\n // If palindrome centered at i expand past R,\n // adjust center based on expanded palindrome.\n if (i + P[i] > R) {\n C = i;\n R = i + P[i];\n }\n }\n\n // Find the maximum element in P.\n let maxLen = 0;\n let centerIndex = 0;\n for (let j = 1; j < n - 1; j++) {\n if (P[j] > maxLen) {\n maxLen = P[j];\n centerIndex = j;\n }\n }\n\n return s.substr((centerIndex - 1 - maxLen) / 2, maxLen);\n};\n\nfunction preProcess(s) {\n let n = s.length;\n if (n === 0) return \"^$\";\n let ret = \"^\";\n for (let i = 0; i < n; i++) ret += \"#\" + s.substr(i, 1);\n\n ret += \"#$\";\n return ret;\n}\n\n// another\n\n/**\n * @param {string} s\n * @return {string}\n */\nconst longestPalindrome = function(s) {\n const n = s.length\n let res = ''\n for(let i = 0; i < n; i++) {\n const first = chk(s, i, i, n)\n if(first.length > res.length) res = first\n const second = chk(s, i, i + 1, n)\n if(second.length > res.length) res = second\n }\n return res\n};\n\nfunction chk(str, i, j, n) {\n if(j >= n) return str[i]\n let l = i, r = j\n while(l >= 0 && r < n) {\n if(str[l] === str[r]) {\n l--\n r++\n } else {\n return str.slice(l + 1, r)\n }\n }\n if(l < 0) {\n return str.slice(0, r)\n } else {\n return str.slice(l + 1, n)\n }\n}\n\n" + }, + { + "_id": "66f925ddfdfb8e1665720ad1", + "questionid": 6, + "title": "Reverse Integer", + "slug": "reverse-integer", + "description": "Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0. Assume the environment does not allow you to store 64-bit integers (signed or unsigned). ", + "category": [ + "Math" + ], + "complexity": "Medium", + "successrate": 26.7, + "totalsubmissions": 7589410, + "totalaccepted": 2022695, + "likes": 6971, + "dislikes": 9596, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "x = 123", + "expected_output": "321", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "x = -123", + "expected_output": "-321", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "x = 120", + "expected_output": "21", + "explanation": "" + } + ], + "solution": "/**\n * @param {number} x\n * @return {number}\n */\nconst reverse = function (x) {\n let res = 0, tail, newResult\n const low = -Math.pow(2, 31), high = Math.pow(2, 31)\n while(x !== 0) {\n tail = x % 10\n newResult = res * 10 + tail\n // if((newResult - tail) / 10 !== res) return 0\n if(newResult < low || newResult >= high) return 0\n res = newResult\n x = ~~(x / 10)\n }\n \n return res\n};\n\n// another\n\n\n/**\n * @param {number} x\n * @return {number}\n */\nconst reverse = function(num) {\n let negative = false;\n let result = 0;\n if (num < 0) {\n negative = true;\n num = Math.abs(num);\n }\n while (num > 0) {\n mod = num % 10; // mod = 3 // mod = 2 // mod\n num = Math.floor(num / 10); // num = 12 // num = 1\n result = result * 10 + mod; // 0 = 0 * 10 + 3 = 0 + 3 = 3 // 3 = 3 * 10 + 2 = 30 + 2 = 32\n }\n if (result > 2147483647) return 0;\n if (negative) return result * -1;\n return result;\n};\n\n// another \n\n/**\n * @param {number} n\n * @return {number}\n */\nconst reverse = (n) => {\n if (typeof n !== 'number') {\n throw new Error('n must be a number');\n }\n let sign = Math.sign(n);\n n = Math.abs(n);\n if (n < 0) {\n return -reverse(-n);\n }\n let reversed = Number([...n.toString()].reverse().join(''));\n return sign * reversed;\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720ad5", + "questionid": 10, + "title": "3Sum", + "slug": "3sum", + "description": "Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0. Notice that the solution set must not contain duplicate triplets. ", + "category": [ + "Array", + "Two Pointers", + "Sorting" + ], + "complexity": "Medium", + "successrate": 31, + "totalsubmissions": 6090299, + "totalaccepted": 1886780, + "likes": 17218, + "dislikes": 1653, + "hints": "So, we essentially need to find three numbers x, y, and z such that they add up to the given value. If we fix one of the numbers say x, we are left with the two-sum problem at hand! For the two-sum problem, if we fix one of the numbers, say x, we have to scan the entire array to find the next numbery which is value - x where value is the input parameter. Can we change our array somehow so that this search becomes faster? The second train of thought for two-sum is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [-1,0,1,2,-1,-4]", + "expected_output": "[[-1,-1,2],[-1,0,1]]", + "explanation": "nums[0] + nums[1] + nums[2] = (-1) + 0 + 1 = 0.\nnums[1] + nums[2] + nums[4] = 0 + 1 + (-1) = 0.\nnums[0] + nums[3] + nums[4] = (-1) + 2 + (-1) = 0.\nThe distinct triplets are [-1,0,1] and [-1,-1,2].\nNotice that the order of the output and the order of the triplets does not matter." + }, + { + "example_num": 2, + "expected_input": "nums = [0,1,1]", + "expected_output": "[]", + "explanation": "The only possible triplet does not sum up to 0." + }, + { + "example_num": 3, + "expected_input": "nums = [0,0,0]", + "expected_output": "[[0,0,0]]", + "explanation": "The only possible triplet sums up to 0." + } + ], + "solution": "/**\n * @param {number[]} nums\n * @return {number[][]}\n */\nconst threeSum = function(nums) {\n const res = [], n = nums.length\n nums.sort((a, b) => a - b)\n \n for(let i = 0; i < n; i++) {\n const target = -nums[i]\n let l = i + 1, r = n - 1\n while(l < r) {\n const sum = nums[l] + nums[r]\n if(sum > target) r--\n else if(sum < target) l++\n else {\n const e = [nums[i], nums[l], nums[r]]\n res.push(e)\n while(l + 1 < r && nums[l + 1] === nums[l]) l++\n while(r - 1 > l && nums[r - 1] === nums[r]) r--\n l++\n r--\n }\n }\n while(i + 1 < n && nums[i] === nums[i + 1]) i++\n }\n \n \n return res\n};\n\n// another\n\n\n/**\n * @param {number[]} nums\n * @return {number[][]}\n */\nconst threeSum = function (nums) {\n nums.sort((a, b) => a - b)\n const res = []\n let lo, hi, sum\n for (let i = 0; i < nums.length - 2; i++) {\n if (nums[i] > 0) break\n if (nums[i] === nums[i - 1]) continue\n if (i === 0 || (i > 0 && nums[i] !== nums[i - 1])) {\n lo = i + 1\n hi = nums.length - 1\n sum = 0 - nums[i]\n while (lo < hi) {\n if (nums[lo] + nums[hi] === sum) {\n res.push([nums[i], nums[lo], nums[hi]])\n while (lo < hi && nums[lo] === nums[lo + 1]) lo += 1\n while (lo < hi && nums[hi] === nums[hi - 1]) hi -= 1\n lo += 1\n hi -= 1\n } else if (nums[lo] + nums[hi] < sum) lo++\n else hi--\n }\n }\n }\n return res\n}\n\n// another\n\n/**\n * @param {number[]} nums\n * @return {number[][]}\n */\nconst threeSum = function(nums) {\n const res = [], n = nums.length\n nums.sort((a, b) => a - b)\n for(let i = 0; i < n - 2; i++) {\n let l = i + 1, r = n - 1, target = -nums[i]\n if(i === 0 || (i > 0 && nums[i] !== nums[i - 1])) {\n while(l < r) {\n if(nums[l] + nums[r] === target) {\n res.push([nums[i], nums[l], nums[r]])\n while(l < n - 1 && nums[l] === nums[l + 1]) l++\n while(r > 0 && nums[r] === nums[r - 1]) r--\n r--\n l++\n } else if(nums[l] + nums[r] > target) {\n r--\n } else l++\n }\n }\n } \n\n return res\n};\n\n// another\n\n/**\n * @param {number[]} nums\n * @return {number[][]}\n */\nconst threeSum = function(nums) {\n nums.sort((a, b) => a - b)\n const n = nums.length\n let res = []\n for(let i = 0; i < n - 2; i++) {\n const e = nums[i], target = -e\n let l = i + 1, r = n - 1\n while(l < r) {\n const tmp = nums[l] + nums[r]\n if(tmp < target) l++\n else if(tmp > target) r--\n else {\n res.push([nums[i], nums[l], nums[r]])\n l++\n r--\n while(l < r && nums[l] === nums[l - 1]) l++\n while(l < r && nums[r] === nums[r + 1]) r--\n }\n }\n while(i + 1 < n && nums[i + 1] === e) i++\n }\n \n \n return res\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720ad7", + "questionid": 12, + "title": "Letter Combinations of a Phone Number", + "slug": "letter-combinations-of-a-phone-number", + "description": "Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent. Return the answer in any order. A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters. ", + "category": [ + "Hash Table", + "String", + "Backtracking" + ], + "complexity": "Medium", + "successrate": 53.5, + "totalsubmissions": 2146094, + "totalaccepted": 1147569, + "likes": 9594, + "dislikes": 668, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "digits = "23"", + "expected_output": "["ad","ae","af","bd","be","bf","cd","ce","cf"]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "digits = """, + "expected_output": "[]", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "digits = "2"", + "expected_output": "["a","b","c"]", + "explanation": "" + } + ], + "solution": "/**\n * @param {string} digits\n * @return {string[]}\n */\nconst letterCombinations = function(digits) {\n if (digits === \"\") {\n return [];\n }\n const charMap = {\n 2: [\"a\", \"b\", \"c\"],\n 3: [\"d\", \"e\", \"f\"],\n 4: [\"g\", \"h\", \"i\"],\n 5: [\"j\", \"k\", \"l\"],\n 6: [\"m\", \"n\", \"o\"],\n 7: [\"p\", \"q\", \"r\", \"s\"],\n 8: [\"t\", \"u\", \"v\"],\n 9: [\"w\", \"x\", \"y\", \"z\"]\n };\n const res = [];\n const matrix = [];\n for (let i = 0; i < digits.length; i++) {\n matrix.push(charMap[digits.charAt(i)]);\n }\n let tmp = matrix[0];\n for (let j = 1; j < matrix.length; j++) {\n tmp = helper(matrix, j, tmp);\n }\n return tmp;\n};\nfunction helper(matrix, rowIdx, arr) {\n const res = [];\n for (let i = 0; i < arr.length; i++) {\n const preStr = arr[i];\n for (let j = 0; j < matrix[rowIdx].length; j++) {\n res.push(`${preStr}${matrix[rowIdx][j]}`);\n }\n }\n return res;\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720add", + "questionid": 18, + "title": "Reverse Nodes in k-Group", + "slug": "reverse-nodes-in-k-group", + "description": "Given the head of a linked list, reverse the nodes of the list k at a time, and return the modified list. k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes, in the end, should remain as it is. You may not alter the values in the list's nodes, only nodes themselves may be changed. ", + "category": [ + "Linked List", + "Recursion" + ], + "complexity": "Hard", + "successrate": 50.9, + "totalsubmissions": 983085, + "totalaccepted": 500025, + "likes": 6837, + "dislikes": 485, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "head = [1,2,3,4,5], k = 2", + "expected_output": "[2,1,4,3,5]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "head = [1,2,3,4,5], k = 3", + "expected_output": "[3,2,1,4,5]", + "explanation": "" + } + ], + "solution": "/**\n * Definition for singly-linked list.\n * function ListNode(val) {\n * this.val = val;\n * this.next = null;\n * }\n */\n/**\n * @param {ListNode} head\n * @param {number} k\n * @return {ListNode}\n */\nconst reverseKGroup = function(head, k) {\n let n = 0\n for (let i = head; i != null; n++, i = i.next);\n let dmy = new ListNode(0)\n dmy.next = head\n for (let prev = dmy, tail = head; n >= k; n -= k) {\n for (let i = 1; i < k; i++) {\n let next = tail.next.next\n tail.next.next = prev.next\n prev.next = tail.next\n tail.next = next\n }\n\n prev = tail\n tail = tail.next\n }\n return dmy.next\n}\n\n// another\n\n/**\n * Definition for singly-linked list.\n * function ListNode(val, next) {\n * this.val = (val===undefined ? 0 : val)\n * this.next = (next===undefined ? null : next)\n * }\n */\n/**\n * @param {ListNode} head\n * @param {number} k\n * @return {ListNode}\n */\nconst reverseKGroup = function (head, k) {\n if(head == null) return head\n const dummy = new ListNode()\n dummy.next = head\n let n = 0, cur = head\n while(cur) {\n n++\n cur = cur.next\n }\n if(n < k) return head\n let pre = dummy, tail = head\n\n for(let i = 0; i + k <= n; i += k) {\n for(let j = 1; j < k; j++) {\n const tmp = pre.next\n pre.next = tail.next\n tail.next = tail.next.next\n pre.next.next = tmp\n }\n pre = tail\n tail = tail.next\n } \n \n return dummy.next\n}\n\n\n\n// another\n\n/**\n * Definition for singly-linked list.\n * function ListNode(val, next) {\n * this.val = (val===undefined ? 0 : val)\n * this.next = (next===undefined ? null : next)\n * }\n */\n/**\n * @param {ListNode} head\n * @param {number} k\n * @return {ListNode}\n */\nconst reverseKGroup = function (head, k) {\n let ptr = head\n let ktail = null\n\n // Head of the final, moified linked list\n let new_head = null\n\n // Keep going until there are nodes in the list\n while (ptr != null) {\n let count = 0\n\n // Start counting nodes from the head\n ptr = head\n\n // Find the head of the next k nodes\n while (count < k && ptr != null) {\n ptr = ptr.next\n count += 1\n }\n\n // If we counted k nodes, reverse them\n if (count == k) {\n // Reverse k nodes and get the new head\n let revHead = reverseLinkedList(head, k)\n\n // new_head is the head of the final linked list\n if (new_head == null) new_head = revHead\n\n // ktail is the tail of the previous block of\n // reversed k nodes\n if (ktail != null) ktail.next = revHead\n\n ktail = head\n head = ptr\n }\n }\n\n // attach the final, possibly un-reversed portion\n if (ktail != null) ktail.next = head\n\n return new_head == null ? head : new_head\n}\n\nfunction reverseLinkedList(head, k) {\n // Reverse k nodes of the given linked list.\n // This function assumes that the list contains\n // atleast k nodes.\n let new_head = null\n let ptr = head\n\n while (k > 0) {\n // Keep track of the next node to process in the\n // original list\n let next_node = ptr.next\n\n // Insert the node pointed to by \"ptr\"\n // at the beginning of the reversed list\n ptr.next = new_head\n new_head = ptr\n\n // Move on to the next node\n ptr = next_node\n\n // Decrement the count of nodes to be reversed by 1\n k--\n }\n\n // Return the head of the reversed list\n return new_head\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720ae3", + "questionid": 24, + "title": "Search Insert Position", + "slug": "search-insert-position", + "description": "Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. You must\u00a0write an algorithm with\u00a0O(log n) runtime complexity. ", + "category": [ + "Array", + "Binary Search" + ], + "complexity": "Easy", + "successrate": 42.3, + "totalsubmissions": 3247274, + "totalaccepted": 1374840, + "likes": 7432, + "dislikes": 401, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,3,5,6], target = 5", + "expected_output": "2", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "nums = [1,3,5,6], target = 2", + "expected_output": "1", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "nums = [1,3,5,6], target = 7", + "expected_output": "4", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} nums\n * @param {number} target\n * @return {number}\n */\nconst searchInsert = function(nums, target) {\n for (let i = 0; i < nums.length; i++) {\n if (nums[i] >= target) {\n return i;\n } else {\n if (i === nums.length - 1) {\n return i + 1;\n }\n }\n }\n};\n\n// another\n\n/**\n * @param {number[]} nums\n * @param {number} target\n * @return {number}\n */\nconst searchInsert = function(nums, target) {\n const n = nums.length\n let l = 0, r = n - 1\n while(l <= r) {\n const mid = l + ((r - l) >> 1)\n if(nums[mid] === target) return mid\n if(nums[mid] > target) r = mid - 1\n else l = mid + 1\n }\n return l\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720af4", + "questionid": 41, + "title": "Length of Last Word", + "slug": "length-of-last-word", + "description": "Given a string s consisting\u00a0of some words separated by some number of spaces, return the length of the last word in the string. A word is a maximal substring consisting of non-space characters only. ", + "category": [ + "String" + ], + "complexity": "Easy", + "successrate": 37.4, + "totalsubmissions": 1916299, + "totalaccepted": 716989, + "likes": 875, + "dislikes": 70, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "Hello World"", + "expected_output": "5", + "explanation": "The last word is "World" with length 5." + }, + { + "example_num": 2, + "expected_input": "s = " fly me to the moon "", + "expected_output": "4", + "explanation": "The last word is "moon" with length 4." + }, + { + "example_num": 3, + "expected_input": "s = "luffy is still joyboy"", + "expected_output": "6", + "explanation": "The last word is "joyboy" with length 6." + } + ], + "solution": "/**\n * @param {string} s\n * @return {number}\n */\nconst lengthOfLastWord = function(s) {\n const arr = s.split(\" \");\n for (let i = arr.length - 1; i >= 0; i--) {\n if (arr[i].length > 0) return arr[i].length;\n }\n return 0;\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720af6", + "questionid": 43, + "title": "Rotate List", + "slug": "rotate-list", + "description": "Given the head of a linked\u00a0list, rotate the list to the right by k places. ", + "category": [ + "Linked List", + "Two Pointers" + ], + "complexity": "Medium", + "successrate": 34.8, + "totalsubmissions": 1566873, + "totalaccepted": 545760, + "likes": 4972, + "dislikes": 1265, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "head = [1,2,3,4,5], k = 2", + "expected_output": "[4,5,1,2,3]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "head = [0,1,2], k = 4", + "expected_output": "[2,0,1]", + "explanation": "" + } + ], + "solution": "/**\n * Definition for singly-linked list.\n * function ListNode(val) {\n * this.val = val;\n * this.next = null;\n * }\n */\n/**\n * @param {ListNode} head\n * @param {number} k\n * @return {ListNode}\n */\nconst rotateRight = function(head, k) {\n if (head === null || head.next === null) return head;\n const dummy = new ListNode(0);\n dummy.next = head;\n let fast = dummy,slow = dummy;\n\n let i;\n for (i = 0; fast.next != null; i++)//Get the total length \n \tfast = fast.next;\n \n for (let j = i - k % i; j > 0; j--) //Get the i-n%i th node\n \tslow = slow.next;\n \n fast.next = dummy.next; //Do the rotation\n dummy.next = slow.next;\n slow.next = null;\n \n return dummy.next;\n};\n\n// another\n\n/**\n * Definition for singly-linked list.\n * function ListNode(val, next) {\n * this.val = (val===undefined ? 0 : val)\n * this.next = (next===undefined ? null : next)\n * }\n */\n/**\n * @param {ListNode} head\n * @param {number} k\n * @return {ListNode}\n */\nconst rotateRight = function(head, k) {\n if(head == null) return null\n let len = 1\n let tmp = head\n while(tmp.next) {\n len++\n tmp = tmp.next\n }\n k = k % len\n if(k === 0) return head\n let tail = head\n for(let i = 1; i < len - k; i++) {\n tail = tail.next\n }\n const newHead = tail.next\n tmp.next = head\n tail.next = null\n return newHead\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720afa", + "questionid": 47, + "title": "Add Binary", + "slug": "add-binary", + "description": "Given two binary strings a and b, return their sum as a binary string. ", + "category": [ + "Math", + "String", + "Bit Manipulation", + "Simulation" + ], + "complexity": "Easy", + "successrate": 50.4, + "totalsubmissions": 1625914, + "totalaccepted": 819020, + "likes": 4851, + "dislikes": 533, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "a = \"11\", b = \"1\"", + "expected_output": "\"100\"", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "a = \"1010\", b = \"1011\"", + "expected_output": "\"10101\"", + "explanation": "" + } + ], + "solution": "/**\n * @param {string} a\n * @param {string} b\n * @return {string}\n */\nconst addBinary = function(a, b) {\n let s = ''\n let c = 0\n let i = a.length - 1\n let j = b.length - 1\n while(i >= 0 || j >= 0 || c === 1) {\n c += i >= 0 ? +a[i--] : 0\n c += j >= 0 ? +b[j--] : 0\n s = (c % 2 === 1 ? '1' : '0') + s\n c = Math.floor(c / 2)\n }\n return s\n};\n\n// another\n\n/**\n * @param {string} a\n * @param {string} b\n * @return {string}\n */\nconst addBinary = function(a, b) {\n let next = false\n let res = []\n let ai = a.length - 1\n let bi = b.length - 1\n while((ai >= 0 && bi >=0) || next) {\n const tmp = (ai >= 0 ? +a[ai--] : 0) + (bi >= 0 ? +b[bi--] : 0) + (next ? 1 : 0)\n if(tmp > 1) next = true\n else next = false\n res.unshift('' + (tmp % 2))\n }\n\n while(ai >= 0) res.unshift(a[ai--])\n while(bi >= 0) res.unshift(b[bi--])\n \n return res.join('')\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720aff", + "questionid": 52, + "title": "Combinations", + "slug": "combinations", + "description": "Given two integers n and k, return all possible combinations of k numbers out of the range [1, n]. You may return the answer in any order. ", + "category": [ + "Backtracking" + ], + "complexity": "Medium", + "successrate": 63.7, + "totalsubmissions": 799662, + "totalaccepted": 509584, + "likes": 4032, + "dislikes": 136, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 4, k = 2", + "expected_output": "[[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]", + "explanation": "There are 4 choose 2 = 6 total combinations.\nNote that combinations are unordered, i.e., [1,2] and [2,1] are considered to be the same combination." + }, + { + "example_num": 2, + "expected_input": "n = 1, k = 1", + "expected_output": "[[1]]", + "explanation": "There is 1 choose 1 = 1 total combination." + } + ], + "solution": "/**\n * @param {number} n\n * @param {number} k\n * @return {number[][]}\n */\nconst combine = function(n, k) {\n const res = [];\n bt(res, [], 1, n, k);\n return res;\n};\n\nfunction bt(res, tmp, start, n, k) {\n if (k === 0) {\n res.push(tmp.slice(0));\n return;\n }\n for (let i = start; i <= n - k + 1; i++) {\n tmp.push(i);\n bt(res, tmp, i + 1, n, k - 1);\n tmp.pop();\n }\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720b01", + "questionid": 54, + "title": "Word Search", + "slug": "word-search", + "description": "Given an m x n grid of characters board and a string word, return true if word exists in the grid. The word can be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once. ", + "category": [ + "Array", + "Backtracking", + "Matrix" + ], + "complexity": "Medium", + "successrate": 39.6, + "totalsubmissions": 2376458, + "totalaccepted": 940859, + "likes": 8999, + "dislikes": 344, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED"", + "expected_output": "true", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "SEE"", + "expected_output": "true", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCB"", + "expected_output": "false", + "explanation": "" + } + ], + "solution": "/**\n * @param {character[][]} board\n * @param {string} word\n * @return {boolean}\n */\nconst exist = function(board, word) {\n const dirs = [[0, 1], [0, -1], [-1, 0], [1, 0]];\n for (let j = 0; j < board.length; j++) {\n for (let i = 0; i < board[0].length; i++) {\n let res = dfs(board, i, j, dirs, word, 0);\n if (res) {\n return true;\n }\n }\n }\n return false;\n};\n\nfunction dfs(board, x, y, dirs, word, start) {\n if (start >= word.length) return true;\n if (x < 0 || y < 0 || x >= board[0].length || y >= board.length) return false;\n if (word[start] !== board[y][x] || board[y][x] === \"#\") return false;\n\n let res = false;\n let c = board[y][x];\n board[y][x] = \"#\";\n for (let el of dirs) {\n let posx = x + el[0];\n let posy = y + el[1];\n res = res || dfs(board, posx, posy, dirs, word, start + 1);\n if (res) return true;\n }\n board[y][x] = c;\n\n return false;\n}\n\n// time complexity: O(M * N * 3^L), where L is the length of word.\n// we have a visited array and we never go back, so 3 directions\n\n// another\n\n/**\n * @param {character[][]} board\n * @param {string} word\n * @return {boolean}\n */\nconst exist = function(board, word) {\n if (!word || !board || board.length === 0) return false\n const dirs = [[-1, 0], [1, 0], [0, -1], [0, 1]]\n for (let row = 0; row < board.length; row++) {\n for (let col = 0; col < board[row].length; col++) {\n if (searchWord(board, row, col, word, 0, dirs)) return true\n }\n }\n return false\n}\n\nconst searchWord = (board, row, col, word, widx, dirs) => {\n if (widx === word.length) return true\n if (\n row < 0 ||\n col < 0 ||\n row === board.length ||\n col === board[0].length ||\n board[row][col] === null ||\n board[row][col] !== word[widx]\n ) return false\n\n const ch = board[row][col]\n board[row][col] = null // mark visited\n\n for (let dir of dirs) {\n if (searchWord(board, row + dir[0], col + dir[1], word, widx + 1, dirs)) {\n return true\n }\n }\n board[row][col] = ch // recover\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720b03", + "questionid": 56, + "title": "Remove Duplicates from Sorted List II", + "slug": "remove-duplicates-from-sorted-list-ii", + "description": "Given the head of a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. Return the linked list sorted as well. ", + "category": [ + "Linked List", + "Two Pointers" + ], + "complexity": "Medium", + "successrate": 44.2, + "totalsubmissions": 1085754, + "totalaccepted": 480084, + "likes": 5610, + "dislikes": 164, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "head = [1,2,3,3,4,4,5]", + "expected_output": "[1,2,5]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "head = [1,1,1,2,3]", + "expected_output": "[2,3]", + "explanation": "" + } + ], + "solution": "\n/**\n * Definition for singly-linked list.\n * function ListNode(val) {\n * this.val = val;\n * this.next = null;\n * }\n */\n/**\n * @param {ListNode} head\n * @return {ListNode}\n */\nconst deleteDuplicates = function(head) {\n let dummy = new ListNode(undefined);\n dummy.next = head;\n let prev = dummy;\n let curr = head;\n \n while(curr) {\n while(curr.next && curr.next.val === curr.val) {\n curr = curr.next;\n }\n if(prev.next === curr) { // detect if it has deleted some elements\n prev = prev.next;\n curr = curr.next;\n } else {\n prev.next = curr.next;\n curr = curr.next;\n }\n }\n \n return dummy.next;\n };\n" + }, + { + "_id": "66f925ddfdfb8e1665720b04", + "questionid": 57, + "title": "Remove Duplicates from Sorted List", + "slug": "remove-duplicates-from-sorted-list", + "description": "Given the head of a sorted linked list, delete all duplicates such that each element appears only once. Return the linked list sorted as well. ", + "category": [ + "Linked List" + ], + "complexity": "Easy", + "successrate": 49, + "totalsubmissions": 1714235, + "totalaccepted": 839133, + "likes": 4634, + "dislikes": 183, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "head = [1,1,2]", + "expected_output": "[1,2]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "head = [1,1,2,3,3]", + "expected_output": "[1,2,3]", + "explanation": "" + } + ], + "solution": "/**\n * Definition for singly-linked list.\n * function ListNode(val) {\n * this.val = val;\n * this.next = null;\n * }\n */\n/**\n * @param {ListNode} head\n * @return {ListNode}\n */\nconst deleteDuplicates = function(head) {\n let current = head;\n while (current !== null && current.next !== null) {\n if (current.val === current.next.val) {\n current.next = current.next.next;\n } else {\n current = current.next;\n }\n }\n return head;\n};\n\n// another\n\n/**\n * Definition for singly-linked list.\n * function ListNode(val, next) {\n * this.val = (val===undefined ? 0 : val)\n * this.next = (next===undefined ? null : next)\n * }\n */\n/**\n * @param {ListNode} head\n * @return {ListNode}\n */\nconst deleteDuplicates = function(head) {\n let prev = null, cur = head\n while(cur) {\n if(prev && prev.val === cur.val) {\n prev.next = cur.next\n cur = cur.next\n } else {\n prev = cur\n cur = cur.next \n }\n }\n return head\n};\n\n" + }, + { + "_id": "66f925ddfdfb8e1665720b06", + "questionid": 59, + "title": "Maximal Rectangle", + "slug": "maximal-rectangle", + "description": "Given a rows x cols\u00a0binary matrix filled with 0's and 1's, find the largest rectangle containing only 1's and return its area. ", + "category": [ + "Array", + "Dynamic Programming", + "Stack", + "Matrix", + "Monotonic Stack" + ], + "complexity": "Hard", + "successrate": 42.7, + "totalsubmissions": 682660, + "totalaccepted": 291357, + "likes": 6471, + "dislikes": 106, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]]", + "expected_output": "6", + "explanation": "The maximal rectangle is shown in the above picture." + }, + { + "example_num": 2, + "expected_input": "matrix = [["0"]]", + "expected_output": "0", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "matrix = [["1"]]", + "expected_output": "1", + "explanation": "" + } + ], + "solution": "/**\n * @param {character[][]} matrix\n * @return {number}\n */\nconst maximalRectangle = function(matrix) {\n const m = matrix.length, n = matrix[0].length\n const heights = Array(n).fill(0), left = Array(n).fill(0), right = Array(n).fill(n)\n let res = 0\n for(let i = 0; i < m; i++) {\n let l = 0, r = n\n for(let j = 0; j < n; j++) {\n if(matrix[i][j] === '1') {\n heights[j]++\n } else {\n heights[j] = 0\n }\n }\n\n for(let j = 0; j < n; j++) {\n if(matrix[i][j] === '1') {\n left[j] = Math.max(l, left[j])\n } else {\n left[j] = 0\n l = j + 1\n }\n }\n\n for(let j = n - 1; j >= 0; j--) {\n if(matrix[i][j] === '1') {\n right[j] = Math.min(r, right[j])\n } else {\n right[j] = n\n r = j\n }\n }\n\n for(let j = 0; j < n; j++) {\n res = Math.max(res, heights[j] * (right[j] - left[j]))\n }\n\n }\n\n return res\n};\n\n// another\n\n\n/**\n * @param {character[][]} matrix\n * @return {number}\n */\nconst maximalRectangle = function(matrix) {\n const m = matrix.length, n = matrix[0].length\n const left = Array(n).fill(0)\n const right = Array(n).fill(n - 1)\n const height = Array(n).fill(0)\n \n let res = 0\n \n for(let i = 0; i < m; i++) {\n let l = 0, r = n - 1\n for(let j = 0; j < n; j++) {\n if(matrix[i][j] === '1') left[j] = Math.max(left[j], l)\n else {\n left[j] = 0\n l = j + 1\n }\n }\n \n for(let j = n - 1; j >= 0; j--) {\n if(matrix[i][j] === '1') right[j] = Math.min(right[j], r)\n else {\n right[j] = n - 1\n r = j - 1\n }\n }\n\n for(let j = 0; j < n; j++) {\n height[j] = matrix[i][j] === '1' ? height[j] + 1 : 0\n res = Math.max(res, (right[j] - left[j] + 1) * height[j])\n }\n \n // console.log(left, right, height)\n }\n \n return res\n};\n\n// another\n\n\n/**\n * @param {character[][]} matrix\n * @return {number}\n */\nconst maximalRectangle = function(matrix) {\n if(matrix.length === 0) return 0;\n const m = matrix.length; // rows\n const n = matrix[0].length; // cols\n const left = new Array(n).fill(0)\n const right = new Array(n).fill(n)\n const height = new Array(n).fill(0);\n let maxA = 0;\n for(let i = 0; i < m; i++) {\n let cur_left = 0, cur_right = n;\n // compute height (can do this from either side)\n for(let j = 0; j < n; j++) {\n if(matrix[i][j] === '1') height[j]++; \n else height[j] = 0;\n }\n // compute left (from left to right)\n for(let j = 0; j < n; j++) {\n if(matrix[i][j] ==='1') left[j] = Math.max(left[j], cur_left);\n else {left[j] = 0; cur_left = j + 1;}\n }\n // compute right (from right to left)\n for(let j = n - 1; j >= 0; j--) {\n if(matrix[i][j] === '1') right[j] = Math.min(right[j], cur_right);\n else {right[j] = n; cur_right = j;} \n }\n // compute the area of rectangle (can do this from either side)\n for(let j = 0; j < n; j++) {\n maxA = Math.max(maxA, (right[j] - left[j]) * height[j]); \n }\n }\n return maxA; \n};\n\n// another\n\n/**\n * @param {character[][]} matrix\n * @return {number}\n */\nconst maximalRectangle = function(matrix) {\n if (matrix == null || matrix.length === 0 || matrix[0] == null || matrix[0].length === 0) return 0;\n let m = matrix.length, n = matrix[0].length, maxArea = 0;\n\n const left = new Array(n).fill(0)\n const right = new Array(n).fill(n - 1)\n const height = new Array(n).fill(0)\n for (let i = 0; i < m; i++) {\n let rB = n - 1;\n for (let j = n - 1; j >= 0; j--) {\n if (matrix[i][j] === '1') {\n right[j] = Math.min(right[j], rB);\n } else {\n right[j] = n - 1;\n rB = j - 1;\n }\n }\n let lB = 0;\n for (let j = 0; j < n; j++) {\n if (matrix[i][j] === '1') {\n left[j] = Math.max(left[j], lB);\n height[j]++;\n maxArea = Math.max(maxArea, height[j] * (right[j] - left[j] + 1));\n } else {\n height[j] = 0;\n left[j] = 0;\n lB = j + 1;\n }\n }\n }\n return maxArea;\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720ad9", + "questionid": 14, + "title": "Merge Two Sorted Lists", + "slug": "merge-two-sorted-lists", + "description": "You are given the heads of two sorted linked lists list1 and list2. Merge the two lists in a one sorted list. The list should be made by splicing together the nodes of the first two lists. Return the head of the merged linked list. ", + "category": [ + "Linked List", + "Recursion" + ], + "complexity": "Easy", + "successrate": 60.2, + "totalsubmissions": 3519901, + "totalaccepted": 2118031, + "likes": 11753, + "dislikes": 1070, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "list1 = [1,2,4], list2 = [1,3,4]", + "expected_output": "[1,1,2,3,4,4]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "list1 = [], list2 = []", + "expected_output": "[]", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "list1 = [], list2 = [0]", + "expected_output": "[0]", + "explanation": "" + } + ], + "solution": "/**\n * Definition for singly-linked list.\n * function ListNode(val) {\n * this.val = val;\n * this.next = null;\n * }\n */\n/**\n * @param {ListNode} l1\n * @param {ListNode} l2\n * @return {ListNode}\n */\n\nconst mergeTwoLists = function(l1, l2) {\n if (l1 === null) return l2;\n if (l2 === null) return l1;\n if (l1.val < l2.val) {\n l1.next = mergeTwoLists(l1.next, l2);\n return l1;\n } else {\n l2.next = mergeTwoLists(l1, l2.next);\n return l2;\n }\n};\n\n// another\n\n/**\n * Definition for singly-linked list.\n * function ListNode(val, next) {\n * this.val = (val===undefined ? 0 : val)\n * this.next = (next===undefined ? null : next)\n * }\n */\n/**\n * @param {ListNode} l1\n * @param {ListNode} l2\n * @return {ListNode}\n */\nconst mergeTwoLists = function(l1, l2) {\n const dummy = new ListNode()\n let cur = dummy\n while(l1 && l2) {\n if(l1.val < l2.val) {\n cur.next = new ListNode(l1.val)\n l1 = l1.next\n } else {\n cur.next = new ListNode(l2.val)\n l2 = l2.next\n }\n \n cur = cur.next\n }\n if(l1) cur.next = l1\n if(l2) cur.next = l2\n \n return dummy.next\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720adf", + "questionid": 20, + "title": "Next Permutation", + "slug": "next-permutation", + "description": "A permutation of an array of integers is an arrangement of its members into a sequence or linear order. The next permutation of an array of integers is the next lexicographically greater permutation of its integer. More formally, if all the permutations of the array are sorted in one container according to their lexicographical order, then the next permutation of that array is the permutation that follows it in the sorted container. If such arrangement is not possible, the array must be rearranged as the lowest possible order (i.e., sorted in ascending order). Given an array of integers nums, find the next permutation of nums. The replacement must be in place and use only constant extra memory. ", + "category": [ + "Array", + "Two Pointers" + ], + "complexity": "Medium", + "successrate": 36.3, + "totalsubmissions": 2166111, + "totalaccepted": 787106, + "likes": 10346, + "dislikes": 3360, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,2,3]", + "expected_output": "[1,3,2]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "nums = [3,2,1]", + "expected_output": "[1,2,3]", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "nums = [1,1,5]", + "expected_output": "[1,5,1]", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} nums\n * @return {void} Do not return anything, modify nums in-place instead.\n */\nconst nextPermutation = function(nums) {\n const n = nums.length\n let k = null\n for(let i = n - 2; i >= 0; i--) {\n if(nums[i] < nums[i + 1]) {\n k = i\n break\n }\n }\n if(k == null) {\n reverse(nums, 0, n - 1)\n } else {\n let end\n for(let i = n - 1; i >= 0; i--) {\n if(nums[i] > nums[k]) {\n end = i\n break\n }\n }\n swap(nums, k, end)\n reverse(nums, k + 1, n - 1)\n }\n \n function reverse(arr, start, end) {\n while(start < end) {\n swap(arr, start, end)\n start++\n end--\n }\n }\n \n function swap(arr, i, j) {\n ;[arr[i], arr[j]] = [arr[j], arr[i]];\n }\n};\n\n// another\n\n\n/**\n * @param {number[]} nums\n * @return {void} Do not return anything, modify nums in-place instead.\n */\nconst nextPermutation = function(nums) {\n let i = nums.length - 2;\n while (i >= 0 && nums[i + 1] <= nums[i]) {\n i--;\n }\n if (i >= 0) {\n let j = nums.length - 1;\n while (j >= 0 && nums[j] <= nums[i]) {\n j--;\n }\n swap(nums, i, j);\n }\n reverse(nums, i + 1);\n \n};\n\nfunction reverse(nums, start) {\n let i = start, j = nums.length - 1;\n while (i < j) {\n swap(nums, i, j);\n i++;\n j--;\n }\n}\n\nfunction swap(arr, i, j) {\n arr[i] ^= arr[j];\n arr[j] ^= arr[i];\n arr[i] ^= arr[j];\n}\n\n// another\n\n/**\n * @param {number[]} nums\n * @return {void} Do not return anything, modify nums in-place instead.\n */\nconst nextPermutation = function(nums) {\n const n = nums.length\n let start, end\n for(let i = n - 2; i >= 0; i--) {\n if(nums[i] < nums[i + 1]) {\n start = i\n break\n }\n }\n if(start == null) {\n reverse(nums, 0, n - 1)\n } else {\n for(let i = n - 1; i >= 0; i--) {\n if(nums[i] > nums[start]) {\n end = i\n break\n }\n }\n swap(nums, start, end)\n reverse(nums, start + 1, n - 1)\n }\n};\nfunction reverse(arr, start, end) {\n while(start < end) {\n swap(arr, start++, end--)\n }\n}\nfunction swap(arr, i, j) {\n const tmp = arr[i]\n arr[i] = arr[j]\n arr[j] = tmp\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720ae0", + "questionid": 21, + "title": "Longest Valid Parentheses", + "slug": "longest-valid-parentheses", + "description": "Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring. ", + "category": [ + "String", + "Dynamic Programming", + "Stack" + ], + "complexity": "Hard", + "successrate": 31.2, + "totalsubmissions": 1518755, + "totalaccepted": 474545, + "likes": 7527, + "dislikes": 256, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "(()"", + "expected_output": "2", + "explanation": "The longest valid parentheses substring is "()"." + }, + { + "example_num": 2, + "expected_input": "s = ")()())"", + "expected_output": "4", + "explanation": "The longest valid parentheses substring is "()()"." + }, + { + "example_num": 3, + "expected_input": "s = """, + "expected_output": "0", + "explanation": "" + } + ], + "solution": "/**\n * @param {string} s\n * @return {number}\n */\nconst longestValidParentheses = function(s) {\n const arr = s.split(\"\")\n const dp = new Array(arr.length).fill(0)\n let open = 0\n let max = 0\n for (let i = 0; i < arr.length; i++) {\n if (arr[i] === \"(\") open++\n if (arr[i] === \")\" && open > 0) {\n dp[i] = 2 + dp[i - 1]\n if (i - dp[i] > 0) dp[i] += dp[i - dp[i]]\n open--\n }\n if (dp[i] > max) max = dp[i]\n }\n return max\n}\n\n// another\n\nconst longestValidParentheses = function(s) {\n let longest = 0\n let stack = [-1]\n for (let i = 0; i < s.length; i++) {\n if (s[i] === \"(\") {\n stack.push(i)\n } else {\n stack.pop()\n if (!stack.length) stack.push(i)\n else longest = Math.max(longest, i - stack[stack.length - 1])\n }\n }\n\n return longest\n}\n\n// another\n\n/**\n * @param {string} s\n * @return {number}\n */\nconst longestValidParentheses = function (s) {\n let res = 0,\n stk = [],\n n = s.length,\n idxStk = []\n for (let i = 0; i < n; i++) {\n const ch = s[i]\n if (stk.length && stk[stk.length - 1] === '(' && ch === ')')\n stk.pop(), idxStk.pop()\n else stk.push(ch), idxStk.push(i)\n res = Math.max(res, i - (idxStk.length ? idxStk[idxStk.length - 1] : -1))\n }\n return res\n}\n/**\n * @param {string} s\n * @return {number}\n */\nconst longestValidParentheses = function (s) {\n let res = 0,\n stk = [],\n n = s.length,\n idxStk = []\n for (let i = 0; i < n; i++) {\n const ch = s[i]\n if (stk.length && stk[stk.length - 1] === '(' && ch === ')')\n stk.pop(), idxStk.pop()\n else stk.push(ch), idxStk.push(i)\n res = Math.max(res, i - (idxStk.length ? idxStk[idxStk.length - 1] : -1))\n }\n return res\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720aeb", + "questionid": 32, + "title": "Group Anagrams", + "slug": "group-anagrams", + "description": "Given an array of strings strs, group the anagrams together. You can return the answer in any order. An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. ", + "category": [ + "Hash Table", + "String", + "Sorting" + ], + "complexity": "Medium", + "successrate": 64, + "totalsubmissions": 2043076, + "totalaccepted": 1307071, + "likes": 8945, + "dislikes": 308, + "hints": "", + "deleted": false, + "examples": [], + "solution": "/**\n * @param {string[]} strs\n * @return {string[][]}\n */\nconst groupAnagrams = (strs) => {\n const resp = new Array(),\n termsGrouped = new Map()\n strs.forEach((term) => {\n const hashed = hash(term)\n if (!termsGrouped.has(hashed)) termsGrouped.set(hashed, new Array())\n termsGrouped.get(hashed).push(term)\n })\n termsGrouped.forEach((terms) => {\n resp.push(terms)\n })\n return resp\n}\n\nconst hash = (term) => {\n const arr = Array(26).fill(0)\n const a = 'a'.charCodeAt(0)\n for(let i = 0, len = term.length; i < len; i++) {\n arr[term[i].charCodeAt(0) - a]++\n }\n return arr.join('-')\n}\n\n// another\n\n/**\n * @param {string[]} strs\n * @return {string[][]}\n */\nconst groupAnagrams = function(strs) {\n if (strs.length === 0) {\n return [];\n }\n const ans = [];\n const hash = {};\n for (let el of strs) {\n let sel = el\n .split(\"\")\n .sort()\n .join(\"\");\n if (hash.hasOwnProperty(sel)) {\n hash[sel].push(el);\n } else {\n hash[sel] = [el];\n }\n }\n return Object.values(hash);\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720aec", + "questionid": 33, + "title": "Pow(x, n)", + "slug": "powx-n", + "description": "Implement pow(x, n), which calculates x raised to the power n (i.e., xn). ", + "category": [ + "Math", + "Recursion" + ], + "complexity": "Medium", + "successrate": 32.3, + "totalsubmissions": 2733809, + "totalaccepted": 883674, + "likes": 4323, + "dislikes": 5309, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "x = 2.00000, n = 10", + "expected_output": "1024.00000", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "x = 2.10000, n = 3", + "expected_output": "9.26100", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "x = 2.00000, n = -2", + "expected_output": "0.25000", + "explanation": "2-2 = 1/22 = 1/4 = 0.25" + } + ], + "solution": "/**\n * @param {number} x\n * @param {number} n\n * @return {number}\n */\nconst myPow = function(x, n) {\n if (n === 0) return 1;\n if (n === 1) return x;\n if (x === 0) return 0;\n\n if (n > 0) {\n return (n % 2 === 1 ? x : 1) * myPow(x * x, Math.floor(n / 2));\n } else {\n return myPow(1 / x, -n);\n }\n};\n\n// another\n\n/**\n * @param {number} x\n * @param {number} n\n * @return {number}\n */\nconst myPow = function(x, n) {\n if(n === 0) return 1\n if(n === 1) return x\n if(n < 0) {\n x = 1 / x\n n = -n\n }\n return n % 2 === 1 ? myPow(x, ~~(n / 2)) ** 2 * x : myPow(x, ~~(n / 2)) ** 2\n};\n\n// another\n\n/**\n * @param {number} x\n * @param {number} n\n * @return {number}\n */\nconst myPow = function (x, n) {\n if (n === 0) return 1\n if (n < 0) {\n if (n === -(2 ** 31)) {\n ++n\n n = -n\n x = 1 / x\n return x * x * myPow(x * x, n / 2)\n }\n n = -n\n x = 1 / x\n }\n return n % 2 == 0 ? myPow(x * x, n / 2) : x * myPow(x * x, (n / 2) >> 0)\n}\n\n// another\n\n/**\n * @param {number} x\n * @param {number} n\n * @return {number}\n */\nconst myPow = function (x, n) {\n if (n === 0) return 1\n if (n < 0) {\n n = -n\n x = 1 / x\n }\n let res = 1\n while (n > 0) {\n if (n & 1) {\n res *= x\n --n\n }\n x *= x\n n /= 2\n }\n return res\n}\n\n" + }, + { + "_id": "66f925ddfdfb8e1665720aed", + "questionid": 34, + "title": "N-Queens", + "slug": "n-queens", + "description": "The n-queens puzzle is the problem of placing n queens on an n x n chessboard such that no two queens attack each other. Given an integer n, return all distinct solutions to the n-queens puzzle. You may return the answer in any order. Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space, respectively. ", + "category": [ + "Array", + "Backtracking" + ], + "complexity": "Hard", + "successrate": 57.2, + "totalsubmissions": 625138, + "totalaccepted": 357360, + "likes": 5603, + "dislikes": 152, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 4", + "expected_output": "[[".Q..","...Q","Q...","..Q."],["..Q.","Q...","...Q",".Q.."]]", + "explanation": "There exist two distinct solutions to the 4-queens puzzle as shown above" + }, + { + "example_num": 2, + "expected_input": "n = 1", + "expected_output": "[["Q"]]", + "explanation": "" + } + ], + "solution": "/**\n * @param {number} n\n * @return {string[][]}\n */\nconst solveNQueens = function(n) {\n const res = []\n const chess = Array.from({length: n}, () => new Array(n).fill('.'))\n bt(res, chess, 0)\n return res\n}\n\nfunction bt(res, chess, row) {\n if(row === chess.length) {\n res.push(build(chess))\n return\n }\n for(let i = 0, num = chess[0].length; i < num; i++) {\n if(valid(chess, row, i)) {\n chess[row][i] = 'Q'\n bt(res, chess, row + 1)\n chess[row][i] = '.'\n }\n }\n}\n\nfunction valid(chess, row, col) {\n for(let i = row - 1; i >= 0; i--) {\n if(chess[i][col] === 'Q') return false\n }\n for(let i = row - 1, j = col - 1; i >= 0 && j >= 0; i--, j--) {\n if(chess[i][j] === 'Q') return false\n }\n for(let i = row - 1, j = col + 1; i >= 0 && j < chess[0].length; i--, j++) {\n if(chess[i][j] === 'Q') return false\n }\n return true\n}\n\nfunction build(chess) {\n return chess.map(el => el.join(''))\n}\n\n// another\n\n/**\n * @param {number} n\n * @return {string[][]}\n */\nconst solveNQueens = function(n) {\n const res = []\n bt(res, n)\n return res\n}\n\nfunction bt(res, n, board = [], r = 0) {\n if (r === n) {\n res.push(board.map(c => '.'.repeat(c) + 'Q' + '.'.repeat(n - c - 1)))\n return\n }\n for (let c = 0; c < n; c++) {\n if (\n !board.some(\n (bc, br) => bc === c || bc === c + r - br || bc === c - r + br\n )\n ) {\n board.push(c)\n bt(res, n, board, r + 1)\n board.pop()\n }\n }\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720aee", + "questionid": 35, + "title": "N-Queens II", + "slug": "n-queens-ii", + "description": "The n-queens puzzle is the problem of placing n queens on an n x n chessboard such that no two queens attack each other. Given an integer n, return the number of distinct solutions to the\u00a0n-queens puzzle. ", + "category": [ + "Backtracking" + ], + "complexity": "Hard", + "successrate": 66.1, + "totalsubmissions": 327225, + "totalaccepted": 216188, + "likes": 1670, + "dislikes": 209, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 4", + "expected_output": "2", + "explanation": "There are two distinct solutions to the 4-queens puzzle as shown." + }, + { + "example_num": 2, + "expected_input": "n = 1", + "expected_output": "1", + "explanation": "" + } + ], + "solution": null + }, + { + "_id": "66f925ddfdfb8e1665720af5", + "questionid": 42, + "title": "Spiral Matrix II", + "slug": "spiral-matrix-ii", + "description": "Given a positive integer n, generate an n x n matrix filled with elements from 1 to n2 in spiral order. ", + "category": [ + "Array", + "Matrix", + "Simulation" + ], + "complexity": "Medium", + "successrate": 64.7, + "totalsubmissions": 549056, + "totalaccepted": 355230, + "likes": 3579, + "dislikes": 180, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 3", + "expected_output": "[[1,2,3],[8,9,4],[7,6,5]]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "n = 1", + "expected_output": "[[1]]", + "explanation": "" + } + ], + "solution": null + }, + { + "_id": "66f925ddfdfb8e1665720af8", + "questionid": 45, + "title": "Unique Paths II", + "slug": "unique-paths-ii", + "description": "You are given an m x n integer array grid. There is a robot initially located at the top-left corner (i.e., grid[0][0]). The robot tries to move to the bottom-right corner (i.e., grid[m-1][n-1]). The robot can only move either down or right at any point in time. An obstacle and space are marked as 1 or 0 respectively in grid. A path that the robot takes cannot include any square that is an obstacle. Return the number of possible unique paths that the robot can take to reach the bottom-right corner. The testcases are generated so that the answer will be less than or equal to 2 * 109. ", + "category": [ + "Array", + "Dynamic Programming", + "Matrix" + ], + "complexity": "Medium", + "successrate": 37.5, + "totalsubmissions": 1331781, + "totalaccepted": 499048, + "likes": 4533, + "dislikes": 371, + "hints": "The robot can only move either down or right. Hence any cell in the first row can only be reached from the cell left to it. However, if any cell has an obstacle, you don't let that cell contribute to any path. So, for the first row, the number of ways will simply be \r\n\r\n\r\nif obstacleGrid[i][j] is not an obstacle\r\n obstacleGrid[i,j] = obstacleGrid[i,j - 1] \r\nelse\r\n obstacleGrid[i,j] = 0\r\n\r\n\r\nYou can do a similar processing for finding out the number of ways of reaching the cells in the first column. For any other cell, we can find out the number of ways of reaching it, by making use of the number of ways of reaching the cell directly above it and the cell to the left of it in the grid. This is because these are the only two directions from which the robot can come to the current cell. Since we are making use of pre-computed values along the iteration, this becomes a dynamic programming problem.\r\n\r\n\r\nif obstacleGrid[i][j] is not an obstacle\r\n obstacleGrid[i,j] = obstacleGrid[i,j - 1] + obstacleGrid[i - 1][j]\r\nelse\r\n obstacleGrid[i,j] = 0", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "obstacleGrid = [[0,0,0],[0,1,0],[0,0,0]]", + "expected_output": "2", + "explanation": "There is one obstacle in the middle of the 3x3 grid above.\nThere are two ways to reach the bottom-right corner:\n1. Right -> Right -> Down -> Down\n2. Down -> Down -> Right -> Right" + }, + { + "example_num": 2, + "expected_input": "obstacleGrid = [[0,1],[0,0]]", + "expected_output": "1", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[][]} obstacleGrid\n * @return {number}\n */\nconst uniquePathsWithObstacles = function(obstacleGrid) {\n const rows = obstacleGrid.length\n const cols = obstacleGrid[0].length\n const dp = Array.from({ length: rows }, () => new Array(cols).fill(0))\n if (obstacleGrid[0][0] === 1) return 0\n else dp[0][0] = 1\n let firstRowOneIdx\n let firstColOneIdx\n for (let i = 0; i < cols; i++) {\n if (obstacleGrid[0][i] === 1) {\n firstRowOneIdx = i\n break\n } else {\n dp[0][i] = 1\n }\n }\n for (let i = 0; i < rows; i++) {\n if (obstacleGrid[i][0] === 1) {\n firstColOneIdx = i\n break\n } else {\n dp[i][0] = 1\n }\n }\n\n for (let i = 1; i < rows; i++) {\n for (let j = 1; j < cols; j++) {\n if (obstacleGrid[i][j] !== 1) {\n dp[i][j] = dp[i - 1][j] + dp[i][j - 1]\n }\n }\n }\n return dp[rows - 1][cols - 1]\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720afc", + "questionid": 49, + "title": "Set Matrix Zeroes", + "slug": "set-matrix-zeroes", + "description": "Given an m x n integer matrix matrix, if an element is 0, set its entire row and column to 0's. You must do it in place. ", + "category": [ + "Array", + "Hash Table", + "Matrix" + ], + "complexity": "Medium", + "successrate": 48.2, + "totalsubmissions": 1379982, + "totalaccepted": 664738, + "likes": 6658, + "dislikes": 481, + "hints": "If any cell of the matrix has a zero we can record its row and column number using additional memory.\r\nBut if you don't want to use extra memory then you can manipulate the array instead. i.e. simulating exactly what the question says. Setting cell values to zero on the fly while iterating might lead to discrepancies. What if you use some other integer value as your marker?\r\nThere is still a better approach for this problem with 0(1) space. We could have used 2 sets to keep a record of rows/columns which need to be set to zero. But for an O(1) space solution, you can use one of the rows and and one of the columns to keep track of this information. We can use the first cell of every row and column as a flag. This flag would determine whether a row or column has been set to zero.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "matrix = [[1,1,1],[1,0,1],[1,1,1]]", + "expected_output": "[[1,0,1],[0,0,0],[1,0,1]]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "matrix = [[0,1,2,0],[3,4,5,2],[1,3,1,5]]", + "expected_output": "[[0,0,0,0],[0,4,5,0],[0,3,1,0]]", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[][]} matrix\n * @return {void} Do not return anything, modify matrix in-place instead.\n */\nconst setZeroes = function(matrix) {\n const rows = []\n const cols = []\n const rowNum = matrix.length\n const colNum = matrix[0].length\n for(let i = 0; i < rowNum; i++) {\n for(let j = 0; j < colNum; j++) {\n if(matrix[i][j] === 0) {\n rows.push(i)\n cols.push(j)\n }\n }\n }\n const mrows = rows.filter((el, idx, arr) => arr.indexOf(el) === idx)\n const mcols = cols.filter((el, idx, arr) => arr.indexOf(el) === idx)\n for(let i = 0; i < mrows.length; i++) {\n matrix[mrows[i]] = new Array(colNum).fill(0)\n }\n for(let j = 0; j < mcols.length; j++) {\n for(let k = 0; k < rowNum; k++) {\n matrix[k][mcols[j]] = 0\n }\n }\n return matrix\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720afe", + "questionid": 51, + "title": "Minimum Window Substring", + "slug": "minimum-window-substring", + "description": "Given two strings s and t of lengths m and n respectively, return the minimum window substring of s such that every character in t (including duplicates) is included in the window. If there is no such substring, return the empty string \"\". The testcases will be generated such that the answer is unique. A substring is a contiguous sequence of characters within the string. ", + "category": [ + "Hash Table", + "String", + "Sliding Window" + ], + "complexity": "Hard", + "successrate": 38.9, + "totalsubmissions": 1890669, + "totalaccepted": 735482, + "likes": 9964, + "dislikes": 529, + "hints": "Use two pointers to create a window of letters in S, which would have all the characters from T. Since you have to find the minimum window in S which has all the characters from T, you need to expand and contract the window using the two pointers and keep checking the window for all the characters. This approach is also called Sliding Window Approach.\r\n\r\n\n\r\nL ------------------------ R , Suppose this is the window that contains all characters of T \r\n \r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 L----------------- R , this is the contracted window. We found a smaller window that still contains all the characters in T\r\n\r\nWhen the window is no longer valid, start expanding again using the right pointer.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "ADOBECODEBANC", t = "ABC"", + "expected_output": ""BANC"", + "explanation": "The minimum window substring "BANC" includes 'A', 'B', and 'C' from string t." + }, + { + "example_num": 2, + "expected_input": "s = "a", t = "a"", + "expected_output": ""a"", + "explanation": "The entire string s is the minimum window." + }, + { + "example_num": 3, + "expected_input": "s = "a", t = "aa"", + "expected_output": """", + "explanation": "Both 'a's from t must be included in the window.\nSince the largest window of s only has one 'a', return empty string." + } + ], + "solution": "/**\n * @param {string} s\n * @param {string} t\n * @return {string}\n */\nvar minWindow = function(s, t) {\n const a = 'a'.charCodeAt(0)\n const A = 'A'.charCodeAt(0)\n const arr = new Array(52).fill(0)\n const n = s.length\n const idx = (ch) => {\n const code = ch.charCodeAt(0)\n return code - (code >= a ? a : A) + (code >= a ? 26 : 0)\n }\n for (const ch of t) {\n arr[idx(ch)]++\n }\n let l = 0, r = 0\n let res = ''\n while(r < n) {\n const i = idx(s[r])\n arr[i]--\n while(l < r && arr[idx(s[l])] < 0) {\n arr[idx(s[l])]++\n l++\n }\n const tmp = s.slice(l, r + 1)\n if(arr.every(x => x <= 0) && (res === '' || tmp.length < res.length)) {\n res = tmp\n }\n r++\n }\n\n return res\n};\n\n// another\n\n/**\n * @param {string} s\n * @param {string} t\n * @return {string}\n */\nconst minWindow = function(s, t) {\n const map = {}\n for (const c of t) {\n map[c] = (map[c] || 0) + 1\n }\n let counter = t.length\n let start = 0\n let end = 0\n let minLen = Infinity\n let minStart = 0\n while (end < s.length) {\n const eChar = s[end]\n if (map[eChar] > 0) {\n counter--\n }\n map[eChar] = (map[eChar] || 0) - 1\n end++\n while (counter === 0) {\n if (end - start < minLen) {\n minStart = start\n minLen = end - start\n }\n const sChar = s[start]\n map[sChar] = (map[sChar] || 0) + 1\n if (map[sChar] > 0) {\n counter++\n }\n start++\n }\n }\n if (minLen !== Infinity) {\n return s.substring(minStart, minStart + minLen)\n }\n return ''\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720b07", + "questionid": 60, + "title": "Partition List", + "slug": "partition-list", + "description": "Given the head of a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x. You should preserve the original relative order of the nodes in each of the two partitions. ", + "category": [ + "Linked List", + "Two Pointers" + ], + "complexity": "Medium", + "successrate": 47.8, + "totalsubmissions": 703320, + "totalaccepted": 335965, + "likes": 3376, + "dislikes": 474, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "head = [1,4,3,2,5,2], x = 3", + "expected_output": "[1,2,2,4,3,5]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "head = [2,1], x = 2", + "expected_output": "[1,2]", + "explanation": "" + } + ], + "solution": "/**\n * Definition for singly-linked list.\n * function ListNode(val) {\n * this.val = val;\n * this.next = null;\n * }\n */\n/**\n * @param {ListNode} head\n * @param {number} x\n * @return {ListNode}\n */\nconst partition = function(head, x) {\n const leftHead = new ListNode(); \n const rightHead = new ListNode(); \n let left = leftHead;\n let right = rightHead;\n \n // split list into two sides, left if val < x, else right\n for (let node = head; node !== null; node = node.next) {\n if (node.val < x) {\n left.next = node;\n left = node;\n } else {\n right.next = node;\n right = node;\n }\n }\n \n // combine the two sides\n left.next = rightHead.next;\n right.next = null;\n \n return leftHead.next;\n};\n\n// another\n\n/**\n * Definition for singly-linked list.\n * function ListNode(val) {\n * this.val = val;\n * this.next = null;\n * }\n */\n/**\n * @param {ListNode} head\n * @param {number} x\n * @return {ListNode}\n */\nconst partition = function(head, x) {\n const left = []\n const right = []\n let containX = false\n let cur = head\n while(cur !== null) {\n if (containX === true) {\n if (cur.val < x) {\n left.push(cur)\n } else {\n right.push(cur)\n }\n } else {\n if (cur.val >= x) {\n containX = true\n right.push(cur)\n } else {\n left.push(cur)\n }\n }\n cur = cur.next\n }\n const arr = left.concat(right)\n \n for(let i = 0; i < arr.length; i++) {\n if (i === arr.length - 1) {\n arr[i].next = null\n } else {\n arr[i].next = arr[i+1]\n }\n }\n return arr[0] == null ? null : arr[0]\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720b09", + "questionid": 62, + "title": "Subsets II", + "slug": "subsets-ii", + "description": "Given an integer array nums that may contain duplicates, return all possible subsets (the power set). The solution set must not contain duplicate subsets. Return the solution in any order. ", + "category": [ + "Array", + "Backtracking", + "Bit Manipulation" + ], + "complexity": "Medium", + "successrate": 53.1, + "totalsubmissions": 924788, + "totalaccepted": 491045, + "likes": 4830, + "dislikes": 149, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,2,2]", + "expected_output": "[[],[1],[1,2],[1,2,2],[2],[2,2]]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "nums = [0]", + "expected_output": "[[],[0]]", + "explanation": "" + } + ], + "solution": null + }, + { + "_id": "66f925ddfdfb8e1665720b0b", + "questionid": 64, + "title": "Restore IP Addresses", + "slug": "restore-ip-addresses", + "description": "A valid IP address consists of exactly four integers separated by single dots. Each integer is between 0 and 255 (inclusive) and cannot have leading zeros. Given a string s containing only digits, return all possible valid IP addresses that can be formed by inserting dots into s. You are not allowed to reorder or remove any digits in s. You may return the valid IP addresses in any order. ", + "category": [ + "String", + "Backtracking" + ], + "complexity": "Medium", + "successrate": 41.7, + "totalsubmissions": 705550, + "totalaccepted": 294170, + "likes": 2649, + "dislikes": 624, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "25525511135"", + "expected_output": "["255.255.11.135","255.255.111.35"]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "s = "0000"", + "expected_output": "["0.0.0.0"]", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "s = "101023"", + "expected_output": "["1.0.10.23","1.0.102.3","10.1.0.23","10.10.2.3","101.0.2.3"]", + "explanation": "" + } + ], + "solution": "/**\n * @param {string} s\n * @return {string[]}\n */\nconst restoreIpAddresses = function(s) {\n if (s.length < 4 || s.length > 12) return [];\n const res = [];\n let ans = \"\";\n for (let a = 1; a <= 3; a++) {\n for (let b = 1; b <= 3; b++) {\n for (let c = 1; c <= 3; c++) {\n for (let d = 1; d <= 3; d++) {\n if (a + b + c + d === s.length) {\n let A = +s.substr(0, a);\n let B = +s.substr(a, b);\n let C = +s.substr(a + b, c);\n let D = +s.substr(a + b + c, d);\n if (A <= 255 && B <= 255 && C <= 255 && D <= 255) {\n if (\n ((ans = A + \".\" + B + \".\" + C + \".\" + D).length === s.length + 3)\n ) {\n res.push(ans);\n }\n }\n }\n }\n }\n }\n }\n return res;\n};\n\n// another method\n\n/**\n * @param {string} s\n * @return {string[]}\n */\nconst restoreIpAddresses = function(s) {\n const ans = [];\n const stack = [];\n let ipstr;\n const len = s.length;\n function restoreIp(start) {\n if (stack.length > 4) return;\n if (stack.length === 4 && start > len - 1) {\n ans.push(stack.slice().join(\".\"));\n return;\n }\n for (let i = start; i < start + 3; i++) {\n if (i > len - 1) return;\n ipstr = s.substring(start, i + 1);\n if ((ipstr[0] === \"0\" && ipstr.length !== 1) || ipstr > 255) return;\n stack.push(ipstr);\n restoreIp(i + 1);\n stack.pop();\n }\n }\n restoreIp(0);\n return ans;\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720acd", + "questionid": 2, + "title": "Add Two Numbers", + "slug": "add-two-numbers", + "description": "You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum\u00a0as a linked list. You may assume the two numbers do not contain any leading zero, except the number 0 itself. ", + "category": [ + "Linked List", + "Math", + "Recursion" + ], + "complexity": "Medium", + "successrate": 38.5, + "totalsubmissions": 6987977, + "totalaccepted": 2690949, + "likes": 17799, + "dislikes": 3682, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "l1 = [2,4,3], l2 = [5,6,4]", + "expected_output": "[7,0,8]", + "explanation": "342 + 465 = 807." + }, + { + "example_num": 2, + "expected_input": "l1 = [0], l2 = [0]", + "expected_output": "[0]", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]", + "expected_output": "[8,9,9,9,0,0,0,1]", + "explanation": "" + } + ], + "solution": "/**\n * Definition for singly-linked list.\n * function ListNode(val, next) {\n * this.val = (val===undefined ? 0 : val)\n * this.next = (next===undefined ? null : next)\n * }\n */\n/**\n * @param {ListNode} l1\n * @param {ListNode} l2\n * @return {ListNode}\n */\nconst addTwoNumbers = function(l1, l2) {\n let res = new ListNode(null)\n let inc = false\n let cur = res\n while(l1 || l2 || inc) {\n const tmp = ((l1 && l1.val) || 0) + ((l2 && l2.val) || 0) + (inc ? 1 : 0)\n if(tmp >= 10) inc = true\n else inc = false\n cur.next = new ListNode(tmp % 10)\n cur = cur.next\n if(l1) l1 = l1.next\n if(l2) l2 = l2.next\n }\n \n return res.next\n};\n\n// another\n\n/**\n * Definition for singly-linked list.\n * function ListNode(val) {\n * this.val = val;\n * this.next = null;\n * }\n */\n/**\n * @param {ListNode} l1\n * @param {ListNode} l2\n * @return {ListNode}\n */\nconst addTwoNumbers = function(l1, l2) {\n const res = new ListNode(null);\n single(l1, l2, res);\n return res.next;\n};\n\nfunction single(l1, l2, res) {\n let cur;\n let addOne = 0;\n let sum = 0;\n let curVal = 0;\n while (l1 || l2 || addOne) {\n sum = ((l1 && l1.val) || 0) + ((l2 && l2.val) || 0) + addOne;\n if (sum / 10 >= 1) {\n curVal = sum % 10;\n addOne = 1;\n } else {\n curVal = sum;\n addOne = 0;\n }\n\n if (cur) {\n cur = cur.next = new ListNode(curVal);\n } else {\n cur = res.next = new ListNode(curVal);\n }\n\n if (l1) {\n l1 = l1.next;\n }\n if (l2) {\n l2 = l2.next;\n }\n }\n}\n\n// another\n\n/**\n * Definition for singly-linked list.\n * function ListNode(val, next) {\n * this.val = (val===undefined ? 0 : val)\n * this.next = (next===undefined ? null : next)\n * }\n */\n/**\n * @param {ListNode} l1\n * @param {ListNode} l2\n * @return {ListNode}\n */\nconst addTwoNumbers = function(l1, l2) {\n let extra = false\n const dummy = new ListNode()\n let cur = dummy\n while(l1 || l2) {\n let val = 0\n if(l1) val += l1.val\n if(l2) val += l2.val\n if(extra) val += 1\n \n if(val > 9) {\n extra = true\n val = val % 10\n } else {\n extra = false\n }\n cur.next = new ListNode(val)\n cur = cur.next\n if(l1) l1 = l1.next\n if(l2) l2 = l2.next\n }\n\n if(extra) cur.next = new ListNode(1)\n return dummy.next\n};\n\n// another\n\n/**\n * Definition for singly-linked list.\n * function ListNode(val, next) {\n * this.val = (val===undefined ? 0 : val)\n * this.next = (next===undefined ? null : next)\n * }\n */\n/**\n * @param {ListNode} l1\n * @param {ListNode} l2\n * @return {ListNode}\n */\nconst addTwoNumbers = function(l1, l2) {\n const dummy = new ListNode(null)\n let cur = dummy, carry = 0\n \n while(l1 || l2) {\n let v = 0\n if(l1 && l2) {\n v = l1.val + l2.val + carry\n l1 = l1.next\n l2 = l2.next\n } else {\n const node = l1 || l2\n v = node.val + carry\n if(l1) l1 = l1.next\n if(l2) l2 = l2.next\n }\n \n cur.next = new ListNode(v % 10)\n cur = cur.next\n if(v >= 10) carry = 1\n else carry = 0\n }\n \n if(carry) cur.next = new ListNode(1)\n \n return dummy.next\n};\n\n" + }, + { + "_id": "66f925ddfdfb8e1665720ace", + "questionid": 3, + "title": "Longest Substring Without Repeating Characters", + "slug": "longest-substring-without-repeating-characters", + "description": "Given a string s, find the length of the longest substring without repeating characters. ", + "category": [ + "Hash Table", + "String", + "Sliding Window" + ], + "complexity": "Medium", + "successrate": 33, + "totalsubmissions": 9621884, + "totalaccepted": 3175843, + "likes": 22941, + "dislikes": 1027, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "abcabcbb"", + "expected_output": "3", + "explanation": "The answer is "abc", with the length of 3." + }, + { + "example_num": 2, + "expected_input": "s = "bbbbb"", + "expected_output": "1", + "explanation": "The answer is "b", with the length of 1." + }, + { + "example_num": 3, + "expected_input": "s = "pwwkew"", + "expected_output": "3", + "explanation": "The answer is "wke", with the length of 3.\nNotice that the answer must be a substring, "pwke" is a subsequence and not a substring." + } + ], + "solution": "/**\n * @param {string} s\n * @return {number}\n */\nconst lengthOfLongestSubstring = function(s) {\n const n = s.length, hash = {}\n let res = 0\n let i = -1\n for(j = 0;j < n; j++) {\n const e = s[j]\n if(hash[e] != null) i = Math.max(i, hash[e])\n hash[e] = j\n res = Math.max(res, j - i)\n }\n \n return res\n};\n\n\n// another\n\n/**\n * @param {string} s\n * @return {number}\n */\nconst lengthOfLongestSubstring = function(s) {\n if(s.length < 2) return s.length\n const hash = {}\n let max = 0\n for(let i = 0, j = -1, len = s.length; i < len; i++) {\n const cur = s[i]\n if(hash[cur] != null) j = Math.max(j, hash[cur])\n \n hash[cur] = i\n max = Math.max(max, i - j)\n }\n \n return max\n};\n\n// another\n\n/**\n * @param {string} s\n * @return {number}\n */\nconst lengthOfLongestSubstring = function(s) {\n const n = s.length, hash = {}\n let res = 0\n let l = 0, r = 0\n while(r < n) {\n const ch = s[r]\n if(hash[ch] == null) hash[ch] = 0\n hash[ch]++\n while(hash[s[l]] > 1) {\n hash[s[l]]--\n l++\n }\n while(l <= r && Object.keys(hash).length !== r - l + 1) {\n hash[s[l]]--\n if(hash[s[l]] === 0) delete hash[s[l]]\n l++\n }\n res = Math.max(res, r - l + 1)\n r++\n }\n\n return res\n};\n\n// another\n\n/**\n * @param {string} s\n * @return {number}\n */\nconst lengthOfLongestSubstring = function(s) {\n // var p=0, q=0; //p: start of the sub, q: end of the queue\n\n //hashmap in js????? Array.indexOf\n const sub = [];\n let max = 0;\n\n for (let i = 0; i < s.length; i++) {\n let index = sub.indexOf(s.charAt(i));\n if (index == -1) {\n sub.push(s.charAt(i));\n // q++;\n } else {\n //find repeat, get index of repeat el, remve all el before that index\n sub = sub.slice(index + 1, sub.length);\n sub.push(s.charAt(i));\n }\n max = Math.max(max, sub.length);\n }\n return max;\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720ad3", + "questionid": 8, + "title": "Container With Most Water", + "slug": "container-with-most-water", + "description": "You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the ith line are (i, 0) and (i, height[i]). Find two lines that together with the x-axis form a container, such that the container contains the most water. Return the maximum amount of water a container can store. Notice that you may not slant the container. ", + "category": [ + "Array", + "Two Pointers", + "Greedy" + ], + "complexity": "Medium", + "successrate": 53.9, + "totalsubmissions": 2673605, + "totalaccepted": 1441824, + "likes": 16437, + "dislikes": 930, + "hints": "The aim is to maximize the area formed between the vertical lines. The area of any container is calculated using the shorter line as length and the distance between the lines as the width of the rectangle.\r\n\r\n\r\nArea = length of shorter vertical line * distance between lines\r\n\r\n\r\nWe can definitely get the maximum width container as the outermost lines have the maximum distance between them. However, this container might not be the maximum in size as one of the vertical lines of this container could be really short. Start with the maximum width container and go to a shorter width container if there is a vertical line longer than the current containers shorter line. This way we are compromising on the width but we are looking forward to a longer length container.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "height = [1,8,6,2,5,4,8,3,7]", + "expected_output": "49", + "explanation": "The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49." + }, + { + "example_num": 2, + "expected_input": "height = [1,1]", + "expected_output": "1", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} height\n * @return {number}\n */\nconst maxArea = function(height) {\n let res = 0, l = 0, r = height.length - 1\n while(l < r) {\n const tmp = (r - l) * Math.min(height[l], height[r])\n if(tmp > res) res = tmp\n if(height[l] < height[r]) l++\n else r--\n }\n return res\n};\n\n// another\n\n/**\n * @param {number[]} height\n * @return {number}\n */\nconst maxArea = function(height) {\n const n = height.length, {min,max} = Math\n let i = 0, j = n - 1, leftMax = height[i], rightMax = height[j]\n let res = 0\n while(i < j) {\n res = max(res, (j - i) * min(leftMax, rightMax))\n if(leftMax <= rightMax) {\n i++\n leftMax = max(leftMax, height[i])\n } else {\n j--\n rightMax = max(rightMax, height[j])\n }\n }\n \n return res\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720ad4", + "questionid": 9, + "title": "Longest Common Prefix", + "slug": "longest-common-prefix", + "description": "Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string \"\". ", + "category": [ + "String" + ], + "complexity": "Easy", + "successrate": 39.3, + "totalsubmissions": 3891029, + "totalaccepted": 1529495, + "likes": 7636, + "dislikes": 2930, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "strs = ["flower","flow","flight"]", + "expected_output": ""fl"", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "strs = ["dog","racecar","car"]", + "expected_output": """", + "explanation": "There is no common prefix among the input strings." + } + ], + "solution": "/**\n * @param {string[]} strs\n * @return {string}\n */\nconst longestCommonPrefix = function(strs) {\n const A = strs.concat().sort(),\n a1 = A[0] || \"\",\n a2 = A[A.length - 1] || \"\",\n L = a1.length,\n i = 0;\n while (i < L && a1.charAt(i) === a2.charAt(i)) i++;\n return a1.substring(0, i);\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720ad8", + "questionid": 13, + "title": "Remove Nth Node From End of List", + "slug": "remove-nth-node-from-end-of-list", + "description": "Given the head of a linked list, remove the nth node from the end of the list and return its head. ", + "category": [ + "Linked List", + "Two Pointers" + ], + "complexity": "Medium", + "successrate": 38.2, + "totalsubmissions": 3510223, + "totalaccepted": 1340984, + "likes": 9607, + "dislikes": 457, + "hints": "Maintain two pointers and update one with a delay of n steps.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "head = [1,2,3,4,5], n = 2", + "expected_output": "[1,2,3,5]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "head = [1], n = 1", + "expected_output": "[]", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "head = [1,2], n = 1", + "expected_output": "[1]", + "explanation": "" + } + ], + "solution": "/**\n * Definition for singly-linked list.\n * function ListNode(val) {\n * this.val = val;\n * this.next = null;\n * }\n */\n/**\n * @param {ListNode} head\n * @param {number} n\n * @return {ListNode}\n */\nconst removeNthFromEnd = (head, n) => {\n if (head.next === null) return null;\n\n let ptrBeforeN = head;\n let count = 1;\n\n // While there are more elements\n let el = head.next;\n while (el !== null) {\n if (count > n) ptrBeforeN = ptrBeforeN.next;\n el = el.next;\n count++;\n }\n\n if (count === n) return head.next;\n\n ptrBeforeN.next = ptrBeforeN.next.next;\n return head;\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720adb", + "questionid": 16, + "title": "Merge k Sorted Lists", + "slug": "merge-k-sorted-lists", + "description": "You are given an array of k linked-lists lists, each linked-list is sorted in ascending order. Merge all the linked-lists into one sorted linked-list and return it. ", + "category": [ + "Linked List", + "Divide and Conquer", + "Heap (Priority Queue)", + "Merge Sort" + ], + "complexity": "Hard", + "successrate": 46.9, + "totalsubmissions": 2627265, + "totalaccepted": 1233044, + "likes": 11827, + "dislikes": 462, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "lists = [[1,4,5],[1,3,4],[2,6]]", + "expected_output": "[1,1,2,3,4,4,5,6]", + "explanation": "The linked-lists are:\n[\n 1->4->5,\n 1->3->4,\n 2->6\n]\nmerging them into one sorted list:\n1->1->2->3->4->4->5->6" + }, + { + "example_num": 2, + "expected_input": "lists = []", + "expected_output": "[]", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "lists = [[]]", + "expected_output": "[]", + "explanation": "" + } + ], + "solution": "/**\n * Definition for singly-linked list.\n * function ListNode(val) {\n * this.val = val;\n * this.next = null;\n * }\n */\n/**\n * @param {ListNode[]} lists\n * @return {ListNode}\n */\nconst mergeKLists = function(lists) {\n return merge(lists, 0, lists.length - 1)\n}\nfunction merge(lists, l, r) {\n if (l > r) return null\n if (l === r) return lists[l]\n let m = Math.floor((r + l) / 2)\n let left = merge(lists, l, m)\n let right = merge(lists, m + 1, r)\n let head = new ListNode(0)\n let dummy = head\n while (left && right) {\n if (left.val <= right.val) {\n head.next = left\n left = left.next\n } else {\n head.next = right\n right = right.next\n }\n head = head.next\n }\n head.next = left ? left : right\n return dummy.next\n}\n\n// another\n\n/**\n * Definition for singly-linked list.\n * function ListNode(val, next) {\n * this.val = (val===undefined ? 0 : val)\n * this.next = (next===undefined ? null : next)\n * }\n */\n/**\n * @param {ListNode[]} lists\n * @return {ListNode}\n */\nconst mergeKLists = function(lists) {\n if(lists == null || lists.length === 0) return null\n if(lists.length === 1) return lists[0]\n if(lists.length === 2) return mergeTwo(lists[0], lists[1])\n const left = mergeKLists(lists.slice(0, ~~(lists.length / 2)))\n const right = mergeKLists(lists.slice(~~(lists.length / 2)))\n \n return mergeTwo(left, right)\n};\n\nfunction mergeTwo(l1, l2) {\n const dummy = new ListNode()\n let cur = dummy\n while(l1 && l2) {\n if(l1.val < l2.val) {\n cur.next = l1\n l1 = l1.next\n } else {\n cur.next = l2\n l2 = l2.next\n }\n cur = cur.next\n }\n if(l1) cur.next = l1\n if(l2) cur.next = l2\n \n \n return dummy.next\n}\n\n\n// another\n\n/**\n * Definition for singly-linked list.\n * function ListNode(val, next) {\n * this.val = (val===undefined ? 0 : val)\n * this.next = (next===undefined ? null : next)\n * }\n */\n/**\n * @param {ListNode[]} lists\n * @return {ListNode}\n */\nconst mergeKLists = function(lists) {\n if(lists == null || lists.length === 0) return null\n const dummy = new ListNode()\n let head = dummy\n const pq = new PriorityQueue((a, b) => a.val < b.val)\n for(let list of lists) {\n while(list) {\n pq.push(list)\n list = list.next\n }\n }\n while(!pq.isEmpty()) {\n const pop = pq.pop()\n head.next = new ListNode(pop.val)\n head = head.next\n }\n return dummy.next\n};\n\nclass PriorityQueue {\n constructor(comparator = (a, b) => a > b) {\n this.heap = []\n this.top = 0\n this.comparator = comparator\n }\n size() {\n return this.heap.length\n }\n isEmpty() {\n return this.size() === 0\n }\n peek() {\n return this.heap[this.top]\n }\n push(...values) {\n values.forEach((value) => {\n this.heap.push(value)\n this.siftUp()\n })\n return this.size()\n }\n pop() {\n const poppedValue = this.peek()\n const bottom = this.size() - 1\n if (bottom > this.top) {\n this.swap(this.top, bottom)\n }\n this.heap.pop()\n this.siftDown()\n return poppedValue\n }\n replace(value) {\n const replacedValue = this.peek()\n this.heap[this.top] = value\n this.siftDown()\n return replacedValue\n }\n\n parent = (i) => ((i + 1) >>> 1) - 1\n left = (i) => (i << 1) + 1\n right = (i) => (i + 1) << 1\n greater = (i, j) => this.comparator(this.heap[i], this.heap[j])\n swap = (i, j) => ([this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]])\n siftUp = () => {\n let node = this.size() - 1\n while (node > this.top && this.greater(node, this.parent(node))) {\n this.swap(node, this.parent(node))\n node = this.parent(node)\n }\n }\n siftDown = () => {\n let node = this.top\n while (\n (this.left(node) < this.size() && this.greater(this.left(node), node)) ||\n (this.right(node) < this.size() && this.greater(this.right(node), node))\n ) {\n let maxChild =\n this.right(node) < this.size() &&\n this.greater(this.right(node), this.left(node))\n ? this.right(node)\n : this.left(node)\n this.swap(node, maxChild)\n node = maxChild\n }\n }\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720adc", + "questionid": 17, + "title": "Swap Nodes in Pairs", + "slug": "swap-nodes-in-pairs", + "description": "Given a\u00a0linked list, swap every two adjacent nodes and return its head. You must solve the problem without\u00a0modifying the values in the list's nodes (i.e., only nodes themselves may be changed.) ", + "category": [ + "Linked List", + "Recursion" + ], + "complexity": "Medium", + "successrate": 58.6, + "totalsubmissions": 1452282, + "totalaccepted": 851081, + "likes": 6765, + "dislikes": 289, + "hints": "", + "deleted": false, + "examples": [], + "solution": "/**\n * Definition for singly-linked list.\n * function ListNode(val) {\n * this.val = val;\n * this.next = null;\n * }\n */\n/**\n * @param {ListNode} head\n * @return {ListNode}\n */\nconst swapPairs = function(node) {\n const head = new ListNode(-1);\n let cur = head;\n\n while (node !== null) {\n if (node.next !== null) {\n let one = node;\n let two = node.next;\n let three = node.next.next;\n cur.next = two;\n two.next = one;\n one.next = three;\n cur = cur.next.next;\n node = three;\n } else {\n cur.next = node;\n break;\n }\n }\n\n return head.next;\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720ade", + "questionid": 19, + "title": "Substring with Concatenation of All Words", + "slug": "substring-with-concatenation-of-all-words", + "description": "You are given a string s and an array of strings words of the same length. Return\u00a0all starting indices of substring(s) in s\u00a0that is a concatenation of each word in words exactly once, in any order,\u00a0and without any intervening characters. You can return the answer in any order. ", + "category": [ + "Hash Table", + "String", + "Sliding Window" + ], + "complexity": "Hard", + "successrate": 28, + "totalsubmissions": 894344, + "totalaccepted": 250616, + "likes": 1893, + "dislikes": 1828, + "hints": "", + "deleted": false, + "examples": [], + "solution": "/**\n * @param {string} s\n * @param {string[]} words\n * @return {number[]}\n */\nconst findSubstring = function(s, words) {\n if (words == null || words.length === 0 || !s) return []\n const wh = {}\n const slen = s.length\n const wl = words[0].length\n const len = words[0].length * words.length\n words.forEach(el => {\n if (wh[el]) wh[el]++\n else wh[el] = 1\n })\n const res = []\n for (let i = 0; i < slen - len + 1; i++) {\n if (chk(wh, s.slice(i, i + len), wl, words.length)) res.push(i)\n }\n return res\n}\n\nfunction chk(hash, str, wl, num) {\n const oh = {}\n for (let i = 0; i < num; i++) {\n let tmp = str.slice(i * wl, i * wl + wl)\n if (oh[tmp]) oh[tmp]++\n else oh[tmp] = 1\n }\n const keys = Object.keys(hash)\n for (let i = 0; i < keys.length; i++) {\n if (oh[keys[i]] !== hash[keys[i]]) return false\n }\n return true\n}\n\n// another\n\n/**\n * @param {string} s\n * @param {string[]} words\n * @return {number[]}\n */\nconst findSubstring = function(s, words) {\n if (s === \"\" || words.length === 0) return []\n const wordMap = new Map()\n words.forEach(item => {\n if (wordMap.has(item)) {\n wordMap.set(item, wordMap.get(item) + 1)\n } else {\n wordMap.set(item, 1)\n }\n })\n const w = words[0].length\n const wlen = words.length\n const ans = []\n const n = s.length\n for (let i = 0; i < w; i++) {\n let left = i\n let count = 0\n let sMap = new Map()\n for (let j = i; j <= n - w; j += w) {\n let sub = s.substring(j, j + w)\n if (wordMap.has(sub)) {\n if (sMap.has(sub)) {\n sMap.set(sub, sMap.get(sub) + 1)\n } else {\n sMap.set(sub, 1)\n }\n if (sMap.get(sub) <= wordMap.get(sub)) {\n count++\n } else {\n while (sMap.get(sub) > wordMap.get(sub)) {\n let next = s.substring(left, left + w)\n sMap.set(next, sMap.get(next) - 1)\n if (sMap.get(next) < wordMap.get(next)) {\n count--\n }\n left += w\n }\n }\n if (count === wlen) {\n ans.push(left)\n let first = s.substring(left, left + w)\n sMap.set(first, sMap.get(first) - 1)\n left += w\n count--\n }\n } else {\n sMap.clear()\n count = 0\n left = j + w\n }\n }\n }\n return ans\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720ae9", + "questionid": 30, + "title": "Permutations II", + "slug": "permutations-ii", + "description": "Given a collection of numbers, nums,\u00a0that might contain duplicates, return all possible unique permutations in any order. ", + "category": [ + "Array", + "Backtracking" + ], + "complexity": "Medium", + "successrate": 54, + "totalsubmissions": 1105821, + "totalaccepted": 596907, + "likes": 4794, + "dislikes": 90, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,1,2]", + "expected_output": "[[1,1,2],\n [1,2,1],\n [2,1,1]]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "nums = [1,2,3]", + "expected_output": "[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} nums\n * @return {number[][]}\n */\nconst permuteUnique = function(nums) {\n const result = [];\n if (nums == null || nums.length === 0) {\n return result;\n }\n const map = {};\n for (let n of nums) {\n map[n] = map.hasOwnProperty(n) ? map[n] + 1 : 1;\n }\n permuteUniqueHelper(map, nums.length, [], 0, result);\n return result;\n};\n\nfunction permuteUniqueHelper(m, l, p, i, r) {\n if (l === i) {\n r.push(p.slice(0, l));\n return;\n }\n for (let key of Object.keys(m)) {\n if (m[key] > 0) {\n m[key] = m[key] - 1;\n p[i] = key;\n permuteUniqueHelper(m, l, p, i + 1, r);\n m[key] = m[key] + 1;\n }\n }\n}\n\n\n// another\n\n/**\n * @param {number[]} nums\n * @return {number[][]}\n */\nconst permuteUnique = function(nums) {\n const set = new Set()\n const used = new Set()\n bt(nums, 0, [], used, set)\n const res = []\n for(let item of set) {\n res.push(item.split(','))\n }\n return res\n};\n\nfunction bt(nums, i, cur, used, set) {\n if(i === nums.length) {\n set.add(cur.slice().join(','))\n return\n }\n for(let idx = 0; idx < nums.length; idx++) {\n if(used.has(idx)) continue\n cur.push(nums[idx])\n used.add(idx)\n bt(nums, i + 1, cur, used, set)\n used.delete(idx)\n cur.pop()\n }\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720aea", + "questionid": 31, + "title": "Rotate Image", + "slug": "rotate-image", + "description": "You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise). You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation. ", + "category": [ + "Array", + "Math", + "Matrix" + ], + "complexity": "Medium", + "successrate": 66.4, + "totalsubmissions": 1295324, + "totalaccepted": 860014, + "likes": 8777, + "dislikes": 473, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "matrix = [[1,2,3],[4,5,6],[7,8,9]]", + "expected_output": "[[7,4,1],[8,5,2],[9,6,3]]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "matrix = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]]", + "expected_output": "[[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]]", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[][]} matrix\n * @return {void} Do not return anything, modify matrix in-place instead.\n */\nconst rotate = function(matrix) {\n let s = 0,\n e = matrix.length - 1\n while (s < e) {\n let temp = matrix[s]\n matrix[s] = matrix[e]\n matrix[e] = temp\n s++\n e--\n }\n\n for (let i = 0; i < matrix.length; i++) {\n for (let j = i + 1; j < matrix[i].length; j++) {\n let temp = matrix[i][j]\n matrix[i][j] = matrix[j][i]\n matrix[j][i] = temp\n }\n }\n}\n\n// another\n\n/**\n * @param {number[][]} matrix\n * @return {void} Do not return anything, modify matrix in-place instead.\n */\nconst rotate = function (matrix) {\n matrix.reverse()\n for (let i = 0; i < matrix.length; ++i) {\n for (let j = i + 1; j < matrix[i].length; ++j) swap(matrix, i, j)\n }\n}\n\nfunction swap(matrix, i, j) {\n const tmp = matrix[j][i]\n matrix[j][i] = matrix[i][j]\n matrix[i][j] = tmp\n}\n\n// another\n\n/**\n * @param {number[][]} matrix\n * @return {void} Do not return anything, modify matrix in-place instead.\n */\nconst rotate = function (matrix) {\n matrix.reverse()\n for (let i = 0; i < matrix.length; ++i) {\n for (let j = matrix[i].length - 1; j > i; j--) swap(matrix, i, j)\n }\n}\n\nfunction swap(matrix, i, j) {\n const tmp = matrix[j][i]\n matrix[j][i] = matrix[i][j]\n matrix[i][j] = tmp\n}\n/*\n1 2 3 7 8 9 7 4 1\n4 5 6 ---> 4 5 6 --->8 5 2\n7 8 9 1 2 3 9 6 3\n*/\n" + }, + { + "_id": "66f925ddfdfb8e1665720aef", + "questionid": 36, + "title": "Maximum Subarray", + "slug": "maximum-subarray", + "description": "Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. A subarray is a contiguous part of an array. ", + "category": [ + "Array", + "Divide and Conquer", + "Dynamic Programming" + ], + "complexity": "Easy", + "successrate": 49.5, + "totalsubmissions": 4544146, + "totalaccepted": 2249144, + "likes": 19877, + "dislikes": 969, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [-2,1,-3,4,-1,2,1,-5,4]", + "expected_output": "6", + "explanation": "The subarray [4,-1,2,1] has the largest sum 6." + }, + { + "example_num": 2, + "expected_input": "nums = [1]", + "expected_output": "1", + "explanation": "The subarray [1] has the largest sum 1." + }, + { + "example_num": 3, + "expected_input": "nums = [5,4,-1,7,8]", + "expected_output": "23", + "explanation": "The subarray [5,4,-1,7,8] has the largest sum 23." + } + ], + "solution": "/**\n * @param {number[]} nums\n * @return {number}\n */\nconst maxSubArray = function (nums) {\n let res = -1e9, sum = 0\n for(const e of nums) {\n sum += e\n res = Math.max(res, sum)\n if(sum < 0) sum = 0\n }\n return res\n}\n\n// another\n\n/**\n * @param {number[]} nums\n * @return {number}\n */\nconst maxSubArray = function(nums) {\n let preSum = nums[0];\n let maxSum = preSum;\n for (let i = 1; i < nums.length; i++) {\n preSum = preSum > 0 ? preSum + nums[i] : nums[i];\n maxSum = Math.max(preSum, maxSum);\n }\n return maxSum;\n};\n\n// another\n\n/**\n * @param {number[]} nums\n * @return {number}\n */\nconst maxSubArray = function(nums) {\n const n = nums.length, dp = Array(n).fill(0)\n dp[0] = nums[0]\n let res = dp[0]\n for(let i = 1; i < n; i++) {\n dp[i] = Math.max(dp[i - 1], 0) + nums[i]\n res = Math.max(res, dp[i])\n }\n return res\n};\n\n// another\n\n/**\n * @param {number[]} nums\n * @return {number}\n */\nconst maxSubArray = function(nums) {\n return helper(nums, 0, nums.length - 1)\n};\n\nfunction helper(arr, l, r) {\n if(l > r) return -Infinity\n const mid = l + ((r - l) >> 1)\n let cur = 0, leftMax = 0, rightMax = 0\n for(let i = mid - 1; i >= l; i--) {\n cur += arr[i]\n leftMax = Math.max(leftMax, cur)\n }\n cur = 0\n for(let i = mid + 1; i <= r; i++) {\n cur += arr[i]\n rightMax = Math.max(rightMax, cur)\n }\n const res = arr[mid] + leftMax + rightMax\n const leftRes = helper(arr, l, mid - 1)\n const rightRes = helper(arr, mid + 1, r)\n \n return Math.max(res, leftRes, rightRes)\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720af1", + "questionid": 38, + "title": "Jump Game", + "slug": "jump-game", + "description": "You are given an integer array nums. You are initially positioned at the array's first index, and each element in the array represents your maximum jump length at that position. Return true if you can reach the last index, or false otherwise. ", + "category": [ + "Array", + "Dynamic Programming", + "Greedy" + ], + "complexity": "Medium", + "successrate": 37.7, + "totalsubmissions": 2575216, + "totalaccepted": 971160, + "likes": 10627, + "dislikes": 612, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [2,3,1,1,4]", + "expected_output": "true", + "explanation": "Jump 1 step from index 0 to 1, then 3 steps to the last index." + }, + { + "example_num": 2, + "expected_input": "nums = [3,2,1,0,4]", + "expected_output": "false", + "explanation": "You will always arrive at index 3 no matter what. Its maximum jump length is 0, which makes it impossible to reach the last index." + } + ], + "solution": "/**\n * @param {number[]} nums\n * @return {boolean}\n */\nconst canJump = function(nums) {\n let max = 0\n for(let i = 0, len = nums.length; i < len; i++) {\n if(i <= max && nums[i] > 0) {\n max = Math.max(max, i + nums[i])\n }\n }\n return max >= nums.length - 1\n};\n\n// another\n\n/**\n * @param {number[]} nums\n * @return {boolean}\n */\nconst canJump = function(nums) {\n let max = 0\n const n = nums.length\n for(let i = 0; i < n; i++) {\n if(max < i) return false\n max = Math.max(max, i + nums[i])\n if(max >= n - 1) return true\n }\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720afd", + "questionid": 50, + "title": "Sort Colors", + "slug": "sort-colors", + "description": "Given an array nums with n objects colored red, white, or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue. We will use the integers 0, 1, and 2 to represent the color red, white, and blue, respectively. You must solve this problem without using the library's sort function. ", + "category": [ + "Array", + "Two Pointers", + "Sorting" + ], + "complexity": "Medium", + "successrate": 54.6, + "totalsubmissions": 1791336, + "totalaccepted": 978245, + "likes": 9434, + "dislikes": 408, + "hints": "A rather straight forward solution is a two-pass algorithm using counting sort. Iterate the array counting number of 0's, 1's, and 2's. Overwrite array with the total number of 0's, then 1's and followed by 2's.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [2,0,2,1,1,0]", + "expected_output": "[0,0,1,1,2,2]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "nums = [2,0,1]", + "expected_output": "[0,1,2]", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} nums\n * @return {void} Do not return anything, modify nums in-place instead.\n */\nconst sortColors = function(nums) {\n let j = 0;\n let k = nums.length - 1;\n const swap = (a, b) => {\n const t = nums[a];\n nums[a] = nums[b];\n nums[b] = t;\n };\n for (let i = 0; i <= k; i++) {\n if (nums[i] === 2) {\n swap(i--, k--);\n } else if (nums[i] === 0) {\n swap(i, j++);\n }\n }\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720b08", + "questionid": 61, + "title": "Merge Sorted Array", + "slug": "merge-sorted-array", + "description": "You are given two integer arrays nums1 and nums2, sorted in non-decreasing order, and two integers m and n, representing the number of elements in nums1 and nums2 respectively. Merge nums1 and nums2 into a single array sorted in non-decreasing order. The final sorted array should not be returned by the function, but instead be stored inside the array nums1. To accommodate this, nums1 has a length of m + n, where the first m elements denote the elements that should be merged, and the last n elements are set to 0 and should be ignored. nums2 has a length of n. ", + "category": [ + "Array", + "Two Pointers", + "Sorting" + ], + "complexity": "Easy", + "successrate": 43.7, + "totalsubmissions": 3069815, + "totalaccepted": 1342555, + "likes": 4189, + "dislikes": 401, + "hints": "You can easily solve this problem if you simply think about two elements at a time rather than two arrays. We know that each of the individual arrays is sorted. What we don't know is how they will intertwine. Can we take a local decision and arrive at an optimal solution? If you simply consider one element each at a time from the two arrays and make a decision and proceed accordingly, you will arrive at the optimal solution.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3", + "expected_output": "[1,2,2,3,5,6]", + "explanation": "The arrays we are merging are [1,2,3] and [2,5,6].\nThe result of the merge is [1,2,2,3,5,6] with the underlined elements coming from nums1." + }, + { + "example_num": 2, + "expected_input": "nums1 = [1], m = 1, nums2 = [], n = 0", + "expected_output": "[1]", + "explanation": "The arrays we are merging are [1] and [].\nThe result of the merge is [1]." + }, + { + "example_num": 3, + "expected_input": "nums1 = [0], m = 0, nums2 = [1], n = 1", + "expected_output": "[1]", + "explanation": "The arrays we are merging are [] and [1].\nThe result of the merge is [1].\nNote that because m = 0, there are no elements in nums1. The 0 is only there to ensure the merge result can fit in nums1." + } + ], + "solution": "/**\n * @param {number[]} nums1\n * @param {number} m\n * @param {number[]} nums2\n * @param {number} n\n * @return {void} Do not return anything, modify nums1 in-place instead.\n */\nconst merge = function(nums1, m, nums2, n) {\n if (nums2.length === 0) return nums1;\n let fi = 0;\n let si = 0;\n for (let i = si; i < n; i++) {\n let se = nums2[i];\n while (se >= nums1[fi] && fi < m + n && fi < m + i) {\n fi++;\n }\n nums1.splice(fi, 0, se);\n fi++;\n }\n while (nums1.length > m + n) {\n nums1.pop();\n }\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720b11", + "questionid": 70, + "title": "Symmetric Tree", + "slug": "symmetric-tree", + "description": "Given the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center). ", + "category": [ + "Tree", + "Depth-First Search", + "Breadth-First Search", + "Binary Tree" + ], + "complexity": "Easy", + "successrate": 51.5, + "totalsubmissions": 2345643, + "totalaccepted": 1207686, + "likes": 9140, + "dislikes": 225, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [1,2,2,3,4,4,3]", + "expected_output": "true", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "root = [1,2,2,null,3,null,3]", + "expected_output": "false", + "explanation": "" + } + ], + "solution": "/**\n * Definition for a binary tree node.\n * function TreeNode(val) {\n * this.val = val;\n * this.left = this.right = null;\n * }\n */\n/**\n * @param {TreeNode} root\n * @return {boolean}\n */\nconst isSymmetric = function(root) {\n if(root == null) return true\n return compare(root.left, root.right)\n};\n\nfunction compare(l, r) {\n if(l == null && r == null) return true\n if( (l == null && r != null) || (l != null && r == null) ) return false\n \n if(l.val === r.val) {\n if(compare(l.left, r.right) !== false && compare(l.right, r.left) !== false) {\n return true\n } else {\n return false\n }\n \n } else {\n return false\n }\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720b12", + "questionid": 71, + "title": "Binary Tree Level Order Traversal", + "slug": "binary-tree-level-order-traversal", + "description": "Given the root of a binary tree, return the level order traversal of its nodes' values. (i.e., from left to right, level by level). ", + "category": [ + "Tree", + "Breadth-First Search", + "Binary Tree" + ], + "complexity": "Medium", + "successrate": 60.8, + "totalsubmissions": 1979250, + "totalaccepted": 1203028, + "likes": 7903, + "dislikes": 156, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [3,9,20,null,null,15,7]", + "expected_output": "[[3],[9,20],[15,7]]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "root = [1]", + "expected_output": "[[1]]", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "root = []", + "expected_output": "[]", + "explanation": "" + } + ], + "solution": "/**\n * Definition for a binary tree node.\n * function TreeNode(val) {\n * this.val = val;\n * this.left = this.right = null;\n * }\n */\n/**\n * @param {TreeNode} root\n * @return {number[][]}\n */\nconst levelOrder = function(root) {\n const res = [];\n if (root == null) return res;\n let next = [root];\n while (next.length > 0) {\n next = tr(res, next);\n }\n return res;\n};\n\nfunction tr(res, nodeArr) {\n const arr = [];\n const nextLevelNodes = [];\n for (let i = 0; i < nodeArr.length; i++) {\n arr.push(nodeArr[i].val);\n if (nodeArr[i].left) {\n nextLevelNodes.push(nodeArr[i].left);\n }\n if (nodeArr[i].right) {\n nextLevelNodes.push(nodeArr[i].right);\n }\n }\n if (arr.length) res.push(arr);\n return nextLevelNodes;\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720b17", + "questionid": 76, + "title": "Binary Tree Level Order Traversal II", + "slug": "binary-tree-level-order-traversal-ii", + "description": "Given the root of a binary tree, return the bottom-up level order traversal of its nodes' values. (i.e., from left to right, level by level from leaf to root). ", + "category": [ + "Tree", + "Breadth-First Search", + "Binary Tree" + ], + "complexity": "Medium", + "successrate": 58.6, + "totalsubmissions": 841912, + "totalaccepted": 493042, + "likes": 3118, + "dislikes": 276, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [3,9,20,null,null,15,7]", + "expected_output": "[[15,7],[9,20],[3]]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "root = [1]", + "expected_output": "[[1]]", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "root = []", + "expected_output": "[]", + "explanation": "" + } + ], + "solution": "/**\n * Definition for a binary tree node.\n * function TreeNode(val) {\n * this.val = val;\n * this.left = this.right = null;\n * }\n */\n/**\n * @param {TreeNode} root\n * @return {number[][]}\n */\nconst levelOrderBottom = function(root) {\n const levels = []\n postOrderTraversal(root)\n return levels.reverse()\n\n function postOrderTraversal(node, level = 0) {\n if (node) {\n if (!levels[level]) levels.push([])\n postOrderTraversal(node.left, level + 1)\n postOrderTraversal(node.right, level + 1)\n levels[level].push(node.val)\n }\n }\n}\n\n// another\n\nconst levelOrderBottom = function(root) {\n if (!root) return []\n const currentLevelNodes = [root]\n const result = []\n while (currentLevelNodes.length > 0) {\n const count = currentLevelNodes.length\n const currentLevelValues = []\n for (let i = 0; i < count; i++) {\n const node = currentLevelNodes.shift()\n currentLevelValues.push(node.val)\n if (node.left) currentLevelNodes.push(node.left)\n if (node.right) currentLevelNodes.push(node.right)\n }\n result.unshift(currentLevelValues)\n }\n return result\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720b1a", + "questionid": 79, + "title": "Path Sum", + "slug": "path-sum", + "description": "Given the root of a binary tree and an integer targetSum, return true if the tree has a root-to-leaf path such that adding up all the values along the path equals targetSum. A leaf is a node with no children. ", + "category": [ + "Tree", + "Depth-First Search", + "Breadth-First Search", + "Binary Tree" + ], + "complexity": "Easy", + "successrate": 45.4, + "totalsubmissions": 1884955, + "totalaccepted": 856231, + "likes": 5299, + "dislikes": 779, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22", + "expected_output": "true", + "explanation": "The root-to-leaf path with the target sum is shown." + }, + { + "example_num": 2, + "expected_input": "root = [1,2,3], targetSum = 5", + "expected_output": "false", + "explanation": "There are two root-to-leaf paths in the tree:\n(1 --> 2): The sum is 3.\n(1 --> 3): The sum is 4.\nThere is no root-to-leaf path with sum = 5." + }, + { + "example_num": 3, + "expected_input": "root = [], targetSum = 0", + "expected_output": "false", + "explanation": "Since the tree is empty, there are no root-to-leaf paths." + } + ], + "solution": "/**\n * Definition for a binary tree node.\n * function TreeNode(val) {\n * this.val = val;\n * this.left = this.right = null;\n * }\n */\n/**\n * @param {TreeNode} root\n * @param {number} sum\n * @return {boolean}\n */\nconst hasPathSum = function(root, sum) {\n if (root == null) {\n return false\n }\n const obj = {\n sum: 0\n }\n const res = []\n dfs(root, obj, sum, res)\n return res.indexOf(true) !== -1\n};\n\nfunction dfs(node, obj, target, res) {\n\n if (node.left == null && node.right == null) {\n obj.sum += node.val\n if (obj.sum === target) {\n res.push(true)\n }\n }\n if (node.left) {\n dfs(node.left, {sum: obj.sum + node.val}, target, res)\n }\n if (node.right) {\n dfs(node.right, {sum: obj.sum + node.val}, target, res)\n }\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720b1d", + "questionid": 82, + "title": "Populating Next Right Pointers in Each Node II", + "slug": "populating-next-right-pointers-in-each-node-ii", + "description": "Given a binary tree Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL. Initially, all next pointers are set to NULL. ", + "category": [ + "Linked List", + "Tree", + "Depth-First Search", + "Breadth-First Search", + "Binary Tree" + ], + "complexity": "Medium", + "successrate": 46.5, + "totalsubmissions": 923889, + "totalaccepted": 429180, + "likes": 3606, + "dislikes": 237, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [1,2,3,4,5,null,7]", + "expected_output": "[1,#,2,3,#,4,5,7,#]\nExplanation: Given the above binary tree (Figure A), your function should populate each next pointer to point to its next right node, just like in Figure B. The serialized output is in level order as connected by the next pointers, with '#' signifying the end of each level.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "root = []", + "expected_output": "[]", + "explanation": "" + } + ], + "solution": "/**\n * // Definition for a Node.\n * function Node(val,left,right,next) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * this.next = next;\n * };\n */\n/**\n * @param {Node} root\n * @return {Node}\n */\nconst connect = function(root) {\n if (root == null) return null\n const cur = [root]\n while (cur.length) {\n const len = cur.length\n for (let i = 0; i < len; i++) {\n const el = cur.shift()\n if (i === len - 1) el.next = null\n else el.next = cur[0]\n if (el.left) cur.push(el.left)\n if (el.right) cur.push(el.right)\n }\n }\n return root\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720b1e", + "questionid": 83, + "title": "Triangle", + "slug": "triangle", + "description": "Given a triangle array, return the minimum path sum from top to bottom. For each step, you may move to an adjacent number of the row below. More formally, if you are on index i on the current row, you may move to either index i or index i + 1 on the next row. ", + "category": [ + "Array", + "Dynamic Programming" + ], + "complexity": "Medium", + "successrate": 50.6, + "totalsubmissions": 807721, + "totalaccepted": 409106, + "likes": 4786, + "dislikes": 380, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "triangle = [[2],[3,4],[6,5,7],[4,1,8,3]]", + "expected_output": "11", + "explanation": "The triangle looks like:\n 2\n 3 4\n 6 5 7\n4 1 8 3\nThe minimum path sum from top to bottom is 2 + 3 + 5 + 1 = 11 (underlined above)." + }, + { + "example_num": 2, + "expected_input": "triangle = [[-10]]", + "expected_output": "-10", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[][]} triangle\n * @return {number}\n */\nconst minimumTotal = function(triangle) {\n const n = triangle.length;\n for (let i = n - 2; i >= 0; i--) {\n for (let j = 0; j < n; j++) {\n let self = triangle[i][j]; //\u83b7\u53d6\u7b2c\uff08i+1\uff09\u884c\uff08j+1\uff09\u4e2a\u6570\u5b57\n let res = Math.min(\n triangle[i + 1][j] + self,\n triangle[i + 1][j + 1] + self\n ); //\u5f97\u5230\u8fd9\u4e00\u884c\u4e0e\u4e0b\u4e00\u884c\u76f8\u90bb\u6570\u7684\u548c\u7684\u6700\u5c0f\u503c\n triangle[i][j] = res; //\u66f4\u65b0\u7b2c\uff08i+1\uff09\u884c\u7b2c\uff08j+1\uff09\u4e2a\u6570\u5b57\n }\n }\n\n return triangle[0][0];\n};\n\n// another\n\n/**\n * @param {number[][]} triangle\n * @return {number}\n */\nconst minimumTotal = function(triangle) {\n const m = triangle.length, n = triangle.at(-1).length\n const dp = Array.from({ length: m + 1 }, () => Array(n + 1).fill(Infinity))\n dp[1][1] = triangle[0][0]\n for(let i = 2; i <= m; i++) {\n for(let j = 1; j <= triangle[i - 1].length; j++) {\n if(j === 1) dp[i][j] = dp[i - 1][j] + triangle[i - 1][j - 1]\n else dp[i][j] = Math.min(dp[i - 1][j], dp[i - 1][j - 1]) + triangle[i - 1][j - 1] \n }\n }\n let res = Infinity\n for (let j = 0; j <= n; j++) {\n res = Math.min(res, dp[m][j])\n }\n return res\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720b21", + "questionid": 86, + "title": "Binary Tree Maximum Path Sum", + "slug": "binary-tree-maximum-path-sum", + "description": "A path in a binary tree is a sequence of nodes where each pair of adjacent nodes in the sequence has an edge connecting them. A node can only appear in the sequence at most once. Note that the path does not need to pass through the root. The path sum of a path is the sum of the node's values in the path. Given the root of a binary tree, return the maximum path sum of any non-empty path. ", + "category": [ + "Dynamic Programming", + "Tree", + "Depth-First Search", + "Binary Tree" + ], + "complexity": "Hard", + "successrate": 37.6, + "totalsubmissions": 1899960, + "totalaccepted": 714542, + "likes": 9151, + "dislikes": 529, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [1,2,3]", + "expected_output": "6", + "explanation": "The optimal path is 2 -> 1 -> 3 with a path sum of 2 + 1 + 3 = 6." + }, + { + "example_num": 2, + "expected_input": "root = [-10,9,20,null,null,15,7]", + "expected_output": "42", + "explanation": "The optimal path is 15 -> 20 -> 7 with a path sum of 15 + 20 + 7 = 42." + } + ], + "solution": "/**\n * Definition for a binary tree node.\n * function TreeNode(val) {\n * this.val = val;\n * this.left = this.right = null;\n * }\n */\n/**\n * @param {TreeNode} root\n * @return {number}\n */\nconst maxPathSum = function(root) {\n let obj = {\n max: Number.MIN_SAFE_INTEGER\n }\n traverse(root, obj)\n \n return obj.max\n};\n\nfunction traverse(node, obj) {\n if(node === null) return 0\n let left = Math.max(0, traverse(node.left, obj))\n let right = Math.max(0, traverse(node.right, obj))\n obj.max = Math.max(obj.max, node.val+left+right)\n return node.val + Math.max(left, right)\n}\n\n// another\n\n/**\n * Definition for a binary tree node.\n * function TreeNode(val, left, right) {\n * this.val = (val===undefined ? 0 : val)\n * this.left = (left===undefined ? null : left)\n * this.right = (right===undefined ? null : right)\n * }\n */\n/**\n * @param {TreeNode} root\n * @return {number}\n */\nconst maxPathSum = function(root) {\n let res = -Infinity\n dfs(root)\n return res\n\n function dfs(node) {\n if(node == null) return 0\n let left = dfs(node.left), right = dfs(node.right)\n res = Math.max(\n res,\n node.val,\n node.val + left,\n node.val + right,\n node.val + left + right,\n )\n return Math.max(node.val, node.val + left, node.val + right)\n }\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720b24", + "questionid": 89, + "title": "Sum Root to Leaf Numbers", + "slug": "sum-root-to-leaf-numbers", + "description": "You are given the root of a binary tree containing digits from 0 to 9 only. Each root-to-leaf path in the tree represents a number. Return the total sum of all root-to-leaf numbers. Test cases are generated so that the answer will fit in a 32-bit integer. A leaf node is a node with no children. ", + "category": [ + "Tree", + "Depth-First Search", + "Binary Tree" + ], + "complexity": "Medium", + "successrate": 56.8, + "totalsubmissions": 795340, + "totalaccepted": 451675, + "likes": 4097, + "dislikes": 78, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [1,2,3]", + "expected_output": "25", + "explanation": "The root-to-leaf path 1->2 represents the number 12.\nThe root-to-leaf path 1->3 represents the number 13.\nTherefore, sum = 12 + 13 = 25." + }, + { + "example_num": 2, + "expected_input": "root = [4,9,0,5,1]", + "expected_output": "1026", + "explanation": "The root-to-leaf path 4->9->5 represents the number 495.\nThe root-to-leaf path 4->9->1 represents the number 491.\nThe root-to-leaf path 4->0 represents the number 40.\nTherefore, sum = 495 + 491 + 40 = 1026." + } + ], + "solution": "/**\n * Definition for a binary tree node.\n * function TreeNode(val) {\n * this.val = val;\n * this.left = this.right = null;\n * }\n */\n/**\n * @param {TreeNode} root\n * @return {number}\n */\nconst sumNumbers = function(root) {\n const sum = []\n rec(root, '', sum)\n return sum.reduce((ac, el) => ac + el, 0)\n};\n\nfunction rec(node, str, arr) {\n if (node == null) {\n arr.push(+str)\n return\n }\n if (node.left !== null) {\n rec(node.left, str + node.val, arr)\n }\n if (node.right !== null) {\n rec(node.right, str + node.val, arr)\n }\n if (node.left === null && node.right === null) {\n arr.push(+(str + node.val) )\n }\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720b29", + "questionid": 94, + "title": "Single Number", + "slug": "single-number", + "description": "Given a non-empty\u00a0array of integers nums, every element appears twice except for one. Find that single one. You must\u00a0implement a solution with a linear runtime complexity and use\u00a0only constant\u00a0extra space. ", + "category": [ + "Array", + "Bit Manipulation" + ], + "complexity": "Easy", + "successrate": 69.3, + "totalsubmissions": 2321213, + "totalaccepted": 1608367, + "likes": 9569, + "dislikes": 339, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [2,2,1]", + "expected_output": "1", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "nums = [4,1,2,1,2]", + "expected_output": "4", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "nums = [1]", + "expected_output": "1", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} nums\n * @return {number}\n */\nconst singleNumber = function(nums) {\n let xor = nums[0]\n for(let i = 1; i< nums.length; i++) xor ^= nums[i]\n return xor\n};\n\n\n// another\n\n/**\n * @param {number[]} nums\n * @return {number}\n */\nconst singleNumber = function(nums) {\n return nums.reduce((ac, e) => ac ^ e, 0)\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720b30", + "questionid": 101, + "title": "Binary Tree Postorder Traversal", + "slug": "binary-tree-postorder-traversal", + "description": "Given the root of a\u00a0binary tree, return the postorder traversal of its nodes' values. ", + "category": [ + "Stack", + "Tree", + "Depth-First Search", + "Binary Tree" + ], + "complexity": "Easy", + "successrate": 63.9, + "totalsubmissions": 1095333, + "totalaccepted": 699695, + "likes": 4035, + "dislikes": 136, + "hints": "", + "deleted": false, + "examples": [], + "solution": "/**\n * Definition for a binary tree node.\n * function TreeNode(val) {\n * this.val = val;\n * this.left = this.right = null;\n * }\n */\n/**\n * @param {TreeNode} root\n * @return {number[]}\n */\nconst postorderTraversal = function(root) {\n const res = []\n traverse(root, res)\n return res\n};\n\nfunction traverse(node, arr) {\n if(node == null) return\n traverse(node.left, arr)\n traverse(node.right, arr)\n arr.push(node.val)\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720b3a", + "questionid": 111, + "title": "Majority Element", + "slug": "majority-element", + "description": "Given an array nums of size n, return the majority element. The majority element is the element that appears more than n / 2 times. You may assume that the majority element always exists in the array. ", + "category": [ + "Array", + "Hash Table", + "Divide and Conquer", + "Sorting", + "Counting" + ], + "complexity": "Easy", + "successrate": 62.8, + "totalsubmissions": 1906897, + "totalaccepted": 1198357, + "likes": 9327, + "dislikes": 333, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [3,2,3]", + "expected_output": "3", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "nums = [2,2,1,1,1,2,2]", + "expected_output": "2", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} nums\n * @return {number}\n */\nvar majorityElement = function(nums) {\n let el, cnt = 0\n for(let e of nums) {\n if(cnt === 0) {\n el = e\n cnt++\n } else if(el === e) {\n cnt++\n } else {\n cnt--\n }\n }\n let tmp = 0\n for(const e of nums) {\n if(e === el) tmp++\n }\n return tmp > Math.floor(nums.length / 2) ? el : null\n};\n\n// another\n\n/**\n * @param {number[]} nums\n * @return {number}\n */\nconst majorityElement = function(nums) {\n let res = 0, cnt = 0\n \n for(const e of nums) {\n if(cnt === 0) {\n res = e\n }\n if(res === e) cnt++\n else cnt--\n }\n \n return res\n};\n\n// another\n\n/**\n * @param {number[]} nums\n * @return {number}\n */\nconst majorityElement = function(nums) {\n const hash = {};\n nums.forEach(el => {\n if (hash.hasOwnProperty(el)) {\n hash[el] += 1;\n } else {\n hash[el] = 1;\n }\n });\n return Object.entries(hash)\n .filter(el => el[1] > Math.floor(nums.length / 2))\n .map(el => +el[0])\n .sort((a, b) => b - a)[0];\n};\n\n// another\n\n/**\n * @param {number[]} nums\n * @return {number}\n */\nconst majorityElement = function(nums) {\n let cnt = 1, candidate = nums[0]\n for(let i = 1, n = nums.length; i < n; i++) {\n if(candidate === nums[i]) cnt++\n else cnt--\n if(cnt === 0) {\n cnt = 1\n candidate = nums[i]\n }\n }\n return candidate\n};\n\n// another\n\n/**\n * @param {number[]} nums\n * @return {number}\n */\nconst majorityElement = function(nums) {\n let cnt = 1, candidate = nums[0]\n for(let i = 1, n = nums.length; i < n; i++) {\n if(cnt === 0) {\n cnt = 1\n candidate = nums[i]\n }else if(candidate === nums[i]) cnt++\n else cnt--\n }\n return candidate\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720b3d", + "questionid": 114, + "title": "Largest Number", + "slug": "largest-number", + "description": "Given a list of non-negative integers nums, arrange them such that they form the largest number and return it. Since the result may be very large, so you need to return a string instead of an integer. ", + "category": [ + "String", + "Greedy", + "Sorting" + ], + "complexity": "Medium", + "successrate": 32.8, + "totalsubmissions": 950354, + "totalaccepted": 312186, + "likes": 4751, + "dislikes": 400, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [10,2]", + "expected_output": ""210"", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "nums = [3,30,34,5,9]", + "expected_output": ""9534330"", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} nums\n * @return {string}\n */\nconst largestNumber = function(nums) {\n const arr = nums\n .map(v => v.toString())\n .sort((a, b) => (a + b < b + a ? 1 : -1))\n .join(\"\");\n\n return arr[0] === \"0\" ? \"0\" : arr;\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720b3f", + "questionid": 116, + "title": "Rotate Array", + "slug": "rotate-array", + "description": "Given an array, rotate the array to the right by k steps, where k is non-negative. ", + "category": [ + "Array", + "Math", + "Two Pointers" + ], + "complexity": "Medium", + "successrate": 38.5, + "totalsubmissions": 2796554, + "totalaccepted": 1077386, + "likes": 9117, + "dislikes": 1268, + "hints": "The easiest solution would use additional memory and that is perfectly fine. The actual trick comes when trying to solve this problem without using any additional memory. This means you need to use the original array somehow to move the elements around. Now, we can place each element in its original location and shift all the elements around it to adjust as that would be too costly and most likely will time out on larger input arrays. One line of thought is based on reversing the array (or parts of it) to obtain the desired result. Think about how reversal might potentially help us out by using an example. The other line of thought is a tad bit complicated but essentially it builds on the idea of placing each element in its original position while keeping track of the element originally in that position. Basically, at every step, we place an element in its rightful position and keep track of the element already there or the one being overwritten in an additional variable. We can't do this in one linear pass and the idea here is based on cyclic-dependencies between elements.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,2,3,4,5,6,7], k = 3", + "expected_output": "[5,6,7,1,2,3,4]", + "explanation": "rotate 1 steps to the right: [7,1,2,3,4,5,6]\nrotate 2 steps to the right: [6,7,1,2,3,4,5]\nrotate 3 steps to the right: [5,6,7,1,2,3,4]" + }, + { + "example_num": 2, + "expected_input": "nums = [-1,-100,3,99], k = 2", + "expected_output": "[3,99,-1,-100]", + "explanation": "rotate 1 steps to the right: [99,-1,-100,3]\nrotate 2 steps to the right: [3,99,-1,-100]" + } + ], + "solution": "/**\n * @param {number[]} nums\n * @param {number} k\n * @return {void} Do not return anything, modify nums in-place instead.\n */\nconst rotate = function(nums, k) {\n nums.unshift(...nums.splice(nums.length - k))\n};\n\n// another\n\nconst rotate = function(nums, k) {\n let i = k\n while (i > 0) {\n nums.unshift(nums.pop())\n i--\n }\n};\n\n// another\n\nconst rotate = function(nums, k) {\n k %= nums.length\n reverse(nums, 0, nums.length - 1)\n reverse(nums, 0, k - 1)\n reverse(nums, k, nums.length - 1)\n}\n\nfunction reverse(nums, start, end) {\n while (start < end) {\n var temp = nums[start]\n nums[start] = nums[end]\n nums[end] = temp\n start++\n end--\n }\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720b42", + "questionid": 119, + "title": "Number of Islands", + "slug": "number-of-islands", + "description": "Given an m x n 2D binary grid grid which represents a map of '1's (land) and '0's (water), return the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water. ", + "category": [ + "Array", + "Depth-First Search", + "Breadth-First Search", + "Union Find", + "Matrix" + ], + "complexity": "Medium", + "successrate": 53.8, + "totalsubmissions": 2825342, + "totalaccepted": 1518896, + "likes": 13254, + "dislikes": 320, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "grid = [\n ["1","1","1","1","0"],\n ["1","1","0","1","0"],\n ["1","1","0","0","0"],\n ["0","0","0","0","0"]\n]", + "expected_output": "1", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "grid = [\n ["1","1","0","0","0"],\n ["1","1","0","0","0"],\n ["0","0","1","0","0"],\n ["0","0","0","1","1"]\n]", + "expected_output": "3", + "explanation": "" + } + ], + "solution": "/**\n * @param {character[][]} grid\n * @return {number}\n */\nconst numIslands = function(grid) {\n if (grid.length === 0) return 0;\n const totalRow = grid.length;\n const totalCol = grid[0].length;\n let res = 0;\n \n for (let i = 0; i < totalRow; i += 1) {\n for (let j = 0; j < totalCol; j += 1) {\n if (grid[i][j] === '1') {\n res += 1;\n dfs(grid, i, j, totalRow, totalCol);\n }\n }\n }\n \n return res;\n};\n\nconst dfs = (grid, row, col, totalRow, totalCol) => {\n if (row < 0 || col < 0 || row === totalRow || col === totalCol || grid[row][col] === '0') {\n return;\n }\n \n grid[row][col] = '0';\n dfs(grid, row - 1, col, totalRow, totalCol);\n dfs(grid, row + 1, col, totalRow, totalCol);\n dfs(grid, row, col - 1, totalRow, totalCol);\n dfs(grid, row, col + 1, totalRow, totalCol);\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720b0d", + "questionid": 66, + "title": "Unique Binary Search Trees II", + "slug": "unique-binary-search-trees-ii", + "description": "Given an integer n, return all the structurally unique BST's (binary search trees), which has exactly n nodes of unique values from 1 to n. Return the answer in any order. ", + "category": [ + "Dynamic Programming", + "Backtracking", + "Tree", + "Binary Search Tree", + "Binary Tree" + ], + "complexity": "Medium", + "successrate": 49.3, + "totalsubmissions": 612378, + "totalaccepted": 301936, + "likes": 4623, + "dislikes": 302, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 3", + "expected_output": "[[1,null,2,null,3],[1,null,3,2],[2,1,3],[3,1,null,null,2],[3,2,null,1]]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "n = 1", + "expected_output": "[[1]]", + "explanation": "" + } + ], + "solution": "/**\n * Definition for a binary tree node.\n * function TreeNode(val) {\n * this.val = val;\n * this.left = this.right = null;\n * }\n */\n/**\n * @param {number} n\n * @return {TreeNode[]}\n */\nconst generateTrees = function(n) {\n if (n === 0) return []\n return genTreeList(1, n)\n}\n\nfunction genTreeList(start, end) {\n const list = []\n if (start > end) list.push(null)\n for (let idx = start; idx <= end; idx++) {\n const leftList = genTreeList(start, idx - 1)\n const rightList = genTreeList(idx + 1, end)\n for (let left of leftList) {\n for (let right of rightList) {\n const root = new TreeNode(idx)\n root.left = left\n root.right = right\n list.push(root)\n }\n }\n }\n return list\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720b0f", + "questionid": 68, + "title": "Recover Binary Search Tree", + "slug": "recover-binary-search-tree", + "description": "You are given the root of a binary search tree (BST), where the values of exactly two nodes of the tree were swapped by mistake. Recover the tree without changing its structure. ", + "category": [ + "Tree", + "Depth-First Search", + "Binary Search Tree", + "Binary Tree" + ], + "complexity": "Medium", + "successrate": 46.3, + "totalsubmissions": 603807, + "totalaccepted": 279687, + "likes": 4150, + "dislikes": 154, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [1,3,null,null,2]", + "expected_output": "[3,1,null,null,2]", + "explanation": "3 cannot be a left child of 1 because 3 > 1. Swapping 1 and 3 makes the BST valid." + }, + { + "example_num": 2, + "expected_input": "root = [3,1,4,null,null,2]", + "expected_output": "[2,1,4,null,null,3]", + "explanation": "2 cannot be in the right subtree of 3 because 2 < 3. Swapping 2 and 3 makes the BST valid." + } + ], + "solution": "/**\n * Definition for a binary tree node.\n * function TreeNode(val) {\n * this.val = val;\n * this.left = this.right = null;\n * }\n */\n/**\n * @param {TreeNode} root\n * @return {void} Do not return anything, modify root in-place instead.\n */\nconst recoverTree = function(root) {\n let node1, node2;\n let prev = new TreeNode(-Infinity);\n traverse(root);\n swap(node1, node2)\n \n function traverse(node) {\n if (!node) return;\n traverse(node.left);\n if (node.val < prev.val) {\n node2 = node;\n if (!node1) node1 = prev;\n }\n prev = node;\n traverse(node.right);\n }\n\n function swap(node1, node2) {\n let temp = node1.val\n node1.val = node2.val\n node2.val = temp\n }\n}\n\n// another\n\nconst recoverTree = function(root) {\n const eNodes = [];\n if (root == null) return;\n let current = root;\n let pre;\n let previous = null;\n while (current != null) {\n if (current.left == null) {\n if (previous != null && previous.val > current.val) {\n eNodes.push(previous);\n eNodes.push(current);\n }\n previous = current;\n current = current.right;\n } else {\n pre = current.left;\n while (pre.right != null && pre.right.val != current.val) {\n pre = pre.right;\n }\n\n if (pre.right == null) {\n pre.right = current;\n current = current.left;\n } else {\n if (previous != null && previous.val > current.val) {\n eNodes.push(previous);\n eNodes.push(current);\n }\n pre.right = null;\n previous = current;\n current = current.right;\n }\n }\n }\n if (eNodes.length == 2) {\n pre = eNodes[0];\n current = eNodes[1];\n } else {\n pre = eNodes[0];\n current = eNodes[3];\n }\n let temp = pre.val;\n pre.val = current.val;\n current.val = temp;\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720b13", + "questionid": 72, + "title": "Binary Tree Zigzag Level Order Traversal", + "slug": "binary-tree-zigzag-level-order-traversal", + "description": "Given the root of a binary tree, return the zigzag level order traversal of its nodes' values. (i.e., from left to right, then right to left for the next level and alternate between). ", + "category": [ + "Tree", + "Breadth-First Search", + "Binary Tree" + ], + "complexity": "Medium", + "successrate": 53.5, + "totalsubmissions": 1299175, + "totalaccepted": 694977, + "likes": 5665, + "dislikes": 168, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [3,9,20,null,null,15,7]", + "expected_output": "[[3],[20,9],[15,7]]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "root = [1]", + "expected_output": "[[1]]", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "root = []", + "expected_output": "[]", + "explanation": "" + } + ], + "solution": "/**\n * Definition for a binary tree node.\n * function TreeNode(val) {\n * this.val = val;\n * this.left = this.right = null;\n * }\n */\n/**\n * @param {TreeNode} root\n * @return {number[][]}\n */\nconst zigzagLevelOrder = function(root) {\n if(root == null) return []\n const row = [root]\n const res = []\n bfs(row, res)\n for(let i = 0; i < res.length; i++) {\n res[i] = i % 2 === 0 ? res[i] : res[i].reverse()\n }\n return res\n};\n\nfunction bfs(row, res) {\n if(row.length === 0) return\n let tmp = []\n let next = []\n for(let i = 0; i< row.length; i++) {\n tmp.push(row[i].val)\n if(row[i].left) {\n next.push(row[i].left)\n }\n if(row[i].right) {\n next.push(row[i].right)\n }\n }\n if(tmp.length) {\n res.push(tmp)\n }\n bfs(next, res)\n}\n\n// another\n\n/**\n * Definition for a binary tree node.\n * function TreeNode(val, left, right) {\n * this.val = (val===undefined ? 0 : val)\n * this.left = (left===undefined ? null : left)\n * this.right = (right===undefined ? null : right)\n * }\n */\n/**\n * @param {TreeNode} root\n * @return {number[][]}\n */\nconst zigzagLevelOrder = function (root) {\n if (!root) return [];\n const queue = [root];\n const zigzag = [];\n let numLevels = 1;\n while (queue.length > 0) {\n const width = queue.length;\n const levelTraversal = [];\n for (let i = 0; i < width; i++) {\n const currentNode = queue.shift();\n if (currentNode.right) queue.push(currentNode.right);\n if (currentNode.left) queue.push(currentNode.left);\n numLevels % 2 === 0\n ? levelTraversal.push(currentNode.val)\n : levelTraversal.unshift(currentNode.val);\n }\n zigzag.push(levelTraversal);\n numLevels++;\n }\n\n return zigzag;\n};\n\n// another\n\n/**\n * Definition for a binary tree node.\n * function TreeNode(val, left, right) {\n * this.val = (val===undefined ? 0 : val)\n * this.left = (left===undefined ? null : left)\n * this.right = (right===undefined ? null : right)\n * }\n */\n/**\n * @param {TreeNode} root\n * @return {number[][]}\n */\nconst zigzagLevelOrder = function (root) {\n const res = []\n dfs(root, res, 0)\n return res\n \n function dfs(node, res, level) {\n if(node == null) return\n if(res.length <= level) res.push([])\n const tmp = res[level]\n if(level % 2 === 0) tmp.push(node.val)\n else tmp.unshift(node.val)\n \n dfs(node.left, res, level + 1)\n dfs(node.right, res, level + 1)\n }\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720b19", + "questionid": 78, + "title": "Convert Sorted List to Binary Search Tree", + "slug": "convert-sorted-list-to-binary-search-tree", + "description": "Given the head of a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST. For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1. ", + "category": [ + "Linked List", + "Divide and Conquer", + "Tree", + "Binary Search Tree", + "Binary Tree" + ], + "complexity": "Medium", + "successrate": 55.4, + "totalsubmissions": 664109, + "totalaccepted": 367942, + "likes": 4468, + "dislikes": 113, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "head = [-10,-3,0,5,9]", + "expected_output": "[0,-3,9,-10,null,5]", + "explanation": "One possible answer is [0,-3,9,-10,null,5], which represents the shown height balanced BST." + }, + { + "example_num": 2, + "expected_input": "head = []", + "expected_output": "[]", + "explanation": "" + } + ], + "solution": "/**\n * Definition for singly-linked list.\n * function ListNode(val) {\n * this.val = val;\n * this.next = null;\n * }\n */\n/**\n * Definition for a binary tree node.\n * function TreeNode(val) {\n * this.val = val;\n * this.left = this.right = null;\n * }\n */\n/**\n * @param {ListNode} head\n * @return {TreeNode}\n */\nconst sortedListToBST = function(head) {\n if(head == null) return null\n const arr = []\n let cur = head\n while(cur !== null) {\n arr.push(cur)\n cur = cur.next\n }\n return build(arr, null, '')\n};\n\nfunction build(arr, parent, type) {\n if(arr.length === 0) return\n let mid = Math.floor(arr.length / 2)\n let left = arr.slice(0, mid)\n let right = arr.slice(mid + 1)\n const node = new TreeNode(arr[mid].val)\n if(parent) parent[type] = node\n build(left, node, 'left')\n build(right, node, 'right')\n return node\n}\n\n// another\n\nconst sortedListToBST = function(head, tail = null) {\n if (head === tail) {\n return null;\n } else if (head.next === tail) {\n return new TreeNode(head.val);\n } else {\n let slow = head; \n let fast = head;\n while (fast !== tail && fast.next !== tail) {\n slow = slow.next;\n fast = fast.next.next;\n }\n let node = new TreeNode(slow.val);\n node.left = sortedListToBST(head, slow);\n node.right = sortedListToBST(slow.next, tail);\n return node;\n }\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720b1c", + "questionid": 81, + "title": "Distinct Subsequences", + "slug": "distinct-subsequences", + "description": "Given two strings s and t, return the number of distinct subsequences of s which equals t. A string's subsequence is a new string formed from the original string by deleting some (can be none) of the characters without disturbing the remaining characters' relative positions. (i.e., \"ACE\" is a subsequence of \"ABCDE\" while \"AEC\" is not). The test cases are generated so that the answer fits on a 32-bit signed integer. ", + "category": [ + "String", + "Dynamic Programming" + ], + "complexity": "Hard", + "successrate": 42.2, + "totalsubmissions": 509853, + "totalaccepted": 215300, + "likes": 3321, + "dislikes": 146, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "rabbbit", t = "rabbit"", + "expected_output": "3", + "explanation": "As shown below, there are 3 ways you can generate "rabbit" from s.\nrabbbit\nrabbbit\nrabbbit" + }, + { + "example_num": 2, + "expected_input": "s = "babgbag", t = "bag"", + "expected_output": "5", + "explanation": "As shown below, there are 5 ways you can generate "bag" from s.\nbabgbag\nbabgbag\nbabgbag\nbabgbag\nbabgbag" + } + ], + "solution": "/**\n * @param {string} s\n * @param {string} t\n * @return {number}\n */\nconst numDistinct = function(s, t) {\n const tlen = t.length\n const slen = s.length\n const mem = Array.from({ length: tlen + 1 }, () =>\n new Array(slen + 1).fill(0)\n )\n for (let j = 0; j <= slen; j++) {\n mem[0][j] = 1\n }\n for (let i = 0; i < tlen; i++) {\n for (let j = 0; j < slen; j++) {\n if (t.charAt(i) === s.charAt(j)) {\n mem[i + 1][j + 1] = mem[i][j] + mem[i + 1][j]\n } else {\n mem[i + 1][j + 1] = mem[i + 1][j]\n }\n }\n }\n return mem[tlen][slen]\n}\n\n\n// another\n\n/**\n * @param {string} s\n * @param {string} t\n * @return {number}\n */\nconst numDistinct = function(s, t) {\n const m = t.length,\n n = s.length\n const cur = new Array(m + 1).fill(0)\n cur[0] = 1\n for (let j = 1; j <= n; j++) {\n let pre = 1\n for (let i = 1; i <= m; i++) {\n let temp = cur[i]\n cur[i] = cur[i] + (t[i - 1] == s[j - 1] ? pre : 0)\n pre = temp\n }\n }\n return cur[m]\n}\n\n// another\n\n/**\n * @param {string} s\n * @param {string} t\n * @return {number}\n */\nconst numDistinct = function(s, t) {\n const m = t.length,\n n = s.length\n const dp = new Array(m + 1).fill(0)\n dp[0] = 1\n for (let j = 1; j <= n; j++) {\n for (let i = m; i > 0; i--) {\n dp[i] = dp[i] + (t[i - 1] == s[j - 1] ? dp[i - 1] : 0)\n }\n }\n return dp[m]\n}\n\n" + }, + { + "_id": "66f925ddfdfb8e1665720b25", + "questionid": 90, + "title": "Surrounded Regions", + "slug": "surrounded-regions", + "description": "Given an m x n matrix board containing 'X' and 'O', capture all regions that are 4-directionally\u00a0surrounded by 'X'. A region is captured by flipping all 'O's into 'X's in that surrounded region. ", + "category": [ + "Array", + "Depth-First Search", + "Breadth-First Search", + "Union Find", + "Matrix" + ], + "complexity": "Medium", + "successrate": 33.9, + "totalsubmissions": 1196214, + "totalaccepted": 405287, + "likes": 4684, + "dislikes": 1164, + "hints": "", + "deleted": false, + "examples": [], + "solution": "/**\n * @param {character[][]} board\n * @return {void} Do not return anything, modify board in-place instead.\n */\nconst solve = function(board) {\n if (!board || board.length < 3 || board[0].length < 3) return;\n let r = board.length;\n let c = board[0].length;\n for (let i = 0; i < c; i++) {\n if (board[0][i] === \"O\") search(board, 0, i);\n if (board[r - 1][i] === \"O\") search(board, r - 1, i);\n }\n for (let i = 0; i < r; i++) {\n if (board[i][0] === \"O\") search(board, i, 0);\n if (board[i][c - 1] === \"O\") search(board, i, c - 1);\n }\n for (let i = 0; i < r; i++) {\n for (let j = 0; j < c; j++) {\n if (board[i][j] === \"O\") board[i][j] = \"X\";\n if (board[i][j] === \"*\") board[i][j] = \"O\";\n }\n }\n};\n\nfunction search(board, i, j) {\n if (i < 0 || j < 0 || i >= board.length || j >= board[0].length) return;\n if (board[i][j] !== \"O\") return;\n board[i][j] = \"*\";\n search(board, i + 1, j);\n search(board, i - 1, j);\n search(board, i, j + 1);\n search(board, i, j - 1);\n}\n\n// another\n\n/**\n * @param {character[][]} board\n * @return {void} Do not return anything, modify board in-place instead.\n */\nconst solve = (board) => {\n if (!board || board.length === 0 || board[0].length === 0) return;\n const n = board.length;\n const m = board[0].length;\n const dirs = [\n [-1, 0],\n [1, 0],\n [0, -1],\n [0, 1],\n ];\n const bfs = (board, n, m, i, j) => {\n const queue = [];\n queue.push([i, j]);\n board[i][j] = \"1\";\n while (queue.length > 0) {\n const pos = queue.shift();\n for (let k = 0; k < 4; k++) {\n i = pos[0] + dirs[k][0];\n j = pos[1] + dirs[k][1];\n if (i >= 0 && i < n && j >= 0 && j < m && board[i][j] === \"O\") {\n board[i][j] = \"1\";\n queue.push([i, j]);\n }\n }\n }\n };\n // scan the borders and mark the 'O's to '1'\n for (let i = 0; i < n; i++) {\n for (let j = 0; j < m; j++) {\n if (\n (i === 0 || i === n - 1 || j === 0 || j === m - 1) &&\n board[i][j] === \"O\"\n ) {\n bfs(board, n, m, i, j);\n }\n }\n }\n // scan the inner area and mark the 'O's to 'X'\n for (let i = 1; i < n; i++) {\n for (let j = 1; j < m; j++) {\n if (board[i][j] === \"O\") {\n board[i][j] = \"X\";\n }\n }\n }\n // reset all the '1's to 'O's\n for (let i = 0; i < n; i++) {\n for (let j = 0; j < m; j++) {\n if (board[i][j] === \"1\") {\n board[i][j] = \"O\";\n }\n }\n }\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720b28", + "questionid": 93, + "title": "Gas Station", + "slug": "gas-station", + "description": "There are n gas stations along a circular route, where the amount of gas at the ith station is gas[i]. You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from the ith station to its next (i + 1)th station. You begin the journey with an empty tank at one of the gas stations. Given two integer arrays gas and cost, return the starting gas station's index if you can travel around the circuit once in the clockwise direction, otherwise return -1. If there exists a solution, it is guaranteed to be unique ", + "category": [ + "Array", + "Greedy" + ], + "complexity": "Medium", + "successrate": 44.4, + "totalsubmissions": 899594, + "totalaccepted": 399619, + "likes": 5703, + "dislikes": 595, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "gas = [1,2,3,4,5], cost = [3,4,5,1,2]", + "expected_output": "3", + "explanation": "Start at station 3 (index 3) and fill up with 4 unit of gas. Your tank = 0 + 4 = 4\nTravel to station 4. Your tank = 4 - 1 + 5 = 8\nTravel to station 0. Your tank = 8 - 2 + 1 = 7\nTravel to station 1. Your tank = 7 - 3 + 2 = 6\nTravel to station 2. Your tank = 6 - 4 + 3 = 5\nTravel to station 3. The cost is 5. Your gas is just enough to travel back to station 3.\nTherefore, return 3 as the starting index." + }, + { + "example_num": 2, + "expected_input": "gas = [2,3,4], cost = [3,4,3]", + "expected_output": "-1", + "explanation": "You can't start at station 0 or 1, as there is not enough gas to travel to the next station.\nLet's start at station 2 and fill up with 4 unit of gas. Your tank = 0 + 4 = 4\nTravel to station 0. Your tank = 4 - 3 + 2 = 3\nTravel to station 1. Your tank = 3 - 3 + 3 = 3\nYou cannot travel back to station 2, as it requires 4 unit of gas but you only have 3.\nTherefore, you can't travel around the circuit once no matter where you start." + } + ], + "solution": "/**\n * @param {number[]} gas\n * @param {number[]} cost\n * @return {number}\n */\nconst canCompleteCircuit = function(gas, cost) {\n let total = 0\n let curLeft = 0\n let curtIdx = 0\n for (let i = 0; i < gas.length; i++) {\n total += gas[i] - cost[i]\n curLeft += gas[i] - cost[i]\n if (curLeft < 0) {\n curtIdx = i + 1\n curLeft = 0\n }\n }\n return total < 0 ? -1 : curtIdx\n}\n\n// another\n\nconst canCompleteCircuit = function(gas, cost) {\n const len = gas.length\n let tank = 0\n let count = 0\n for (let i = 0; i < len * 2; i++) {\n let idx = i % len\n if (count === len) return idx\n count += 1\n tank += gas[idx] - cost[idx]\n if (tank < 0) {\n tank = 0\n count = 0\n }\n }\n return -1\n}\n\n" + }, + { + "_id": "66f925ddfdfb8e1665720b2b", + "questionid": 96, + "title": "Word Break", + "slug": "word-break", + "description": "Given a string s and a dictionary of strings wordDict, return true if s can be segmented into a space-separated sequence of one or more dictionary words. Note that the same word in the dictionary may be reused multiple times in the segmentation. ", + "category": [ + "Hash Table", + "String", + "Dynamic Programming", + "Trie", + "Memoization" + ], + "complexity": "Medium", + "successrate": 44.5, + "totalsubmissions": 2363412, + "totalaccepted": 1051065, + "likes": 10183, + "dislikes": 448, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "leetcode", wordDict = ["leet","code"]", + "expected_output": "true", + "explanation": "Return true because "leetcode" can be segmented as "leet code"." + }, + { + "example_num": 2, + "expected_input": "s = "applepenapple", wordDict = ["apple","pen"]", + "expected_output": "true", + "explanation": "Return true because "applepenapple" can be segmented as "apple pen apple".\nNote that you are allowed to reuse a dictionary word." + }, + { + "example_num": 3, + "expected_input": "s = "catsandog", wordDict = ["cats","dog","sand","and","cat"]", + "expected_output": "false", + "explanation": "" + } + ], + "solution": "/**\n * @param {string} s\n * @param {string[]} wordDict\n * @return {boolean}\n */\nconst wordBreak = function(s, wordDict) {\n const map = new Map()\n return helper(s, 0, new Set(wordDict), map)\n};\n\nfunction helper(str, idx, set, map) {\n if(idx === str.length) return true\n if(map.has(idx)) return map.get(idx)\n let res = false\n for(let i = idx; i < str.length; i++) {\n const tmp = str.slice(idx, i + 1)\n if(set.has(tmp)) {\n const bool = helper(str, i + 1, set, map)\n if(bool) {\n res = true\n break\n }\n }\n }\n map.set(idx, res)\n return res\n}\n\n// another\n\n\n/**\n * @param {string} s\n * @param {string[]} wordDict\n * @return {boolean}\n */\nconst wordBreak = function(s, wordDict) {\n const len = s.length;\n const dp = new Array(len).fill(false);\n\n for (let i = 0; i < len; i++) {\n for (let word of wordDict) {\n if (word.length <= i + 1 \n && s.substring(i - word.length + 1, i + 1) === word) {\n let index = i - word.length;\n if (index < 0) {\n dp[i] = true;\n } else {\n dp[i] = dp[index];\n }\n if(dp[i]) break;\n }\n }\n }\n\n return dp[len - 1];\n};\n\n// another\n\n/**\n * @param {string} s\n * @param {string[]} wordDict\n * @return {boolean}\n */\nconst wordBreak = function(s, wordDict) {\n const len = s.length;\n const f = new Array(len + 1).fill(false);\n\n f[0] = true;\n\n for(let i = 1; i <= len; i++){\n for(let str of wordDict){\n if(str.length <= i \n && f[i - str.length] \n && s.slice(i - str.length, i) === str){\n f[i] = true;\n break;\n }\n }\n }\n\n return f[len];\n};\n\n\n// another\n\n/**\n * @param {string} s\n * @param {string[]} wordDict\n * @return {boolean}\n */\nconst wordBreak = function(s, wordDict) {\n const set = new Set(wordDict)\n const dp = Array(s.length + 1).fill(false)\n dp[0] = true\n for(let i = 1; i <= s.length; i++) {\n for(let j = 0; j < i; j++) {\n if(dp[j] && set.has(s.slice(j, i))) {\n dp[i] = true\n break\n }\n }\n }\n \n return dp[s.length]\n};\n\n" + }, + { + "_id": "66f925ddfdfb8e1665720b2d", + "questionid": 98, + "title": "Linked List Cycle", + "slug": "linked-list-cycle", + "description": "Given head, the head of a linked list, determine if the linked list has a cycle in it. There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the\u00a0next\u00a0pointer. Internally, pos\u00a0is used to denote the index of the node that\u00a0tail's\u00a0next\u00a0pointer is connected to.\u00a0Note that\u00a0pos\u00a0is not passed as a parameter. Return\u00a0true if there is a cycle in the linked list. Otherwise, return false. ", + "category": [ + "Hash Table", + "Linked List", + "Two Pointers" + ], + "complexity": "Easy", + "successrate": 45.8, + "totalsubmissions": 3048390, + "totalaccepted": 1395560, + "likes": 7823, + "dislikes": 773, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "head = [3,2,0,-4], pos = 1", + "expected_output": "true", + "explanation": "There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed)." + }, + { + "example_num": 2, + "expected_input": "head = [1,2], pos = 0", + "expected_output": "true", + "explanation": "There is a cycle in the linked list, where the tail connects to the 0th node." + }, + { + "example_num": 3, + "expected_input": "head = [1], pos = -1", + "expected_output": "false", + "explanation": "There is no cycle in the linked list." + } + ], + "solution": "/**\n * Definition for singly-linked list.\n * function ListNode(val) {\n * this.val = val;\n * this.next = null;\n * }\n */\n\n/**\n * @param {ListNode} head\n * @return {boolean}\n */\nconst hasCycle = function(head) {\n const seen = []\n while(head != null) {\n if(seen.indexOf(head) !== -1) {\n return true\n } else {\n seen.push(head)\n }\n head = head.next\n }\n return false\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720b31", + "questionid": 102, + "title": "Sort List", + "slug": "sort-list", + "description": "Given the head of a linked list, return the list after sorting it in ascending order. ", + "category": [ + "Linked List", + "Two Pointers", + "Divide and Conquer", + "Sorting", + "Merge Sort" + ], + "complexity": "Medium", + "successrate": 51.9, + "totalsubmissions": 930950, + "totalaccepted": 483584, + "likes": 6985, + "dislikes": 229, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "head = [4,2,1,3]", + "expected_output": "[1,2,3,4]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "head = [-1,5,3,4,0]", + "expected_output": "[-1,0,3,4,5]", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "head = []", + "expected_output": "[]", + "explanation": "" + } + ], + "solution": "/**\n * Definition for singly-linked list.\n * function ListNode(val, next) {\n * this.val = (val===undefined ? 0 : val)\n * this.next = (next===undefined ? null : next)\n * }\n */\n/**\n * @param {ListNode} head\n * @return {ListNode}\n */\nfunction sortList(head) {\n quickSort(head, null);\n return head;\n}\n\nfunction quickSort(head, tail) {\n if (head == tail) {\n return;\n }\n const slow = partition(head, tail);\n quickSort(head, slow);\n quickSort(slow.next, tail);\n}\n\nfunction swap(node1, node2) {\n let tmp = node1.val;\n node1.val = node2.val;\n node2.val = tmp;\n}\n\nfunction partition(head, tail) {\n let slow = head,\n fast = head.next;\n let p = head.val;\n while (fast != tail) {\n if (fast.val <= p) {\n slow = slow.next;\n swap(slow, fast);\n }\n fast = fast.next;\n }\n swap(head, slow);\n return slow;\n}\n\n// another\n\n/**\n * Definition for singly-linked list.\n * function ListNode(val, next) {\n * this.val = (val===undefined ? 0 : val)\n * this.next = (next===undefined ? null : next)\n * }\n */\n/**\n * @param {ListNode} head\n * @return {ListNode}\n */\nfunction sortList(head) {\n if(head == null || head.next == null) return head\n let slow = head, fast = head, pre = null\n while(fast && fast.next) {\n pre = slow\n slow = slow.next\n fast = fast.next.next\n }\n pre.next = null\n const left = sortList(head)\n const right = sortList(slow)\n return merge(left, right)\n}\n\nfunction merge(left, right) {\n const dummy = new ListNode()\n let cur = dummy\n while(left && right) {\n if (left.val <= right.val) {\n cur.next = left\n left = left.next\n } else {\n cur.next = right\n right = right.next\n }\n cur = cur.next\n }\n if(left) {\n cur.next = left\n }\n\n if(right) {\n cur.next = right\n }\n\n return dummy.next\n}\n\n\n// another\n\n function sortList(head) {\n quickSort(head, null);\n return head;\n }\n \n function quickSort( head, tail){\n if (head == tail) {\n return;\n }\n let slow = head, fast = head.next;\n let p = head.val;\n while (fast != tail){\n if (fast.val <= p){\n slow = slow.next;\n swap(slow, fast);\n }\n fast = fast.next;\n }\n swap(head, slow);\n quickSort(head, slow);\n quickSort(slow.next, tail);\n }\n \n function swap( node1, node2){\n let tmp = node1.val;\n node1.val = node2.val;\n node2.val = tmp;\n }\n\n// another\n\n/**\n * Definition for singly-linked list.\n * function ListNode(val) {\n * this.val = val;\n * this.next = null;\n * }\n */\n/**\n * @param {ListNode} head\n * @return {ListNode}\n */\n\nconst sortList = function(head) {\n let dummy = new ListNode(0);\n dummy.next = head;\n const list = [];\n let done = (null === head);\n // Keep partitioning our list into bigger sublists length. Starting with a size of 1 and doubling each time\n for (let step = 1; !done; step *= 2) {\n done = true;\n let prev = dummy;\n let remaining = prev.next;\n do {\n // Split off two sublists of size step\n for (let i = 0; i < 2; ++i) {\n list[i] = remaining;\n let tail = null;\n for (let j = 0; j < step && null != remaining; ++j, remaining = remaining.next) {\n tail = remaining;\n }\n // Terminate our sublist\n if (null != tail) {\n tail.next = null;\n }\n }\n\n // We're done if these are the first two sublists in this pass and they\n // encompass the entire primary list\n done &= (null == remaining);\n\n // If we have two sublists, merge them into one\n if (null != list[1]) {\n while (null != list[0] || null != list[1]) {\n let idx = (null == list[1] || null != list[0] && list[0].val <= list[1].val) ? 0 : 1;\n prev.next = list[idx];\n list[idx] = list[idx].next;\n prev = prev.next;\n }\n\n // Terminate our new sublist\n prev.next = null;\n } else {\n // Only a single sublist, no need to merge, just attach to the end\n prev.next = list[0];\n }\n } while (null !== remaining);\n }\n return dummy.next;\n}\n\n\n" + }, + { + "_id": "66f925ddfdfb8e1665720b32", + "questionid": 103, + "title": "Max Points on a Line", + "slug": "max-points-on-a-line", + "description": "Given an array of points where points[i] = [xi, yi] represents a point on the X-Y plane, return the maximum number of points that lie on the same straight line. ", + "category": [ + "Array", + "Hash Table", + "Math", + "Geometry" + ], + "complexity": "Hard", + "successrate": 20.4, + "totalsubmissions": 1113777, + "totalaccepted": 226781, + "likes": 997, + "dislikes": 176, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "points = [[1,1],[2,2],[3,3]]", + "expected_output": "3", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "points = [[1,1],[3,2],[5,3],[4,1],[2,3],[1,4]]", + "expected_output": "4", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[][]} points\n * @return {number}\n */\nconst maxPoints = function (points) {\n if (points.length < 2 || points == null) return points.length\n let max = 2\n for (let i = 0; i < points.length; i++) {\n let [p1x, p1y] = points[i]\n let samePoint = 1,\n map = { base: 0 } // to avoid when map = {}, the max value is -Infinity\n for (let j = i + 1; j < points.length; j++) {\n if (points[i][0] == points[j][0] && points[i][1] == points[j][1]) {\n samePoint++\n } else {\n let [p2x, p2y] = points[j]\n let slope = (1000000.0 * (p2y - p1y)) / (p2x - p1x)\n if (!Number.isFinite(slope)) slope = 'v'\n else if (Number.isNaN(slope)) slope = 'h'\n map[slope] = map[slope] + 1 || 1\n }\n }\n max = Math.max(Math.max(...Object.values(map)) + samePoint, max)\n }\n return max\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720b36", + "questionid": 107, + "title": "Find Peak Element", + "slug": "find-peak-element", + "description": "A peak element is an element that is strictly greater than its neighbors. Given an integer array nums, find a peak element, and return its index. If\u00a0the array contains multiple peaks, return the index to any of the peaks. You may imagine that nums[-1] = nums[n] = -\u02c6\u017e. You must write an algorithm that runs in\u00a0O(log n) time. ", + "category": [ + "Array", + "Binary Search" + ], + "complexity": "Medium", + "successrate": 45.9, + "totalsubmissions": 1665853, + "totalaccepted": 764441, + "likes": 5815, + "dislikes": 3661, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,2,3,1]", + "expected_output": "2", + "explanation": "3 is a peak element and your function should return the index number 2." + }, + { + "example_num": 2, + "expected_input": "nums = [1,2,1,3,5,6,4]", + "expected_output": "5", + "explanation": "Your function can return either index number 1 where the peak element is 2, or index number 5 where the peak element is 6." + } + ], + "solution": "/**\n * @param {number[]} nums\n * @return {number}\n */\nconst findPeakElement = function(nums) {\n let low = 0;\n let high = nums.length-1;\n\n while(low < high) {\n let mid1 = low + ((high - low) >> 1);\n let mid2 = mid1 + 1;\n if(nums[mid1] < nums[mid2]) low = mid2;\n else high = mid1;\n }\n return low;\n};\n\n// another\n\n/**\n * @param {number[]} nums\n * @return {number}\n */\nconst findPeakElement = function(nums) {\n if(nums == null) return -1\n const len = nums.length\n if(len === 1) return 0\n for(let i = 1; i < len; i++) {\n if(i === 1 && nums[i] < nums[i - 1]) return 0\n else if(i === len - 1 && nums[i] > nums[i - 1]) return len - 1\n else if(nums[i] > nums[i - 1] && nums[i] > nums[i + 1]) return i\n }\n return -1\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720b3e", + "questionid": 115, + "title": "Repeated DNA Sequences", + "slug": "repeated-dna-sequences", + "description": "The DNA sequence is composed of a series of nucleotides abbreviated as 'A', 'C', 'G', and 'T'. When studying DNA, it is useful to identify repeated sequences within the DNA. Given a string s that represents a DNA sequence, return all the 10-letter-long sequences (substrings) that occur more than once in a DNA molecule. You may return the answer in any order. ", + "category": [ + "Hash Table", + "String", + "Bit Manipulation", + "Sliding Window", + "Rolling Hash", + "Hash Function" + ], + "complexity": "Medium", + "successrate": 44.6, + "totalsubmissions": 587059, + "totalaccepted": 261815, + "likes": 1945, + "dislikes": 406, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = \"AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT\"", + "expected_output": "[\"AAAAACCCCC\",\"CCCCCAAAAA\"]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "s = \"AAAAAAAAAAAAA\"", + "expected_output": "[\"AAAAAAAAAA\"]", + "explanation": "" + } + ], + "solution": "/**\n * @param {string} s\n * @return {string[]}\n */\nconst findRepeatedDnaSequences = function(s) {\n if (!s || s.length < 10) {\n return [];\n }\n const map = new Map([[\"A\", 0], [\"C\", 1], [\"G\", 2], [\"T\", 3]]);\n const dna = new Set();\n const repeated = new Set();\n const mask = 0xfffff;\n let cur = 0;\n for (let i = 0, n = s.length; i < n; i++) {\n cur <<= 2;\n cur = cur | map.get(s[i]);\n cur = cur & mask;\n if (i >= 9) {\n if (dna.has(cur)) {\n const seq = s.slice(i - 9, i + 1);\n if (!repeated.has(seq)) {\n repeated.add(seq);\n }\n } else {\n dna.add(cur);\n }\n }\n }\n return Array.from(repeated);\n};\n\n// another\n\n/**\n * @param {string} s\n * @return {string[]}\n */\nconst findRepeatedDnaSequences = function(s) {\n let store = new Set(), result = new Set()\n for(let i = 0; i < s.length - 9; i++) {\n const str = s.substring(i, i + 10)\n if(store.has(str)) {\n result.add(str)\n } else {\n store.add(str)\n }\n }\n return Array.from(result)\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720b41", + "questionid": 118, + "title": "Binary Tree Right Side View", + "slug": "binary-tree-right-side-view", + "description": "Given the root of a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom. ", + "category": [ + "Tree", + "Depth-First Search", + "Breadth-First Search", + "Binary Tree" + ], + "complexity": "Medium", + "successrate": 59.5, + "totalsubmissions": 1098642, + "totalaccepted": 653709, + "likes": 6288, + "dislikes": 337, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [1,2,3,null,5,null,4]", + "expected_output": "[1,3,4]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "root = [1,null,3]", + "expected_output": "[1,3]", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "root = []", + "expected_output": "[]", + "explanation": "" + } + ], + "solution": "/**\n * Definition for a binary tree node.\n * function TreeNode(val) {\n * this.val = val;\n * this.left = this.right = null;\n * }\n */\n/**\n * @param {TreeNode} root\n * @return {number[]}\n */\nconst rightSideView = function(root) {\n if(root == null) return []\n const queue = [root]\n const res = []\n while(queue.length) {\n const len = queue.length\n for(let i = 0; i < len; i++) {\n const el = queue.shift()\n if(i === len - 1) res.push(el.val)\n if(el.left) queue.push(el.left)\n if(el.right) queue.push(el.right)\n }\n }\n return res\n};\n\n// another\n\nconst rightSideView = function(root) {\n const res = []\n const helper = function(node, level) {\n if (!node) {\n return\n }\n if (!res[level]) {\n res.push(node.val)\n }\n helper(node.right, level + 1)\n helper(node.left, level + 1)\n }\n helper(root, 0)\n return res\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720b45", + "questionid": 122, + "title": "Count Primes", + "slug": "count-primes", + "description": "Given an integer n, return the number of prime numbers that are strictly less than n. ", + "category": [ + "Array", + "Math", + "Enumeration", + "Number Theory" + ], + "complexity": "Medium", + "successrate": 33, + "totalsubmissions": 1819491, + "totalaccepted": 600270, + "likes": 4703, + "dislikes": 985, + "hints": "Let's start with a isPrime function. To determine if a number is prime, we need to check if it is not divisible by any number less than n. The runtime complexity of isPrime function would be O(n) and hence counting the total prime numbers up to n would be O(n2). Could we do better? As we know the number must not be divisible by any number > n / 2, we can immediately cut the total iterations half by dividing only up to n / 2. Could we still do better? Let's write down all of 12's factors:\n\r\n2 \u00c3\u2014 6 = 12\r\n3 \u00c3\u2014 4 = 12\r\n4 \u00c3\u2014 3 = 12\r\n6 \u00c3\u2014 2 = 12\r\n\nAs you can see, calculations of 4 \u00c3\u2014 3 and 6 \u00c3\u2014 2 are not necessary. Therefore, we only need to consider factors up to \u02c6\u0161n because, if n is divisible by some number p, then n = p \u00c3\u2014 q and since p \u2030\u00a4 q, we could derive that p \u2030\u00a4 \u02c6\u0161n.\nOur total runtime has now improved to O(n1.5), which is slightly better. Is there a faster approach?\n\r\npublic int countPrimes(int n) {\r\n int count = 0;\r\n for (int i = 1; i < n; i++) {\r\n if (isPrime(i)) count++;\r\n }\r\n return count;\r\n}\r\n\r\nprivate boolean isPrime(int num) {\r\n if (num <= 1) return false;\r\n // Loop's ending condition is i * i <= num instead of i <= sqrt(num)\r\n // to avoid repeatedly calling an expensive function sqrt().\r\n for (int i = 2; i * i <= num; i++) {\r\n if (num % i == 0) return false;\r\n }\r\n return true;\r\n} The Sieve of Eratosthenes is one of the most efficient ways to find all prime numbers up to n. But don't let that name scare you, I promise that the concept is surprisingly simple.\n\n\nSieve of Eratosthenes: algorithm steps for primes below 121. \"Sieve of Eratosthenes Animation\" by SKopp is licensed under CC BY 2.0.\n\nWe start off with a table of n numbers. Let's look at the first number, 2. We know all multiples of 2 must not be primes, so we mark them off as non-primes. Then we look at the next number, 3. Similarly, all multiples of 3 such as 3 \u00c3\u2014 2 = 6, 3 \u00c3\u2014 3 = 9, ... must not be primes, so we mark them off as well. Now we look at the next number, 4, which was already marked off. What does this tell you? Should you mark off all multiples of 4 as well? 4 is not a prime because it is divisible by 2, which means all multiples of 4 must also be divisible by 2 and were already marked off. So we can skip 4 immediately and go to the next number, 5. Now, all multiples of 5 such as 5 \u00c3\u2014 2 = 10, 5 \u00c3\u2014 3 = 15, 5 \u00c3\u2014 4 = 20, 5 \u00c3\u2014 5 = 25, ... can be marked off. There is a slight optimization here, we do not need to start from 5 \u00c3\u2014 2 = 10. Where should we start marking off? In fact, we can mark off multiples of 5 starting at 5 \u00c3\u2014 5 = 25, because 5 \u00c3\u2014 2 = 10 was already marked off by multiple of 2, similarly 5 \u00c3\u2014 3 = 15 was already marked off by multiple of 3. Therefore, if the current number is p, we can always mark off multiples of p starting at p2, then in increments of p: p2 + p, p2 + 2p, ... Now what should be the terminating loop condition? It is easy to say that the terminating loop condition is p < n, which is certainly correct but not efficient. Do you still remember Hint #3? Yes, the terminating loop condition can be p < \u02c6\u0161n, as all non-primes \u2030\u00a5 \u02c6\u0161n must have already been marked off. When the loop terminates, all the numbers in the table that are non-marked are prime.\nThe Sieve of Eratosthenes uses an extra O(n) memory and its runtime complexity is O(n log log n). For the more mathematically inclined readers, you can read more about its algorithm complexity on Wikipedia.\n\r\npublic int countPrimes(int n) {\r\n boolean[] isPrime = new boolean[n];\r\n for (int i = 2; i < n; i++) {\r\n isPrime[i] = true;\r\n }\r\n // Loop's ending condition is i * i < n instead of i < sqrt(n)\r\n // to avoid repeatedly calling an expensive function sqrt().\r\n for (int i = 2; i * i < n; i++) {\r\n if (!isPrime[i]) continue;\r\n for (int j = i * i; j < n; j += i) {\r\n isPrime[j] = false;\r\n }\r\n }\r\n int count = 0;\r\n for (int i = 2; i < n; i++) {\r\n if (isPrime[i]) count++;\r\n }\r\n return count;\r\n}", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 10", + "expected_output": "4", + "explanation": "There are 4 prime numbers less than 10, they are 2, 3, 5, 7." + }, + { + "example_num": 2, + "expected_input": "n = 0", + "expected_output": "0", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "n = 1", + "expected_output": "0", + "explanation": "" + } + ], + "solution": "/**\n * @param {number} n\n * @return {number}\n */\nconst countPrimes = function(n) {\n const arr = Array(n).fill(0)\n \n for(let i = 2; i * i < n; i++) {\n if(arr[i] !== 0) continue\n let j = i * i\n while(j < n) {\n arr[j] = 1\n j += i\n }\n }\n \n let res = 0\n for(let i = 2; i < n; i++) {\n if(arr[i] === 0) res++\n }\n return res\n};\n\n// another\n\n/**\n * @param {number} n\n * @return {number}\n */\nconst countPrimes = function (n) {\n const memo = Array(n).fill(false)\n let res = 0\n for (let i = 2; i < n; i++) {\n if (memo[i] === false) {\n res++\n for (let j = 2; i * j < n; j++) {\n memo[i * j] = true\n }\n }\n }\n\n return res\n}\n\n\n// another\n\n\n/**\n * @param {number} n\n * @return {number}\n */\nconst countPrimes = function(n) {\n /**\n * if n = 2, the prime 2 is not less than n,\n * so there are no primes less than n\n */\n if (n < 3) return 0;\n\n /**\n * Start with the assumption that half the numbers below n are\n * prime candidates, since we know that half of them are even,\n * and so _in general_ aren't prime.\n *\n * An exception to this is 2, which is the only even prime.\n * But also 1 is an odd which isn't prime.\n * These two exceptions (a prime even and a for-sure not-prime odd)\n * cancel each other out for n > 2, so our assumption holds.\n *\n * We'll decrement count when we find an odd which isn't prime.\n *\n * If n = 3, c = 1.\n * If n = 5, c = 2.\n * If n = 10, c = 5.\n */\n let c = Math.floor(n / 2);\n\n /**\n * Java initializes boolean arrays to {false}.\n * In this method, we'll use truth to mark _composite_ numbers.\n *\n * This is the opposite of most Sieve of Eratosthenes methods,\n * which use truth to mark _prime_ numbers.\n *\n * We will _NOT_ mark evens as composite, even though they are.\n * This is because `c` is current after each `i` iteration below.\n */\n let s = [];\n\n /**\n * Starting with an odd prime-candidate above 2, increment by two\n * to skip evens (which we know are not prime candidates).\n */\n for (let i = 3; i * i < n; i += 2) {\n if (s[i]) {\n // c has already been decremented for this composite odd\n continue;\n }\n\n /**\n * For each prime i, iterate through the odd composites\n * we know we can form from i, and mark them as composite\n * if not already marked.\n *\n * We know that i * i is composite.\n * We also know that i * i + i is composite, since they share\n * a common factor of i.\n * Thus, we also know that i * i + a*i is composite for all real a,\n * since they share a common factor of i.\n *\n * Note, though, that i * i + i _must_ be composite for an\n * independent reason: it must be even.\n * (all i are odd, thus all i*i are odd,\n * thus all (odd + odd) are even).\n *\n * Recall that, by initializing c to n/2, we already accounted for\n * all of the evens less than n being composite, and so marking\n * i * i + (odd)*i as composite is needless bookkeeping.\n *\n * So, we can skip checking i * i + a*i for all odd a,\n * and just increment j by even multiples of i,\n * since all (odd + even) are odd.\n */\n for (let j = i * i; j < n; j += 2 * i) {\n if (!s[j]) {\n c--;\n s[j] = true;\n }\n }\n }\n return c;\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720b48", + "questionid": 125, + "title": "Course Schedule", + "slug": "course-schedule", + "description": "There are a total of numCourses courses you have to take, labeled from 0 to numCourses - 1. You are given an array prerequisites where prerequisites[i] = [ai, bi] indicates that you must take course bi first if you want to take course ai. Return true if you can finish all courses. Otherwise, return false. ", + "category": [ + "Depth-First Search", + "Breadth-First Search", + "Graph", + "Topological Sort" + ], + "complexity": "Medium", + "successrate": 45, + "totalsubmissions": 1871795, + "totalaccepted": 842989, + "likes": 9007, + "dislikes": 362, + "hints": "This problem is equivalent to finding if a cycle exists in a directed graph. If a cycle exists, no topological ordering exists and therefore it will be impossible to take all courses. Topological Sort via DFS - A great video tutorial (21 minutes) on Coursera explaining the basic concepts of Topological Sort. Topological sort could also be done via BFS.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "numCourses = 2, prerequisites = [[1,0]]", + "expected_output": "true", + "explanation": "There are a total of 2 courses to take. \nTo take course 1 you should have finished course 0. So it is possible." + }, + { + "example_num": 2, + "expected_input": "numCourses = 2, prerequisites = [[1,0],[0,1]]", + "expected_output": "false", + "explanation": "There are a total of 2 courses to take. \nTo take course 1 you should have finished course 0, and to take course 0 you should also have finished course 1. So it is impossible." + } + ], + "solution": "/**\n * @param {number} numCourses\n * @param {number[][]} prerequisites\n * @return {boolean}\n */\nconst canFinish = function (numCourses, prerequisites) {\n const set = new Set()\n const indegree = Array(numCourses).fill(0)\n const graph = {}\n\n for (const [s, e] of prerequisites) {\n indegree[e]++\n if (graph[s] == null) graph[s] = []\n graph[s].push(e)\n }\n\n let q = []\n for (let i = 0; i < numCourses; i++) {\n if (indegree[i] === 0) q.push(i)\n }\n\n while (q.length) {\n const nxt = []\n for (let i = 0, size = q.length; i < size; i++) {\n const cur = q[i]\n set.add(cur)\n for (const e of graph[cur] || []) {\n indegree[e]--\n if (indegree[e] === 0 && !set.has(e)) {\n nxt.push(e)\n }\n }\n }\n\n q = nxt\n }\n\n return set.size === numCourses\n}\n\n// another\n\n\n/**\n * @param {number} numCourses\n * @param {number[][]} prerequisites\n * @return {boolean}\n */\nconst canFinish = function(numCourses, prerequisites) {\n const [graph, inDegree] = buildGraph(numCourses, prerequisites)\n \n const q = []\n for(let i = 0; i < numCourses; i++) {\n if(inDegree.get(i) == null) q.push(i)\n }\n let num = 0\n while(q.length) {\n const pre = q.pop()\n num++\n for(const next of (graph.get(pre) || [])) {\n inDegree.set(next, inDegree.get(next) - 1)\n if(inDegree.get(next) === 0) q.push(next)\n }\n }\n return num === numCourses\n \n \n function buildGraph(n, arr) {\n const res = new Map(), inDegree = new Map()\n for(const [cur, pre] of arr) {\n if(res.get(pre) == null) res.set(pre, new Set())\n res.get(pre).add(cur)\n if(inDegree.get(cur) == null) inDegree.set(cur, 0)\n inDegree.set(cur, inDegree.get(cur) + 1)\n }\n return [res, inDegree]\n }\n};\n\n// another\n\n/**\n * @param {number} numCourses\n * @param {number[][]} prerequisites\n * @return {boolean}\n */\nconst canFinish = function(numCourses, prerequisites) {\n const seen = new Set()\n const seeing = new Set()\n const adj = [...Array(numCourses)].map(r => [])\n for (let [u, v] of prerequisites) {\n adj[v].push(u)\n }\n for (let c = 0; c < numCourses; c++) {\n if (!dfs(c)) {\n return false\n }\n }\n return true\n function dfs(v) {\n if (seen.has(v)) return true\n if (seeing.has(v)) return false\n seeing.add(v)\n for (let nv of adj[v]) {\n if (!dfs(nv)) {\n return false\n }\n }\n seeing.delete(v)\n seen.add(v)\n return true\n }\n}\n\n// another\n\n/**\n * @param {number} numCourses\n * @param {number[][]} prerequisites\n * @return {boolean}\n */\nconst canFinish = function(vertices, edges) {\n const sortedOrder = []\n if (vertices <= 0) {\n return sortedOrder\n }\n const inDegree = Array(vertices).fill(0)\n const graph = Array(vertices)\n .fill(0)\n .map(() => Array())\n edges.forEach(edge => {\n let parent = edge[0]\n let child = edge[1]\n graph[parent].push(child)\n inDegree[child]++\n })\n const sources = []\n for (let i = 0; i < inDegree.length; i++) {\n if (inDegree[i] === 0) {\n sources.push(i)\n }\n }\n while (sources.length > 0) {\n const vertex = sources.shift()\n sortedOrder.push(vertex)\n\n graph[vertex].forEach(child => {\n inDegree[child] -= 1\n if (inDegree[child] === 0) {\n sources.push(child)\n }\n })\n }\n return sortedOrder.length === vertices ? true : false\n}\n\n// another\n\n/**\n * @param {number} numCourses\n * @param {number[][]} prerequisites\n * @return {boolean}\n */\nconst canFinish = function(numCourses, prerequisites) {\n const set = new Set(), hash = {}\n for(let i = 0; i < prerequisites.length; i++) {\n const [cur, pre] = prerequisites[i]\n if(hash[cur] == null) hash[cur] = new Set()\n hash[cur].add(pre)\n }\n const q = []\n\n for(let i = 0; i < numCourses; i++) {\n if(hash[i] == null) q.push(i)\n }\n let visited = 0\n\n while(q.length) {\n const cur = q.shift()\n visited++\n Object.keys(hash).forEach(k => {\n if(hash[k].has(cur)) {\n hash[k].delete(cur)\n }\n if(hash[k].size === 0) {\n delete hash[k]\n q.push(+k)\n }\n })\n }\n return visited === numCourses\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720b49", + "questionid": 126, + "title": "Minimum Size Subarray Sum", + "slug": "minimum-size-subarray-sum", + "description": "Given an array of positive integers nums and a positive integer target, return the minimal length of a contiguous subarray [numsl, numsl+1, ..., numsr-1, numsr] of which the sum is greater than or equal to target. If there is no such subarray, return 0 instead. ", + "category": [ + "Array", + "Binary Search", + "Sliding Window", + "Prefix Sum" + ], + "complexity": "Medium", + "successrate": 43.2, + "totalsubmissions": 1177660, + "totalaccepted": 508413, + "likes": 6324, + "dislikes": 185, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "target = 7, nums = [2,3,1,2,4,3]", + "expected_output": "2", + "explanation": "The subarray [4,3] has the minimal length under the problem constraint." + }, + { + "example_num": 2, + "expected_input": "target = 4, nums = [1,4,4]", + "expected_output": "1", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "target = 11, nums = [1,1,1,1,1,1,1,1]", + "expected_output": "0", + "explanation": "" + } + ], + "solution": "/**\n * @param {number} s\n * @param {number[]} nums\n * @return {number}\n */\nconst minSubArrayLen = function(s, nums) {\n let sum = 0, from = 0, win = Number.MAX_SAFE_INTEGER;\n for (let i = 0; i < nums.length; i++) {\n sum += nums[i];\n while (sum >= s) {\n win = Math.min(win, i - from + 1);\n sum -= nums[from++];\n }\n }\n return (win === Number.MAX_SAFE_INTEGER) ? 0 : win;\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720b4b", + "questionid": 128, + "title": "Word Search II", + "slug": "word-search-ii", + "description": "Given an m x n board\u00a0of characters and a list of strings words, return all words on the board. Each word must be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once in a word. ", + "category": [ + "Array", + "String", + "Backtracking", + "Trie", + "Matrix" + ], + "complexity": "Hard", + "successrate": 38.1, + "totalsubmissions": 1120097, + "totalaccepted": 426210, + "likes": 5820, + "dislikes": 213, + "hints": "You would need to optimize your backtracking to pass the larger test. Could you stop backtracking earlier? If the current candidate does not exist in all words' prefix, you could stop backtracking immediately. What kind of data structure could answer such query efficiently? Does a hash table work? Why or why not? How about a Trie? If you would like to learn how to implement a basic trie, please work on this problem: Implement Trie (Prefix Tree) first.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "board = [["o","a","a","n"],["e","t","a","e"],["i","h","k","r"],["i","f","l","v"]], words = ["oath","pea","eat","rain"]", + "expected_output": "["eat","oath"]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "board = [["a","b"],["c","d"]], words = ["abcb"]", + "expected_output": "[]", + "explanation": "" + } + ], + "solution": "/**\n * @param {character[][]} board\n * @param {string[]} words\n * @return {string[]}\n */\nclass Trie {\n constructor() {\n this.word = null\n this.children = new Map()\n }\n add(word) {\n let cur = this\n for (let i = 0; i < word.length; i++) {\n if (!cur.children.has(word[i])) {\n cur.children.set(word[i], new Trie())\n }\n cur = cur.children.get(word[i])\n }\n cur.word = word\n }\n addArr(words) {\n words.forEach(word => this.add(word))\n }\n}\n\nconst findWords = function(board, words) {\n const trie = new Trie()\n trie.addArr(words)\n const results = []\n const dirs = [[-1, 0], [1, 0], [0, 1], [0, -1]]\n for (let i = 0; i < board.length; i++) {\n for (let j = 0; j < board[0].length; j++) {\n dfs(board, i, j, trie, results, dirs)\n }\n }\n return results\n}\n\nconst dfs = (board, i, j, trie, results, dirs) => {\n if(i < 0 || j < 0 || i >= board.length || j >= board[0].length) return\n const char = board[i][j]\n if (!trie.children.has(char)) return\n\n const nextTrie = trie.children.get(char)\n if (nextTrie.word) {\n results.push(nextTrie.word)\n nextTrie.word = null\n }\n \n for(let dir of dirs) {\n board[i][j] = '#'\n dfs(board, i + dir[0], j + dir[1], nextTrie, results, dirs)\n board[i][j] = char\n }\n \n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720b10", + "questionid": 69, + "title": "Same Tree", + "slug": "same-tree", + "description": "Given the roots of two binary trees p and q, write a function to check if they are the same or not. Two binary trees are considered the same if they are structurally identical, and the nodes have the same value. ", + "category": [ + "Tree", + "Depth-First Search", + "Breadth-First Search", + "Binary Tree" + ], + "complexity": "Easy", + "successrate": 55.5, + "totalsubmissions": 1816972, + "totalaccepted": 1008051, + "likes": 5477, + "dislikes": 132, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "p = [1,2,3], q = [1,2,3]", + "expected_output": "true", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "p = [1,2], q = [1,null,2]", + "expected_output": "false", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "p = [1,2,1], q = [1,1,2]", + "expected_output": "false", + "explanation": "" + } + ], + "solution": "/**\n * Definition for a binary tree node.\n * function TreeNode(val, left, right) {\n * this.val = (val===undefined ? 0 : val)\n * this.left = (left===undefined ? null : left)\n * this.right = (right===undefined ? null : right)\n * }\n */\n/**\n * @param {TreeNode} p\n * @param {TreeNode} q\n * @return {boolean}\n */\nconst isSameTree = function(p, q) {\n if(p == null && q == null) return true\n if(p == null || q == null || p.val !== q.val) return false\n return isSameTree(p.left, q.left) && isSameTree(p.right, q.right)\n};\n\n// another\n\n/**\n * Definition for a binary tree node.\n * function TreeNode(val, left, right) {\n * this.val = (val===undefined ? 0 : val)\n * this.left = (left===undefined ? null : left)\n * this.right = (right===undefined ? null : right)\n * }\n */\n/**\n * @param {TreeNode} p\n * @param {TreeNode} q\n * @return {boolean}\n */\nconst isSameTree = function(p, q) {\n if(p == null || q == null) return p === q\n if(p.val !== q.val) return false\n return isSameTree(p.left, q.left) && isSameTree(p.right, q.right)\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720b15", + "questionid": 74, + "title": "Construct Binary Tree from Preorder and Inorder Traversal", + "slug": "construct-binary-tree-from-preorder-and-inorder-traversal", + "description": "Given two integer arrays preorder and inorder where preorder is the preorder traversal of a binary tree and inorder is the inorder traversal of the same tree, construct and return the binary tree. ", + "category": [ + "Array", + "Hash Table", + "Divide and Conquer", + "Tree", + "Binary Tree" + ], + "complexity": "Medium", + "successrate": 57.5, + "totalsubmissions": 1199122, + "totalaccepted": 688958, + "likes": 8192, + "dislikes": 218, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]", + "expected_output": "[3,9,20,null,null,15,7]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "preorder = [-1], inorder = [-1]", + "expected_output": "[-1]", + "explanation": "" + } + ], + "solution": "/**\n * Definition for a binary tree node.\n * function TreeNode(val) {\n * this.val = val;\n * this.left = this.right = null;\n * }\n */\n/**\n * @param {number[]} preorder\n * @param {number[]} inorder\n * @return {TreeNode}\n */\nconst buildTree = function(preorder, inorder) {\n if(preorder.length === 0 && inorder.length === 0) return null\n const val = preorder[0]\n const node = new TreeNode(val)\n const inIdx = inorder.indexOf(val)\n const leftIn = inorder.slice(0, inIdx)\n const rightIn = inorder.slice(inIdx + 1)\n \n const leftPre = preorder.slice(1, leftIn.length + 1)\n const rightPre = preorder.slice(leftIn.length + 1)\n \n // console.log(leftIn, rightIn, leftPre, rightPre)\n node.left = buildTree(leftPre, leftIn)\n node.right = buildTree(rightPre, rightIn)\n return node\n};\n\n\n// another\n\n\n/**\n * Definition for a binary tree node.\n * function TreeNode(val) {\n * this.val = val;\n * this.left = this.right = null;\n * }\n */\n/**\n * @param {number[]} preorder\n * @param {number[]} inorder\n * @return {TreeNode}\n */\nlet pre\nlet ins\nlet inmap = {}\nconst buildTree = function(preorder, inorder) {\n pre = preorder\n ins = inorder\n for(let i = 0; i < inorder.length; i++) {\n inmap[inorder[i]] = i\n }\n let root = helper(0,0,ins.length - 1)\n return root\n};\n\nfunction helper(preStart, inStart, inEnd) {\n if (preStart > pre.length -1 || inStart > inEnd) {\n return null\n }\n let val = pre[preStart]\n let root = new TreeNode(val)\n let inIndex = inmap[val]\n root.left = helper(preStart + 1, inStart, inIndex - 1)\n root.right = helper(preStart+inIndex-inStart+1, inIndex+1, inEnd)\n return root\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720b18", + "questionid": 77, + "title": "Convert Sorted Array to Binary Search Tree", + "slug": "convert-sorted-array-to-binary-search-tree", + "description": "Given an integer array nums where the elements are sorted in ascending order, convert it to a height-balanced binary search tree. A height-balanced binary tree is a binary tree in which the depth of the two subtrees of every node never differs by more than one. ", + "category": [ + "Array", + "Divide and Conquer", + "Tree", + "Binary Search Tree", + "Binary Tree" + ], + "complexity": "Easy", + "successrate": 65.9, + "totalsubmissions": 1096431, + "totalaccepted": 722308, + "likes": 6158, + "dislikes": 349, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [-10,-3,0,5,9]", + "expected_output": "[0,-3,9,-10,null,5]", + "explanation": "[0,-10,5,null,-3,null,9] is also accepted:\n\"\"" + }, + { + "example_num": 2, + "expected_input": "nums = [1,3]", + "expected_output": "[3,1]", + "explanation": "[1,null,3] and [3,1] are both height-balanced BSTs." + } + ], + "solution": "/**\n * Definition for a binary tree node.\n * function TreeNode(val) {\n * this.val = val;\n * this.left = this.right = null;\n * }\n */\n/**\n * @param {number[]} nums\n * @return {TreeNode}\n */\nconst sortedArrayToBST = function(nums) {\n if (nums.length == 0) {\n return null;\n }\n const head = helper(nums, 0, nums.length - 1);\n return head;\n};\n\nfunction helper(num, low, high) {\n if (low > high) {\n // Done\n return null;\n }\n let mid = Math.floor((low + high) / 2);\n let node = new TreeNode(num[mid]);\n node.left = helper(num, low, mid - 1);\n node.right = helper(num, mid + 1, high);\n return node;\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720b1f", + "questionid": 84, + "title": "Best Time to Buy and Sell Stock", + "slug": "best-time-to-buy-and-sell-stock", + "description": "You are given an array prices where prices[i] is the price of a given stock on the ith day. You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock. Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0. ", + "category": [ + "Array", + "Dynamic Programming" + ], + "complexity": "Easy", + "successrate": 54, + "totalsubmissions": 3860000, + "totalaccepted": 2084089, + "likes": 15488, + "dislikes": 522, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "prices = [7,1,5,3,6,4]", + "expected_output": "5", + "explanation": "Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.\nNote that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell." + }, + { + "example_num": 2, + "expected_input": "prices = [7,6,4,3,1]", + "expected_output": "0", + "explanation": "In this case, no transactions are done and the max profit = 0." + } + ], + "solution": "/**\n * @param {number[]} prices\n * @return {number}\n */\nconst maxProfit = function(prices) {\n let minPrice = Number.MAX_SAFE_INTEGER;\n let maxP = 0;\n for (let i = 0; i < prices.length; i++) {\n if (prices[i] < minPrice) {\n minPrice = prices[i];\n } else if (prices[i] - minPrice > maxP) {\n maxP = prices[i] - minPrice;\n }\n }\n return maxP;\n};\n\n// another\n\n/**\n * @param {number[]} prices\n * @return {number}\n */\nconst maxProfit = function(prices) {\n let res = 0, maxCur = 0\n for(let i = 1; i < prices.length; i++) {\n maxCur = Math.max(0, maxCur + (prices[i] - prices[i - 1]))\n res = Math.max(res, maxCur)\n }\n return res\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720b20", + "questionid": 85, + "title": "Best Time to Buy and Sell Stock II", + "slug": "best-time-to-buy-and-sell-stock-ii", + "description": "You are given an integer array prices where prices[i] is the price of a given stock on the ith day. On each day, you may decide to buy and/or sell the stock. You can only hold at most one share of the stock at any time. However, you can buy it then immediately sell it on the same day. Find and return the maximum profit you can achieve. ", + "category": [ + "Array", + "Dynamic Programming", + "Greedy" + ], + "complexity": "Medium", + "successrate": 61.9, + "totalsubmissions": 1815327, + "totalaccepted": 1123641, + "likes": 7301, + "dislikes": 2353, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "prices = [7,1,5,3,6,4]", + "expected_output": "7", + "explanation": "Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.\nThen buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.\nTotal profit is 4 + 3 = 7." + }, + { + "example_num": 2, + "expected_input": "prices = [1,2,3,4,5]", + "expected_output": "4", + "explanation": "Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.\nTotal profit is 4." + }, + { + "example_num": 3, + "expected_input": "prices = [7,6,4,3,1]", + "expected_output": "0", + "explanation": "There is no way to make a positive profit, so we never buy the stock to achieve the maximum profit of 0." + } + ], + "solution": "/**\n * @param {number[]} prices\n * @return {number}\n */\nconst maxProfit = function (prices) {\n let p = 0\n for (let i = 1; i < prices.length; ++i) {\n let delta = prices[i] - prices[i - 1]\n if (delta > 0) {\n p += delta\n }\n }\n return p\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720b22", + "questionid": 87, + "title": "Valid Palindrome", + "slug": "valid-palindrome", + "description": "A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers. Given a string s, return true if it is a palindrome, or false otherwise. ", + "category": [ + "Two Pointers", + "String" + ], + "complexity": "Easy", + "successrate": 41.5, + "totalsubmissions": 2944250, + "totalaccepted": 1220904, + "likes": 3460, + "dislikes": 5081, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "A man, a plan, a canal: Panama"", + "expected_output": "true", + "explanation": ""amanaplanacanalpanama" is a palindrome." + }, + { + "example_num": 2, + "expected_input": "s = "race a car"", + "expected_output": "false", + "explanation": ""raceacar" is not a palindrome." + }, + { + "example_num": 3, + "expected_input": "s = " "", + "expected_output": "true", + "explanation": "s is an empty string "" after removing non-alphanumeric characters.\nSince an empty string reads the same forward and backward, it is a palindrome." + } + ], + "solution": "/**\n * @param {string} s\n * @return {boolean}\n */\nconst isPalindrome = function(s) {\n let start = 0\n let end = s.length - 1\n\n while(start < end) {\n while(start < s.length && !valid(s[start])) {\n start++ \n }\n while(end >=0 && !valid(s[end])) {\n end-- \n }\n if(start < s.length && end >=0) {\n if(s[start].toLowerCase() !== s[end].toLowerCase()) return false \n }\n start++\n end--\n }\n return true\n};\n\nfunction valid(c) {\n const code = c.toLowerCase().charCodeAt(0)\n const zeroCode = ('0').charCodeAt(0)\n const nineCode = ('9').charCodeAt(0)\n const aCode = ('a').charCodeAt(0)\n const zCode = ('z').charCodeAt(0)\n if( (code >= zeroCode && code <= nineCode) || ( code >= aCode && code <= zCode ) ) return true\n \n return false\n} \n" + }, + { + "_id": "66f925ddfdfb8e1665720b23", + "questionid": 88, + "title": "Longest Consecutive Sequence", + "slug": "longest-consecutive-sequence", + "description": "Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence. You must write an algorithm that runs in\u00a0O(n)\u00a0time. ", + "category": [ + "Array", + "Hash Table", + "Union Find" + ], + "complexity": "Medium", + "successrate": 48.7, + "totalsubmissions": 1319683, + "totalaccepted": 642062, + "likes": 9034, + "dislikes": 398, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [100,4,200,1,3,2]", + "expected_output": "4", + "explanation": "The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4." + }, + { + "example_num": 2, + "expected_input": "nums = [0,3,7,2,5,8,4,6,0,1]", + "expected_output": "9", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} nums\n * @return {number}\n */\nconst longestConsecutive = function(nums) {\n if(nums.length === 0) return 0\n nums.sort((a, b) => a - b)\n let max = 1\n let cur = 1\n for(let i = 1; i < nums.length; i++) {\n if(nums[i] - nums[i-1] === 1) {\n cur += 1\n max = Math.max(max, cur)\n } else if(nums[i] - nums[i-1] === 0) {\n \n } else {\n cur = 1\n }\n }\n \n return max\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720b2a", + "questionid": 95, + "title": "Single Number II", + "slug": "single-number-ii", + "description": "Given an integer array nums where\u00a0every element appears three times except for one, which appears exactly once. Find the single element and return it. You must\u00a0implement a solution with a linear runtime complexity and use\u00a0only constant\u00a0extra space. ", + "category": [ + "Array", + "Bit Manipulation" + ], + "complexity": "Medium", + "successrate": 56.5, + "totalsubmissions": 605201, + "totalaccepted": 342067, + "likes": 4009, + "dislikes": 475, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [2,2,3,2]", + "expected_output": "3", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "nums = [0,1,0,1,0,1,99]", + "expected_output": "99", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} nums\n * @return {number}\n */\nconst singleNumber = function(nums) {\n const hash = {}\n \n nums.forEach(el => {\n hash[el] = (hash[el] && hash[el] + 1) || 1\n })\n \n for(let el in hash) {\n if(hash[el] === 1) return +el\n }\n};\n\n// another\n\n/**\n * @param {number[]} nums\n * @return {number}\n */\nconst singleNumber = (nums)=> {\n let one=0, two=0;\n for (let i=0; i {\n // Initialize result\n let result = 0;\n let x, sum;\n const n = nums.length\n // Iterate through every bit\n for (let i = 0; i < 32; i++) {\n // Find sum of set bits at ith position in all\n // array elements\n sum = 0;\n x = (1 << i);\n for (let j = 0; j < n; j++ ) {\n if (nums[j] & x) sum++;\n }\n // The bits with sum not multiple of 3, are the\n // bits of element with single occurrence.\n if (sum % 3) result |= x;\n }\n return result;\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720b2f", + "questionid": 100, + "title": "Binary Tree Preorder Traversal", + "slug": "binary-tree-preorder-traversal", + "description": "Given the root of a binary tree, return the preorder traversal of its nodes' values. ", + "category": [ + "Stack", + "Tree", + "Depth-First Search", + "Binary Tree" + ], + "complexity": "Easy", + "successrate": 62.3, + "totalsubmissions": 1471175, + "totalaccepted": 917273, + "likes": 3931, + "dislikes": 125, + "hints": "", + "deleted": false, + "examples": [], + "solution": "/**\n * Definition for a binary tree node.\n * function TreeNode(val) {\n * this.val = val;\n * this.left = this.right = null;\n * }\n */\n/**\n * @param {TreeNode} root\n * @return {number[]}\n */\nconst preorderTraversal = function(root) {\n const res = [];\n traversal(root, res);\n return res;\n};\n\nfunction traversal(node, arr) {\n if (node === null) return;\n arr.push(node.val);\n if (node.left) {\n traversal(node.left, arr);\n }\n if (node.right) {\n traversal(node.right, arr);\n }\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720b33", + "questionid": 104, + "title": "Evaluate Reverse Polish Notation", + "slug": "evaluate-reverse-polish-notation", + "description": "Evaluate the value of an arithmetic expression in Reverse Polish Notation. Valid operators are +, -, *, and /. Each operand may be an integer or another expression. Note that division between two integers should truncate toward zero. It is guaranteed that the given RPN expression is always valid. That means the expression would always evaluate to a result, and there will not be any division by zero operation. ", + "category": [ + "Array", + "Math", + "Stack" + ], + "complexity": "Medium", + "successrate": 42.3, + "totalsubmissions": 936103, + "totalaccepted": 396146, + "likes": 2884, + "dislikes": 615, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "tokens = ["2","1","+","3","*"]", + "expected_output": "9", + "explanation": "((2 + 1) * 3) = 9" + }, + { + "example_num": 2, + "expected_input": "tokens = ["4","13","5","/","+"]", + "expected_output": "6", + "explanation": "(4 + (13 / 5)) = 6" + }, + { + "example_num": 3, + "expected_input": "tokens = ["10","6","9","3","+","-11","*","/","*","17","+","5","+"]", + "expected_output": "22", + "explanation": "((10 * (6 / ((9 + 3) * -11))) + 17) + 5\n= ((10 * (6 / (12 * -11))) + 17) + 5\n= ((10 * (6 / -132)) + 17) + 5\n= ((10 * 0) + 17) + 5\n= (0 + 17) + 5\n= 17 + 5\n= 22" + } + ], + "solution": "/**\n * @param {string[]} tokens\n * @return {number}\n */\nconst evalRPN = function(tokens) {\n const stack = []\n for (let token of tokens) {\n if (token === '+') {\n stack.push(stack.pop() + stack.pop())\n } else if (token === '-') {\n stack.push(-stack.pop() + stack.pop())\n } else if (token === '*') {\n stack.push(stack.pop() * stack.pop())\n } else if (token === '/') {\n stack.push(Math.trunc((1 / stack.pop()) * stack.pop()))\n } else {\n stack.push(parseInt(token))\n }\n }\n return stack[0]\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720b34", + "questionid": 105, + "title": "Reverse Words in a String", + "slug": "reverse-words-in-a-string", + "description": "Given an input string s, reverse the order of the words. A word is defined as a sequence of non-space characters. The words in s will be separated by at least one space. Return a string of the words in reverse order concatenated by a single space. Note that s may contain leading or trailing spaces or multiple spaces between two words. The returned string should only have a single space separating the words. Do not include any extra spaces. ", + "category": [ + "Two Pointers", + "String" + ], + "complexity": "Medium", + "successrate": 28.4, + "totalsubmissions": 2433332, + "totalaccepted": 690127, + "likes": 3004, + "dislikes": 3851, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "the sky is blue"", + "expected_output": ""blue is sky the"", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "s = " hello world "", + "expected_output": ""world hello"", + "explanation": "Your reversed string should not contain leading or trailing spaces." + }, + { + "example_num": 3, + "expected_input": "s = "a good example"", + "expected_output": ""example good a"", + "explanation": "You need to reduce multiple spaces between two words to a single space in the reversed string." + } + ], + "solution": "/**\n * @param {string} str\n * @returns {string}\n */\nconst reverseWords = function(str) {\n return str\n .trim()\n .split(/\\s+/)\n .reverse()\n .join(\" \");\n};\n\n// another\n\n/**\n * @param {string} str\n * @returns {string}\n */\nconst reverseWords = function (s) {\n let sb = ''\n const n = s.length\n let i = n - 1\n while (i >= 0) {\n if (s.charAt(i) == ' ') {\n i--\n continue\n }\n let j = i - 1\n while (j >= 0 && s.charAt(j) != ' ') j--\n sb += ' '\n sb += s.slice(j + 1, i + 1)\n i = j - 1\n }\n if (sb.length > 0) sb = sb.slice(1)\n return sb\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720b35", + "questionid": 106, + "title": "Maximum Product Subarray", + "slug": "maximum-product-subarray", + "description": "Given an integer array nums, find a contiguous non-empty subarray within the array that has the largest product, and return the product. The test cases are generated so that the answer will fit in a 32-bit integer. A subarray is a contiguous subsequence of the array. ", + "category": [ + "Array", + "Dynamic Programming" + ], + "complexity": "Medium", + "successrate": 34.5, + "totalsubmissions": 2086147, + "totalaccepted": 720227, + "likes": 11150, + "dislikes": 345, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [2,3,-2,4]", + "expected_output": "6", + "explanation": "[2,3] has the largest product 6." + }, + { + "example_num": 2, + "expected_input": "nums = [-2,0,-1]", + "expected_output": "0", + "explanation": "The result cannot be 2, because [-2,-1] is not a subarray." + } + ], + "solution": "/**\n * @param {number[]} nums\n * @return {number}\n */\nconst maxProduct = function(nums) {\n let min = nums[0], max = nums[0], res = nums[0]\n for(let i = 1, n = nums.length; i < n; i++) {\n const e = nums[i]\n if(e < 0) [min, max] = [max, min]\n min = Math.min(e, min * e)\n max = Math.max(e, max * e)\n res = Math.max(res, max)\n }\n return res\n};\n\n// another\n\n/**\n * @param {number[]} nums\n * @return {number}\n */\nconst maxProduct = function(nums) {\n let A = nums\n let r = A[0];\n\n // imax/imin stores the max/min product of\n // subarray that ends with the current number A[i]\n for (let i = 1, imax = r, imin = r, n = A.length; i < n; i++) {\n if (A[i] < 0) {\n let tmp = imax\n imax = imin\n imin = tmp\n };\n // max/min product for the current number is either the current number itself\n // or the max/min by the previous number times the current one\n imax = Math.max(A[i], imax * A[i]);\n imin = Math.min(A[i], imin * A[i]);\n\n // the newly computed max value is a candidate for our global result\n r = Math.max(r, imax);\n }\n return r;\n};\n\n// another\n\n/**\n * @param {number[]} nums\n * @return {number}\n */\nconst maxProduct = function(nums) {\n if(nums.length == 1)return nums[0];\n let dpMax = nums[0];\n let dpMin = nums[0];\n let max = nums[0];\n for (let i = 1; i < nums.length; i++) {\n let k = dpMax*nums[i];\n let m = dpMin*nums[i];\n dpMax = Math.max(nums[i], Math.max(k, m));\n dpMin = Math.min(nums[i], Math.min(k, m));\n max = Math.max(dpMax, max);\n }\n return max;\n};\n\n// another\n\n/**\n * @param {number[]} nums\n * @return {number}\n */\nconst maxProduct = function(nums) {\n const n = nums.length\n let max, min\n let res = max = min = nums[0]\n for(let i = 1; i < n; i++) {\n if(nums[i] < 0) [max, min] = [min, max]\n max = Math.max(nums[i], nums[i] * max)\n min = Math.min(nums[i], nums[i] * min)\n res = Math.max(res, max)\n }\n return res\n};\n\n\n// another\n\n/**\n * @param {number[]} nums\n * @return {number}\n */\nconst maxProduct = function (nums) {\n if(nums == null || nums.length === 0) return 0\n const n = nums.length\n let res = nums[0]\n for(let i = 1, min = res, max = res; i < n; i++) {\n if(nums[i] < 0) {\n let tmax = max, tmin = min\n min = Math.min(nums[i], tmax * nums[i])\n max = Math.max(nums[i], tmin * nums[i])\n } else {\n min = Math.min(nums[i], min * nums[i])\n max = Math.max(nums[i], max * nums[i])\n }\n res = Math.max(res, max)\n }\n \n return res\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720b39", + "questionid": 110, + "title": "Two Sum II - Input Array Is Sorted", + "slug": "two-sum-ii-input-array-is-sorted", + "description": "Given a 1-indexed array of integers numbers that is already sorted in non-decreasing order, find two numbers such that they add up to a specific target number. Let these two numbers be numbers[index1] and numbers[index2] where 1 <= index1 < index2 <= numbers.length. Return the indices of the two numbers, index1 and index2, added by one as an integer array [index1, index2] of length 2. The tests are generated such that there is exactly one solution. You may not use the same element twice. Your solution must use only constant extra space. ", + "category": [ + "Array", + "Two Pointers", + "Binary Search" + ], + "complexity": "Medium", + "successrate": 58.6, + "totalsubmissions": 1583339, + "totalaccepted": 928226, + "likes": 5160, + "dislikes": 923, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "numbers = [2,7,11,15], target = 9", + "expected_output": "[1,2]", + "explanation": "The sum of 2 and 7 is 9. Therefore, index1 = 1, index2 = 2. We return [1, 2]." + }, + { + "example_num": 2, + "expected_input": "numbers = [2,3,4], target = 6", + "expected_output": "[1,3]", + "explanation": "The sum of 2 and 4 is 6. Therefore index1 = 1, index2 = 3. We return [1, 3]." + }, + { + "example_num": 3, + "expected_input": "numbers = [-1,0], target = -1", + "expected_output": "[1,2]", + "explanation": "The sum of -1 and 0 is -1. Therefore index1 = 1, index2 = 2. We return [1, 2]." + } + ], + "solution": null + }, + { + "_id": "66f925ddfdfb8e1665720b3c", + "questionid": 113, + "title": "Dungeon Game", + "slug": "dungeon-game", + "description": "The demons had captured the princess and imprisoned her in the bottom-right corner of a dungeon. The dungeon consists of m x n rooms laid out in a 2D grid. Our valiant knight was initially positioned in the top-left room and must fight his way through dungeon to rescue the princess. The knight has an initial health point represented by a positive integer. If at any point his health point drops to 0 or below, he dies immediately. Some of the rooms are guarded by demons (represented by negative integers), so the knight loses health upon entering these rooms; other rooms are either empty (represented as 0) or contain magic orbs that increase the knight's health (represented by positive integers). To reach the princess as quickly as possible, the knight decides to move only rightward or downward in each step. Return the knight's minimum initial health so that he can rescue the princess. Note that any room can contain threats or power-ups, even the first room the knight enters and the bottom-right room where the princess is imprisoned. ", + "category": [ + "Array", + "Dynamic Programming", + "Matrix" + ], + "complexity": "Hard", + "successrate": 36.4, + "totalsubmissions": 465945, + "totalaccepted": 169797, + "likes": 3977, + "dislikes": 80, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "dungeon = [[-2,-3,3],[-5,-10,1],[10,30,-5]]", + "expected_output": "7", + "explanation": "The initial health of the knight must be at least 7 if he follows the optimal path: RIGHT-> RIGHT -> DOWN -> DOWN." + }, + { + "example_num": 2, + "expected_input": "dungeon = [[0]]", + "expected_output": "1", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[][]} dungeon\n * @return {number}\n */\nconst calculateMinimumHP = function (dungeon) {\n const M = dungeon.length\n const N = dungeon[0].length\n // hp[i][j] represents the min hp needed at position (i, j)\n // Add dummy row and column at bottom and right side\n const hp = Array.from({ length: M + 1 }, () =>\n Array(N + 1).fill(Number.MAX_VALUE)\n )\n hp[M][N - 1] = 1\n hp[M - 1][N] = 1\n for (let i = M - 1; i >= 0; i--) {\n for (let j = N - 1; j >= 0; j--) {\n const need = Math.min(hp[i + 1][j], hp[i][j + 1]) - dungeon[i][j]\n hp[i][j] = need <= 0 ? 1 : need\n }\n }\n return hp[0][0]\n}\n\n\n// another\n\n/**\n * @param {number[][]} dungeon\n * @return {number}\n */\nconst calculateMinimumHP = function (dungeon) {\n const n = dungeon.length,\n m = dungeon[0].length\n const dp = Array(n + 1).fill(Number.MAX_VALUE)\n dp[n - 1] = 1\n for (let j = m - 1; j >= 0; j--) {\n for (let i = n - 1; i >= 0; i--) {\n dp[i] = Math.min(dp[i], dp[i + 1]) - dungeon[i][j]\n dp[i] = Math.max(1, dp[i])\n }\n }\n return dp[0]\n}\n\n" + }, + { + "_id": "66f925ddfdfb8e1665720b43", + "questionid": 120, + "title": "Bitwise AND of Numbers Range", + "slug": "bitwise-and-of-numbers-range", + "description": "Given two integers left and right that represent the range [left, right], return the bitwise AND of all numbers in this range, inclusive. ", + "category": [ + "Bit Manipulation" + ], + "complexity": "Medium", + "successrate": 41.8, + "totalsubmissions": 510983, + "totalaccepted": 213336, + "likes": 2225, + "dislikes": 176, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "left = 5, right = 7", + "expected_output": "4", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "left = 0, right = 0", + "expected_output": "0", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "left = 1, right = 2147483647", + "expected_output": "0", + "explanation": "" + } + ], + "solution": "/**\n * @param {number} m\n * @param {number} n\n * @return {number}\n */\nconst rangeBitwiseAnd = function(m, n) {\n while(m>= 1\n n >>= 1\n s++\n }\n return m << s\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720b44", + "questionid": 121, + "title": "Remove Linked List Elements", + "slug": "remove-linked-list-elements", + "description": "Given the head of a linked list and an integer val, remove all the nodes of the linked list that has Node.val == val, and return the new head. ", + "category": [ + "Linked List", + "Recursion" + ], + "complexity": "Easy", + "successrate": 43.4, + "totalsubmissions": 1582236, + "totalaccepted": 686326, + "likes": 4794, + "dislikes": 162, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "head = [1,2,6,3,4,5,6], val = 6", + "expected_output": "[1,2,3,4,5]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "head = [], val = 1", + "expected_output": "[]", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "head = [7,7,7,7], val = 7", + "expected_output": "[]", + "explanation": "" + } + ], + "solution": "/**\n * Definition for singly-linked list.\n * function ListNode(val) {\n * this.val = val;\n * this.next = null;\n * }\n */\n/**\n * @param {ListNode} head\n * @param {number} val\n * @return {ListNode}\n */\nconst removeElements = function(head, val) {\n const dummy = new ListNode(Infinity)\n if(head == null) return null\n dummy.next = head\n let cur = head\n let prev = dummy\n while(cur) {\n if(cur.val === val) {\n prev.next = cur.next\n cur = cur.next\n } else {\n prev = cur\n cur = cur.next\n }\n }\n return dummy.next\n};\n\n// another\n\n/**\n * Definition for singly-linked list.\n * function ListNode(val) {\n * this.val = val;\n * this.next = null;\n * }\n */\n/**\n * @param {ListNode} head\n * @param {number} val\n * @return {ListNode}\n */\nconst removeElements = function(head, val) {\n if (head === null) return null;\n head.next = removeElements(head.next, val);\n return head.val === val ? head.next : head;\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720b46", + "questionid": 123, + "title": "Isomorphic Strings", + "slug": "isomorphic-strings", + "description": "Given two strings s and t, determine if they are isomorphic. Two strings s and t are isomorphic if the characters in s can be replaced to get t. All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character, but a character may map to itself. ", + "category": [ + "Hash Table", + "String" + ], + "complexity": "Easy", + "successrate": 42.1, + "totalsubmissions": 1160012, + "totalaccepted": 487870, + "likes": 3435, + "dislikes": 638, + "hints": "", + "deleted": false, + "examples": [], + "solution": "/**\n * @param {string} s\n * @param {string} t\n * @return {boolean}\n */\nconst isIsomorphic = function(s, t) {\n if (s.length !== t.length) {\n return false;\n }\n const smap = {};\n const tmap = {};\n\n for (let i = 0; i < s.length; i++) {\n if (!smap.hasOwnProperty(s[i])) {\n smap[s[i]] = t[i];\n }\n if (!tmap.hasOwnProperty(t[i])) {\n tmap[t[i]] = s[i];\n }\n\n if (smap[s[i]] !== t[i] || tmap[t[i]] !== s[i]) return false;\n\n }\n\n return true;\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720b4a", + "questionid": 127, + "title": "Course Schedule II", + "slug": "course-schedule-ii", + "description": "There are a total of numCourses courses you have to take, labeled from 0 to numCourses - 1. You are given an array prerequisites where prerequisites[i] = [ai, bi] indicates that you must take course bi first if you want to take course ai. Return the ordering of courses you should take to finish all courses. If there are many valid answers, return any of them. If it is impossible to finish all courses, return an empty array. ", + "category": [ + "Depth-First Search", + "Breadth-First Search", + "Graph", + "Topological Sort" + ], + "complexity": "Medium", + "successrate": 46.4, + "totalsubmissions": 1304440, + "totalaccepted": 605688, + "likes": 6464, + "dislikes": 232, + "hints": "This problem is equivalent to finding the topological order in a directed graph. If a cycle exists, no topological ordering exists and therefore it will be impossible to take all courses. Topological Sort via DFS - A great video tutorial (21 minutes) on Coursera explaining the basic concepts of Topological Sort. Topological sort could also be done via BFS.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "numCourses = 2, prerequisites = [[1,0]]", + "expected_output": "[0,1]", + "explanation": "There are a total of 2 courses to take. To take course 1 you should have finished course 0. So the correct course order is [0,1]." + }, + { + "example_num": 2, + "expected_input": "numCourses = 4, prerequisites = [[1,0],[2,0],[3,1],[3,2]]", + "expected_output": "[0,2,1,3]", + "explanation": "There are a total of 4 courses to take. To take course 3 you should have finished both courses 1 and 2. Both courses 1 and 2 should be taken after you finished course 0.\nSo one correct course order is [0,1,2,3]. Another correct ordering is [0,2,1,3]." + }, + { + "example_num": 3, + "expected_input": "numCourses = 1, prerequisites = []", + "expected_output": "[0]", + "explanation": "" + } + ], + "solution": "/**\n * @param {number} numCourses\n * @param {number[][]} prerequisites\n * @return {number[]}\n */\nconst findOrder = function(numCourses, prerequisites) {\n const graph = {}, inDegree = Array(numCourses).fill(0)\n for(const [s, e] of prerequisites) {\n inDegree[s]++\n if(graph[e] == null) graph[e] = []\n graph[e].push(s)\n }\n \n const res = []\n let q = []\n for(let i = 0; i < numCourses; i++) {\n if(inDegree[i] === 0) q.push(i)\n }\n \n while(q.length) {\n const nxt = []\n for(let i = 0; i < q.length; i++) {\n const cur = q[i]\n res.push(cur)\n for(const e of (graph[cur] || [])) {\n inDegree[e]--\n if(inDegree[e] === 0) nxt.push(e)\n }\n }\n q = nxt\n }\n \n return res.length === numCourses ? res : []\n}\n\n// another\n\n/**\n * @param {number} numCourses\n * @param {number[][]} prerequisites\n * @return {number[]}\n */\nconst findOrder = function(numCourses, prerequisites) {\n const indegree = new Array(numCourses).fill(0)\n const graph = {}\n for (let [course, prereq] of prerequisites) {\n indegree[course]++\n graph[prereq] === undefined\n ? (graph[prereq] = [course])\n : graph[prereq].push(course)\n }\n const queue = [],\n ans = []\n for (let i = 0; i < indegree.length; i++) if (!indegree[i]) queue.push(i)\n while (queue.length) {\n let cur = queue.shift()\n ans.push(cur)\n for (let neigbhors of graph[cur] || []) {\n if (!--indegree[neigbhors]) queue.push(neigbhors)\n }\n }\n return ans.length === numCourses ? ans : []\n}\n\n// another\n\n/**\n * @param {number} numCourses\n * @param {number[][]} prerequisites\n * @return {number[]}\n */\nconst findOrder = function(numCourses, prerequisites) {\n const seen = new Set()\n const seeing = new Set()\n const res = []\n\n const adj = [...Array(numCourses)].map(r => [])\n for (let [u, v] of prerequisites) {\n adj[v].push(u)\n }\n for (let c = 0; c < numCourses; c++) {\n if (!dfs(c)) {\n return []\n }\n }\n return res.reverse()\n\n function dfs(v) {\n if (seen.has(v)) {\n return true\n }\n if (seeing.has(v)) {\n return false\n }\n seeing.add(v)\n for (let nv of adj[v]) {\n if (!dfs(nv)) {\n return false\n }\n }\n seeing.delete(v)\n seen.add(v)\n res.push(v)\n return true\n }\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720b0c", + "questionid": 65, + "title": "Binary Tree Inorder Traversal", + "slug": "binary-tree-inorder-traversal", + "description": "Given the root of a binary tree, return the inorder traversal of its nodes' values. ", + "category": [ + "Stack", + "Tree", + "Depth-First Search", + "Binary Tree" + ], + "complexity": "Easy", + "successrate": 70.6, + "totalsubmissions": 2018990, + "totalaccepted": 1425499, + "likes": 7405, + "dislikes": 335, + "hints": "", + "deleted": false, + "examples": [], + "solution": "/**\n * Definition for a binary tree node.\n * function TreeNode(val) {\n * this.val = val;\n * this.left = this.right = null;\n * }\n */\n/**\n * @param {TreeNode} root\n * @return {number[]}\n */\nconst inorderTraversal = function(root) {\n const res = [];\n if (root == null) return res;\n traversal(root, res);\n return res;\n};\n\nfunction traversal(node, res) {\n if (node.left) {\n traversal(node.left, res);\n }\n res.push(node.val);\n if (node.right) {\n traversal(node.right, res);\n }\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720b0e", + "questionid": 67, + "title": "Unique Binary Search Trees", + "slug": "unique-binary-search-trees", + "description": "Given an integer n, return the number of structurally unique BST's (binary search trees) which has exactly n nodes of unique values from 1 to n. ", + "category": [ + "Math", + "Dynamic Programming", + "Tree", + "Binary Search Tree", + "Binary Tree" + ], + "complexity": "Medium", + "successrate": 58.2, + "totalsubmissions": 815533, + "totalaccepted": 474825, + "likes": 7042, + "dislikes": 284, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 3", + "expected_output": "5", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "n = 1", + "expected_output": "1", + "explanation": "" + } + ], + "solution": "/**\n * @param {number} n\n * @return {number}\n */\nconst numTrees = function(n) {\n const arr = new Array(n + 1).fill(0)\n arr[0] = arr[1] = 1\n for (let i = 2; i <= n; i++) {\n for (let j = 1; j <= i; j++) {\n arr[i] += arr[j - 1] * arr[i - j]\n }\n }\n return arr[n]\n}\n\n// another\n\n/**\n * @param {number} n\n * @return {number}\n */\nconst numTrees = function(n) {\n const hash = {\n 0: 1,\n 1: 1\n }\n return doNumTrees(n, hash)\n}\n\nfunction doNumTrees(n, hash) {\n if (hash[n]) return hash[n]\n let sum = 0\n for (let i = 1; i <= n; i++) {\n const left = doNumTrees(i - 1, hash)\n const right = doNumTrees(n - i, hash)\n sum += left * right\n }\n hash[n] = sum\n return sum\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720b14", + "questionid": 73, + "title": "Maximum Depth of Binary Tree", + "slug": "maximum-depth-of-binary-tree", + "description": "Given the root of a binary tree, return its maximum depth. A binary tree's maximum depth\u00a0is the number of nodes along the longest path from the root node down to the farthest leaf node. ", + "category": [ + "Tree", + "Depth-First Search", + "Breadth-First Search", + "Binary Tree" + ], + "complexity": "Easy", + "successrate": 71.8, + "totalsubmissions": 2259723, + "totalaccepted": 1621474, + "likes": 6744, + "dislikes": 124, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [3,9,20,null,null,15,7]", + "expected_output": "3", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "root = [1,null,2]", + "expected_output": "2", + "explanation": "" + } + ], + "solution": "/**\n * Definition for a binary tree node.\n * function TreeNode(val) {\n * this.val = val;\n * this.left = this.right = null;\n * }\n */\n/**\n * @param {TreeNode} root\n * @return {number}\n */\nconst maxDepth = function(root) {\n if (!root) return 0;\n const left = maxDepth(root.left);\n const right = maxDepth(root.right);\n let depth = left > right ? left : right;\n return (depth += 1);\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720b16", + "questionid": 75, + "title": "Construct Binary Tree from Inorder and Postorder Traversal", + "slug": "construct-binary-tree-from-inorder-and-postorder-traversal", + "description": "Given two integer arrays inorder and postorder where inorder is the inorder traversal of a binary tree and postorder is the postorder traversal of the same tree, construct and return the binary tree. ", + "category": [ + "Array", + "Hash Table", + "Divide and Conquer", + "Tree", + "Binary Tree" + ], + "complexity": "Medium", + "successrate": 55.2, + "totalsubmissions": 707765, + "totalaccepted": 390759, + "likes": 4348, + "dislikes": 72, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "inorder = [9,3,15,20,7], postorder = [9,15,7,20,3]", + "expected_output": "[3,9,20,null,null,15,7]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "inorder = [-1], postorder = [-1]", + "expected_output": "[-1]", + "explanation": "" + } + ], + "solution": "/**\n * Definition for a binary tree node.\n * function TreeNode(val) {\n * this.val = val;\n * this.left = this.right = null;\n * }\n */\n/**\n * @param {number[]} inorder\n * @param {number[]} postorder\n * @return {TreeNode}\n */\n\nconst buildTree = function(inorder, postorder) {\n const inmap = {};\n const posts = postorder;\n for (let i = 0; i < inorder.length; i++) {\n inmap[inorder[i]] = i;\n }\n return helper(postorder.length - 1, 0, inorder.length - 1);\n\n function helper(postEnd, inStart, inEnd) {\n if (postEnd < 0 || inEnd < inStart) return null;\n const val = posts[postEnd];\n const idx = inmap[\"\" + val];\n const root = new TreeNode(val);\n root.left = helper(postEnd - (inEnd - idx) - 1, inStart, idx - 1);\n root.right = helper(postEnd - 1, idx + 1, inEnd);\n\n return root;\n }\n};\n\n// another\n\n/**\n * Definition for a binary tree node.\n * function TreeNode(val) {\n * this.val = val;\n * this.left = this.right = null;\n * }\n */\n/**\n * @param {number[]} inorder\n * @param {number[]} postorder\n * @return {TreeNode}\n */\n\nconst buildTree = function (inorder, postorder) {\n let pInorder = inorder.length - 1\n let pPostorder = postorder.length - 1\n return helper(inorder, postorder, null)\n function helper(inorder, postorder, end) {\n if (pPostorder < 0) return null\n // create root node\n const n = new TreeNode(postorder[pPostorder--])\n // if right node exist, create right subtree\n if (inorder[pInorder] != n.val) {\n n.right = helper(inorder, postorder, n)\n }\n pInorder--\n // if left node exist, create left subtree\n if (end === null || inorder[pInorder] !== end.val) {\n n.left = helper(inorder, postorder, end)\n }\n return n\n }\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720b1b", + "questionid": 80, + "title": "Path Sum II", + "slug": "path-sum-ii", + "description": "Given the root of a binary tree and an integer targetSum, return all root-to-leaf paths where the sum of the node values in the path equals targetSum. Each path should be returned as a list of the node values, not node references. A root-to-leaf path is a path starting from the root and ending at any leaf node. A leaf is a node with no children. ", + "category": [ + "Backtracking", + "Tree", + "Depth-First Search", + "Binary Tree" + ], + "complexity": "Medium", + "successrate": 53.9, + "totalsubmissions": 1052748, + "totalaccepted": 567301, + "likes": 4603, + "dislikes": 109, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22", + "expected_output": "[[5,4,11,2],[5,8,4,5]]", + "explanation": "There are two paths whose sum equals targetSum:\n5 + 4 + 11 + 2 = 22\n5 + 8 + 4 + 5 = 22" + }, + { + "example_num": 2, + "expected_input": "root = [1,2,3], targetSum = 5", + "expected_output": "[]", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "root = [1,2], targetSum = 0", + "expected_output": "[]", + "explanation": "" + } + ], + "solution": "/**\n * Definition for a binary tree node.\n * function TreeNode(val) {\n * this.val = val;\n * this.left = this.right = null;\n * }\n */\n/**\n * @param {TreeNode} root\n * @param {number} sum\n * @return {number[][]}\n */\n\nconst pathSum = function(root, sum) {\n const result = [];\n backtrack(root, sum, [], result);\n return result;\n};\n\nconst backtrack = function(root, sum, temp, result) {\n if (root == null) {\n return;\n }\n temp.push(root.val);\n let newSum = sum - root.val;\n if (root.left == null && root.right == null) {\n if (newSum === 0) {\n result.push([...temp]);\n }\n temp.pop();\n return;\n }\n backtrack(root.left, newSum, temp, result);\n backtrack(root.right, newSum, temp, result);\n temp.pop();\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720b26", + "questionid": 91, + "title": "Palindrome Partitioning", + "slug": "palindrome-partitioning", + "description": "Given a string s, partition s such that every substring of the partition is a palindrome. Return all possible palindrome partitioning of s. A palindrome string is a string that reads the same backward as forward. ", + "category": [ + "String", + "Dynamic Programming", + "Backtracking" + ], + "complexity": "Medium", + "successrate": 59.3, + "totalsubmissions": 746356, + "totalaccepted": 442390, + "likes": 6475, + "dislikes": 201, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = \"aab\"", + "expected_output": "[[\"a\",\"a\",\"b\"],[\"aa\",\"b\"]]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "s = \"a\"", + "expected_output": "[[\"a\"]]", + "explanation": "" + } + ], + "solution": "/**\n * @param {string} s\n * @return {string[][]}\n */\nconst partition = function(s) {\n let res = []\n backtrack(res, [], 0, s)\n return res\n}\n\nfunction backtrack(res, cur, start, s) {\n if (start === s.length) res.push([...cur])\n else {\n for (let i = start; i < s.length; i++) {\n if (isPalindrome(s, start, i)) {\n cur.push(s.substring(start, i + 1))\n backtrack(res, cur, i + 1, s)\n cur.pop()\n }\n }\n }\n}\n\nfunction isPalindrome(str, start, i) {\n let l = start,\n r = i\n while (l < r) {\n if (str[l] !== str[r]) return false\n l++\n r--\n }\n return true\n}\n\n// another\n\n/**\n * @param {string} s\n * @return {string[][]}\n */\nconst partition = function(s) {\n const res = []\n helper(s, 0, [], res)\n return res\n};\n\nfunction helper(str, idx, cur, res) {\n if(idx >= str.length) {\n res.push(cur.slice())\n return\n }\n for(let i = idx, len = str.length; i < len; i++) {\n const tmp = str.slice(idx, i + 1)\n if(chk(tmp)) {\n cur.push(tmp)\n helper(str, i + 1, cur, res)\n cur.pop()\n }\n }\n}\nfunction chk(str) {\n const n = str.length\n let l = 0, r = n - 1\n while(l < r) {\n if(str[l] !== str[r]) return false\n l++\n r--\n }\n return true\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720b27", + "questionid": 92, + "title": "Palindrome Partitioning II", + "slug": "palindrome-partitioning-ii", + "description": "Given a string s, partition s such that every substring of the partition is a palindrome. Return the minimum cuts needed for a palindrome partitioning of s. ", + "category": [ + "String", + "Dynamic Programming" + ], + "complexity": "Hard", + "successrate": 33.1, + "totalsubmissions": 606455, + "totalaccepted": 200922, + "likes": 3268, + "dislikes": 77, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "aab"", + "expected_output": "1", + "explanation": "The palindrome partitioning ["aa","b"] could be produced using 1 cut." + }, + { + "example_num": 2, + "expected_input": "s = "a"", + "expected_output": "0", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "s = "ab"", + "expected_output": "1", + "explanation": "" + } + ], + "solution": "/**\n * @param {string} s\n * @return {number}\n */\n\nconst minCut = function(s) {\n const n = s.length\n if (n <= 1) return 0\n const dp = new Array(n).fill(0)\n for (let i = 1; i < n; i++) dp[i] = i\n for (let i = 1; i < n; i++) {\n // odd\n for (\n let start = i, end = i;\n end < n && start >= 0 && s[end] === s[start];\n start--, end++\n ) {\n dp[end] = Math.min(dp[end], start === 0 ? 0 : dp[start - 1] + 1)\n }\n // even\n for (\n let start = i - 1, end = i;\n end < n && start >= 0 && s[end] === s[start];\n start--, end++\n ) {\n dp[end] = Math.min(dp[end], start === 0 ? 0 : dp[start - 1] + 1)\n }\n }\n return dp[n - 1]\n}\n\n\n\n// another\n\nconst minCut = function(s) {\n const n = s.length\n const cut = new Array(n + 1).fill(0)\n for (let i = 0; i <= n; i++) cut[i] = i - 1\n for (let i = 0; i < n; i++) {\n // odd\n for (let j = 0; i + j < n && i - j >= 0 && s[i + j] === s[i - j]; j++) {\n cut[i + j + 1] = Math.min(cut[i + j + 1], cut[i - j] + 1)\n }\n // even\n for (\n let j = 1;\n i + j < n && i - j + 1 >= 0 && s[i + j] === s[i - j + 1];\n j++\n ) {\n cut[i + j + 1] = Math.min(cut[i + j + 1], cut[i - j + 1] + 1)\n }\n }\n return cut[n]\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720b2c", + "questionid": 97, + "title": "Word Break II", + "slug": "word-break-ii", + "description": "Given a string s and a dictionary of strings wordDict, add spaces in s to construct a sentence where each word is a valid dictionary word. Return all such possible sentences in any order. Note that the same word in the dictionary may be reused multiple times in the segmentation. ", + "category": [ + "Hash Table", + "String", + "Dynamic Programming", + "Backtracking", + "Trie", + "Memoization" + ], + "complexity": "Hard", + "successrate": 41.9, + "totalsubmissions": 1036483, + "totalaccepted": 434784, + "likes": 4595, + "dislikes": 475, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "catsanddog", wordDict = ["cat","cats","and","sand","dog"]", + "expected_output": "["cats and dog","cat sand dog"]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "s = "pineapplepenapple", wordDict = ["apple","pen","applepen","pine","pineapple"]", + "expected_output": "["pine apple pen apple","pineapple pen apple","pine applepen apple"]", + "explanation": "Note that you are allowed to reuse a dictionary word." + }, + { + "example_num": 3, + "expected_input": "s = "catsandog", wordDict = ["cats","dog","sand","and","cat"]", + "expected_output": "[]", + "explanation": "" + } + ], + "solution": "/**\n * @param {string} s\n * @param {string[]} wordDict\n * @return {string[]}\n */\nconst wordBreak = function(s, wordDict) {\n const set = new Set(wordDict)\n const map = new Map()\n return helper(s, 0, set, map)\n};\n\nfunction helper(str, idx, set, map) {\n if(idx === str.length) return []\n if(map.has(idx)) return map.get(idx)\n const res = []\n for(let i = idx; i < str.length; i++) {\n const tmp = str.slice(idx, i + 1)\n if(set.has(tmp)) {\n const arr = helper(str, i + 1, set, map)\n if(i === str.length - 1) res.push(tmp)\n for(let item of arr) {\n res.push(`${tmp} ${item}`)\n }\n }\n }\n map.set(idx, res)\n return res\n}\n// another\n\n\n/**\n * @param {string} s\n * @param {string[]} wordDict\n * @return {string[]}\n */\nconst wordBreak = function(s, wordDict) {\n return backTrack(s, wordDict, {})\n};\n\nfunction backTrack(s, wordDict, mem) {\n if(mem.hasOwnProperty(s)) return mem[s]\n const result = []\n for(let word of wordDict) {\n if(s.startsWith(word)) {\n let next = s.slice(word.length)\n if(next.length === 0) result.push(word)\n else {\n for(let sub of backTrack(next, wordDict, mem)) {\n result.push(word+ ' '+sub)\n }\n }\n }\n }\n mem[s] = result\n return result\n}\n\n// another\n\n/**\n * @param {string} s\n * @param {string[]} wordDict\n * @return {string[]}\n */\nconst wordBreak = function (s, wordDict) {\n const dictSet = new Set(wordDict)\n const memo = {}\n function dfs(start) {\n if (start > s.length - 1) {\n return [[]]\n }\n if (memo[start] !== undefined) {\n return memo[start]\n }\n const out = []\n for (let i = start; i < s.length; i++) {\n const substr = s.substring(start, i + 1)\n if (dictSet.has(substr)) {\n let next = dfs(i + 1)\n for (let n of next) {\n out.push([substr, ...n])\n }\n }\n }\n return (memo[start] = out)\n }\n const res = dfs(0)\n return res.filter((a) => a.join('') === s).map((a) => a.join(' '))\n}\n\n// another\n\n/**\n * @param {string} s\n * @param {string[]} wordDict\n * @return {string[]}\n */\n\nconst wordBreak = (s, wordDict) => {\n const set = new Set(wordDict)\n return helper(s, 0, set)\n}\n\nfunction helper(s, idx, dict) {\n if(idx === s.length) return []\n const res = []\n for(let i = idx; i < s.length; i++) {\n const tmp = s.slice(idx, i + 1)\n if(dict.has(tmp)) {\n const arr = helper(s, i + 1, dict)\n if(i + 1 >= s.length) {\n res.push(tmp)\n } else if(arr.length) {\n for(let e of arr) {\n res.push(tmp + ' ' + e)\n }\n }\n }\n }\n return res\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720b2e", + "questionid": 99, + "title": "Linked List Cycle II", + "slug": "linked-list-cycle-ii", + "description": "Given the head of a linked list, return the node where the cycle begins. If there is no cycle, return null. There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail's next pointer is connected to (0-indexed). It is -1 if there is no cycle. Note that pos is not passed as a parameter. Do not modify the linked list. ", + "category": [ + "Hash Table", + "Linked List", + "Two Pointers" + ], + "complexity": "Medium", + "successrate": 44.1, + "totalsubmissions": 1486657, + "totalaccepted": 656083, + "likes": 7044, + "dislikes": 462, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "head = [3,2,0,-4], pos = 1", + "expected_output": "tail connects to node index 1", + "explanation": "There is a cycle in the linked list, where tail connects to the second node." + }, + { + "example_num": 2, + "expected_input": "head = [1,2], pos = 0", + "expected_output": "tail connects to node index 0", + "explanation": "There is a cycle in the linked list, where tail connects to the first node." + }, + { + "example_num": 3, + "expected_input": "head = [1], pos = -1", + "expected_output": "no cycle", + "explanation": "There is no cycle in the linked list." + } + ], + "solution": "/**\n * Definition for singly-linked list.\n * function ListNode(val) {\n * this.val = val;\n * this.next = null;\n * }\n */\n\n/**\n * @param {ListNode} head\n * @return {ListNode}\n */\nconst detectCycle = function(head) {\n if(head === null || head.next === null) return null\n let fast = head\n let slow = head\n let start = head\n while(fast !== null && fast.next !== null) {\n fast = fast.next.next\n slow = slow.next\n if(fast === slow) {\n while(slow !== start) {\n slow = slow.next\n start = start.next\n }\n return start\n }\n }\n return null\n};\n\n// another method\n\n/**\n * @param {ListNode} head\n * @return {ListNode}\n */\nconst detectCycle = (head) => {\n if (!head) return head;\n let currentNode = head;\n let previousNode = true;\n while (currentNode) {\n if (currentNode.previous) return currentNode\n if (!currentNode.previous) {\n currentNode.previous = previousNode;\n previousNode = currentNode;\n currentNode = currentNode.next;\n }\n }\n return null;\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720b37", + "questionid": 108, + "title": "Maximum Gap", + "slug": "maximum-gap", + "description": "Given an integer array nums, return the maximum difference between two successive elements in its sorted form. If the array contains less than two elements, return 0. You must write an algorithm that runs in linear time and uses linear extra space. ", + "category": [ + "Array", + "Sorting", + "Bucket Sort", + "Radix Sort" + ], + "complexity": "Hard", + "successrate": 41.3, + "totalsubmissions": 333410, + "totalaccepted": 137727, + "likes": 2054, + "dislikes": 281, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [3,6,9,1]", + "expected_output": "3", + "explanation": "The sorted form of the array is [1,3,6,9], either (3,6) or (6,9) has the maximum difference 3." + }, + { + "example_num": 2, + "expected_input": "nums = [10]", + "expected_output": "0", + "explanation": "The array contains less than 2 elements, therefore return 0." + } + ], + "solution": "/**\n * @param {number[]} nums\n * @return {number}\n */\nconst maximumGap = function (nums) {\n if (nums.length < 2) return\n let max = 0\n nums = nums.sort(function (a, b) {\n return a - b\n })\n for (let i = 1; i < nums.length; i++) {\n if (nums[i] - nums[i - 1] > max) max = nums[i] - nums[i - 1]\n }\n return max\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720b38", + "questionid": 109, + "title": "Fraction to Recurring Decimal", + "slug": "fraction-to-recurring-decimal", + "description": "Given two integers representing the numerator and denominator of a fraction, return the fraction in string format. If the fractional part is repeating, enclose the repeating part in parentheses. If multiple answers are possible, return any of them. It is guaranteed that the length of the answer string is less than 104 for all the given inputs. ", + "category": [ + "Hash Table", + "Math", + "String" + ], + "complexity": "Medium", + "successrate": 23.6, + "totalsubmissions": 770005, + "totalaccepted": 181343, + "likes": 1555, + "dislikes": 2915, + "hints": "No scary math, just apply elementary math knowledge. Still remember how to perform a long division? Try a long division on 4/9, the repeating part is obvious. Now try 4/333. Do you see a pattern? Notice that once the remainder starts repeating, so does the divided result. Be wary of edge cases! List out as many test cases as you can think of and test your code thoroughly.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "numerator = 1, denominator = 2", + "expected_output": ""0.5"", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "numerator = 2, denominator = 1", + "expected_output": ""2"", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "numerator = 4, denominator = 333", + "expected_output": ""0.(012)"", + "explanation": "" + } + ], + "solution": "/**\n * @param {number} numerator\n * @param {number} denominator\n * @return {string}\n */\nconst fractionToDecimal = function (numerator, denominator) {\n if (numerator === 0) return '0'\n let s = ''\n if (Math.sign(numerator) !== Math.sign(denominator)) s += '-'\n let n = Math.abs(numerator)\n const d = Math.abs(denominator)\n s += Math.floor(n / d)\n n %= d\n if (n === 0) return s\n s += '.'\n const map = {}\n while (n !== 0) {\n map[n] = s.length\n n *= 10\n s += Math.floor(n / d)\n n %= d\n const i = map[n] // repeat starting index\n if (i != null) return `${s.slice(0, i)}(${s.slice(i)})`\n }\n return s\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720b3b", + "questionid": 112, + "title": "Factorial Trailing Zeroes", + "slug": "factorial-trailing-zeroes", + "description": "Given an integer n, return the number of trailing zeroes in n!. Note that n! = n * (n - 1) * (n - 2) * ... * 3 * 2 * 1. ", + "category": [ + "Math" + ], + "complexity": "Medium", + "successrate": 40.7, + "totalsubmissions": 769195, + "totalaccepted": 313232, + "likes": 1949, + "dislikes": 1657, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 3", + "expected_output": "0", + "explanation": "3! = 6, no trailing zero." + }, + { + "example_num": 2, + "expected_input": "n = 5", + "expected_output": "1", + "explanation": "5! = 120, one trailing zero." + }, + { + "example_num": 3, + "expected_input": "n = 0", + "expected_output": "0", + "explanation": "" + } + ], + "solution": "/**\n * @param {number} n\n * @return {number}\n */\nconst trailingZeroes = function(n) {\n let result = 0;\n for(let i = 5; Math.floor(n/i) > 0; i *= 5){\n result += (Math.floor(n/i));\n }\n return result;\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720b40", + "questionid": 117, + "title": "House Robber", + "slug": "house-robber", + "description": "You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security systems connected and it will automatically contact the police if two adjacent houses were broken into on the same night. Given an integer array nums representing the amount of money of each house, return the maximum amount of money you can rob tonight without alerting the police. ", + "category": [ + "Array", + "Dynamic Programming" + ], + "complexity": "Medium", + "successrate": 47, + "totalsubmissions": 2334058, + "totalaccepted": 1098090, + "likes": 11854, + "dislikes": 255, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,2,3,1]", + "expected_output": "4", + "explanation": "Rob house 1 (money = 1) and then rob house 3 (money = 3).\nTotal amount you can rob = 1 + 3 = 4." + }, + { + "example_num": 2, + "expected_input": "nums = [2,7,9,3,1]", + "expected_output": "12", + "explanation": "Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1).\nTotal amount you can rob = 2 + 9 + 1 = 12." + } + ], + "solution": "/**\n * @param {number[]} nums\n * @return {number}\n */\nfunction rob(nums) {\n if (nums.length == 0) return 0;\n let prev1 = 0;\n let prev2 = 0;\n for (let num of nums) {\n let tmp = prev1;\n prev1 = Math.max(prev2 + num, prev1);\n prev2 = tmp;\n }\n return prev1;\n}\n\n// another\n\n/**\n * @param {number[]} nums\n * @return {number}\n */\nconst rob = function(nums) {\n const n = nums.length\n const dp = Array(n+1).fill(0)\n dp[1] = nums[0] \n \n for(let i = 1; i < n; i++) {\n dp[i + 1] = Math.max(dp[i], dp[i - 1] + nums[i])\n }\n \n return dp[n]\n};\n\n// another\n/**\n * @param {number[]} nums\n * @return {number}\n */\nconst rob = function(nums) {\n const n = nums.length\n const dp = Array(n + 1).fill(0)\n for(let i = 1; i <= n; i++) {\n const e = nums[i - 1]\n dp[i] = Math.max(dp[i - 1], (i === 1 ? 0 : dp[i - 2]) + e)\n }\n return dp[n]\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720b47", + "questionid": 124, + "title": "Reverse Linked List", + "slug": "reverse-linked-list", + "description": "Given the head of a singly linked list, reverse the list, and return the reversed list. ", + "category": [ + "Linked List", + "Recursion" + ], + "complexity": "Easy", + "successrate": 70.1, + "totalsubmissions": 2927119, + "totalaccepted": 2052205, + "likes": 11446, + "dislikes": 199, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "head = [1,2,3,4,5]", + "expected_output": "[5,4,3,2,1]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "head = [1,2]", + "expected_output": "[2,1]", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "head = []", + "expected_output": "[]", + "explanation": "" + } + ], + "solution": "/**\n * Definition for singly-linked list.\n * function ListNode(val, next) {\n * this.val = (val===undefined ? 0 : val)\n * this.next = (next===undefined ? null : next)\n * }\n */\n/**\n * @param {ListNode} head\n * @return {ListNode}\n */\nconst reverseList = function(head) {\n if(head == null) return head\n const pre = new ListNode(null, head)\n let cur = head\n while(cur.next) {\n const tmp = pre.next\n pre.next = cur.next\n cur.next = cur.next.next\n pre.next.next = tmp\n }\n\n return pre.next\n};\n\n// another\n\n/**\n * Definition for singly-linked list.\n * function ListNode(val) {\n * this.val = val;\n * this.next = null;\n * }\n */\n/**\n * @param {ListNode} head\n * @return {ListNode}\n */\nconst reverseList = function(head) {\n let prev = null;\n let cur = head;\n let tmp;\n let tmpNext;\n while (cur !== null) {\n tmp = cur;\n tmpNext = cur.next;\n cur.next = prev;\n prev = tmp;\n cur = tmpNext;\n }\n\n return prev;\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720b4d", + "questionid": 130, + "title": "Shortest Palindrome", + "slug": "shortest-palindrome", + "description": "You are given a string s. You can convert s to a palindrome by adding characters in front of it. Return the shortest palindrome you can find by performing this transformation. ", + "category": [ + "String", + "Rolling Hash", + "String Matching", + "Hash Function" + ], + "complexity": "Hard", + "successrate": 31.7, + "totalsubmissions": 425047, + "totalaccepted": 134927, + "likes": 2322, + "dislikes": 187, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = \"aacecaaa\"", + "expected_output": "\"aaacecaaa\"", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "s = \"abcd\"", + "expected_output": "\"dcbabcd\"", + "explanation": "" + } + ], + "solution": "/**\n * @param {string} s\n * @return {string}\n */\nconst shortestPalindrome = function(s) {\n let j = 0;\n for (let i = s.length - 1; i >= 0; i--) {\n if (s.charAt(i) === s.charAt(j)) { j += 1; }\n }\n if (j === s.length) { return s; }\n let suffix = s.substring(j);\n return suffix.split('').reverse().join('') + shortestPalindrome(s.substring(0, j)) + suffix;\n};\n\n// another\n\n/**\n * @param {string} s\n * @return {string}\n */\nconst shortestPalindrome = function (s) {\n const tmp = s + '#' + s.split('').reverse().join('')\n const fail = getFail(tmp)\n return (\n s\n .split('')\n .slice(fail[fail.length - 1])\n .reverse()\n .join('') + s\n )\n}\n\nfunction getFail(s) {\n const n = s.length\n const table = new Array(n).fill(0)\n let index = 0\n for (let i = 1; i < n; ) {\n if (s.charAt(index) === s.charAt(i)) {\n table[i] = ++index\n i++\n } else {\n if (index > 0) {\n index = table[index - 1]\n } else {\n index = 0\n i++\n }\n }\n }\n return table\n}\n\n// another\n\n/**\n * @param {string} s\n * @return {string}\n */\nconst shortestPalindrome = function(s) {\n const tmp = `${s}#${reverse(s)}`\n const table = kmp(tmp)\n return `${reverse(s.slice(table[table.length - 1]))}${s}`\n};\nfunction reverse(str) {\n return [...str].reverse().join('')\n}\n\nfunction kmp(s) {\n const n = s.length, table = Array(n).fill(0)\n let idx = 0\n for(let i = 1; i < n; ) {\n if(s[i] === s[idx]) {\n idx++\n table[i] = idx\n i++\n } else {\n if(idx > 0) {\n idx = table[idx - 1]\n } else {\n idx = 0\n i++\n }\n }\n }\n return table\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720b4f", + "questionid": 132, + "title": "Contains Duplicate", + "slug": "contains-duplicate", + "description": "Given an integer array nums, return true if any value appears at least twice in the array, and return false if every element is distinct. ", + "category": [ + "Array", + "Hash Table", + "Sorting" + ], + "complexity": "Easy", + "successrate": 60.7, + "totalsubmissions": 2443511, + "totalaccepted": 1483087, + "likes": 4378, + "dislikes": 943, + "hints": "", + "deleted": false, + "examples": [], + "solution": "/**\n * @param {number[]} nums\n * @return {boolean}\n */\nconst containsDuplicate = function(nums) {\n const hash = {};\n for (let el of nums) {\n if (hash.hasOwnProperty(el)) {\n return true;\n } else {\n hash[el] = 1;\n }\n }\n return false;\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720b52", + "questionid": 135, + "title": "Maximal Square", + "slug": "maximal-square", + "description": "Given an m x n binary matrix filled with 0's and 1's, find the largest square containing only 1's and return its area. ", + "category": [ + "Array", + "Dynamic Programming", + "Matrix" + ], + "complexity": "Medium", + "successrate": 43.4, + "totalsubmissions": 1116716, + "totalaccepted": 484269, + "likes": 7011, + "dislikes": 145, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]]", + "expected_output": "4", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "matrix = [["0","1"],["1","0"]]", + "expected_output": "1", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "matrix = [["0"]]", + "expected_output": "0", + "explanation": "" + } + ], + "solution": "/**\n * @param {character[][]} matrix\n * @return {number}\n */\nconst maximalSquare = function(matrix) {\n const rows = matrix.length\n const cols = rows > 0 ? matrix[0].length : 0\n const dp = Array.from(new Array(rows + 1), el => new Array(cols + 1).fill(0))\n let maxLen = 0\n for(let i = 1; i <= rows; i++) {\n for(let j = 1; j <= cols; j++) {\n if(matrix[i - 1][j - 1] === '1') {\n dp[i][j] = Math.min(dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1]) + 1\n maxLen = Math.max(maxLen, dp[i][j])\n }\n }\n }\n \n return maxLen * maxLen\n};\n\n// another\n\nconst maximalSquare = function(matrix) {\n const rows = matrix.length\n if(rows === 0) return 0\n const cols = matrix[0].length\n const dp = new Array(cols + 1).fill(0)\n let max = 0\n let prev = 0\n let tmp\n for(let i = 1; i <= rows; i++) {\n for(let j = 1; j <= cols; j++) {\n tmp = dp[j]\n if(matrix[i - 1][j - 1] === '1') {\n dp[j] = Math.min(dp[j - 1], dp[j], prev) + 1\n if(dp[j] > max) max = dp[j]\n } else {\n dp[j] = 0\n }\n prev = tmp\n }\n }\n return max ** 2\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720b59", + "questionid": 142, + "title": "Number of Digit One", + "slug": "number-of-digit-one", + "description": "Given an integer n, count the total number of digit 1 appearing in all non-negative integers less than or equal to n. ", + "category": [ + "Math", + "Dynamic Programming", + "Recursion" + ], + "complexity": "Hard", + "successrate": 33.5, + "totalsubmissions": 190665, + "totalaccepted": 63889, + "likes": 704, + "dislikes": 1022, + "hints": "Beware of overflow.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 13", + "expected_output": "6", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "n = 0", + "expected_output": "0", + "explanation": "" + } + ], + "solution": "/**\n * @param {number} n\n * @return {number}\n */\nconst countDigitOne = function(n) {\n let res = 0\n const s = `${n}`\n const len = s.length, {floor, pow} = Math\n\n for(let i = 1; i <= len; i++) {\n const np = pow(10, i - 1)\n const pre = floor(n / pow(10, i))\n const remain = n % np\n \n res += pre * np\n const e = +s[len - i]\n if(e > 1) {\n res += np\n } else if(e === 1) {\n res += remain + 1\n }\n }\n\n return res\n};\n\n\n// another\n\n\n/**\n * @param {number} n\n * @return {number}\n */\nconst countDigitOne = function(n) {\n let res = 0\n const str = `${n}`\n const len = str.length, { pow } = Math\n \n for(let i = 1; i <= len; i++) {\n const pre = ~~(n / pow(10, i))\n const remain = n % (pow(10, i - 1))\n const post = pow(10, i - 1)\n res += pre * post\n const e = +(str[len - i])\n if(e > 1) {\n res += pow(10, i - 1)\n } else if(e === 1) {\n res += remain + 1\n }\n }\n \n return res\n};\n\n\n// another\n\n/**\n * @param {number} n\n * @return {number}\n */\nconst countDigitOne = function(n) {\n return countNum(1, n + 1)\n};\n\n// Counts the number of `digit` in the range [0, limit)\nfunction countNum( digit, limit) {\n let count = 0;\n let factor = 1;\n let tail = 0;\n while (limit >= 10) {\n let d = limit % 10;\n limit = ~~(limit / 10);\n count += limit * factor;\n count += d > digit ? factor : d == digit ? tail : 0;\n tail += d * factor;\n factor *= 10;\n }\n return count + (limit > digit ? factor : limit == digit ? tail : 0);\n}\n\n// another\n\n/**\n * @param {number} n\n * @return {number}\n */\nconst countDigitOne = function(n) {\n let count = 0\n for (let m = 1; m <= n; m *= 10) {\n const a = Math.floor(n / m)\n const b = n % m\n if (a % 10 > 1) {\n count += (Math.floor(a / 10) + 1) * m\n } else if (a % 10 === 1) {\n count += Math.floor(a / 10) * m + b + 1\n } else {\n count += Math.floor(a / 10) * m\n }\n }\n return count\n}\n\n// another\n\n/**\n * @param {number} n\n * @return {number}\n */\nconst countDigitOne = function (n) {\n if (n <= 0) return 0\n let ones = 0\n for (let i = 1, q = n; i <= n; i *= 10, q = (q / 10) >> 0) {\n const pre = (n / (i * 10)) >> 0,\n cur = q % 10,\n suf = n % i\n ones += pre * i\n ones += 1 < cur ? i : 1 == cur ? suf + 1 : 0\n }\n return ones\n}\n\n// another\n\n/**\n * @param {number} n\n * @return {number}\n */\nconst countDigitOne = function(n) {\n let res = 0, factor = 1, lower = 0, cur = 0, higher = 0\n while(~~(n / factor) !== 0) {\n lower = n - (~~(n / factor)) * factor\n cur = (~~(n / factor)) % 10\n higher = ~~(n / (factor * 10))\n switch(cur) {\n case 0:\n res += higher * factor\n break\n case 1:\n res += higher * factor + lower + 1\n break\n default:\n res += (higher + 1) * factor\n break\n }\n factor *= 10\n }\n \n return res\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720b5a", + "questionid": 143, + "title": "Palindrome Linked List", + "slug": "palindrome-linked-list", + "description": "Given the head of a singly linked list, return true if it is a palindrome. ", + "category": [ + "Linked List", + "Two Pointers", + "Stack", + "Recursion" + ], + "complexity": "Easy", + "successrate": 46.5, + "totalsubmissions": 2014641, + "totalaccepted": 935997, + "likes": 8563, + "dislikes": 523, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "head = [1,2,2,1]", + "expected_output": "true", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "head = [1,2]", + "expected_output": "false", + "explanation": "" + } + ], + "solution": "/**\n * Definition for singly-linked list.\n * function ListNode(val) {\n * this.val = val;\n * this.next = null;\n * }\n */\n/**\n * @param {ListNode} head\n * @return {boolean}\n */\nconst isPalindrome = function(head) {\n const arr = [] \n while(head != null) {\n arr.push(head.val)\n head = head.next\n }\n let start = 0\n let end = arr.length - 1\n while(start < end) {\n if(arr[start] !== arr[end]) {\n return false\n }\n start++\n end--\n }\n return true\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720b5d", + "questionid": 146, + "title": "Sliding Window Maximum", + "slug": "sliding-window-maximum", + "description": "You are given an array of integers\u00a0nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position. Return the max sliding window. ", + "category": [ + "Array", + "Queue", + "Sliding Window", + "Heap (Priority Queue)", + "Monotonic Queue" + ], + "complexity": "Hard", + "successrate": 46.2, + "totalsubmissions": 1201410, + "totalaccepted": 554953, + "likes": 9485, + "dislikes": 337, + "hints": "How about using a data structure such as deque (double-ended queue)? The queue size need not be the same as the window\u20ac\u2122s size. Remove redundant elements and the queue should store only elements that need to be considered.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,3,-1,-3,5,3,6,7], k = 3", + "expected_output": "[3,3,5,5,6,7]", + "explanation": "Window position Max\n--------------- -----\n[1 3 -1] -3 5 3 6 7 3\n 1 [3 -1 -3] 5 3 6 7 3\n 1 3 [-1 -3 5] 3 6 7 5\n 1 3 -1 [-3 5 3] 6 7 5\n 1 3 -1 -3 [5 3 6] 7 6\n 1 3 -1 -3 5 [3 6 7] 7" + }, + { + "example_num": 2, + "expected_input": "nums = [1], k = 1", + "expected_output": "[1]", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} nums\n * @param {number} k\n * @return {number[]}\n */\nconst maxSlidingWindow = function(nums, k) {\n const n = nums.length\n const stk = []\n const res = []\n \n for(let i = 0; i < n; i++) {\n while(stk.length && stk[0] < i - k + 1) {\n stk.shift()\n }\n while(stk.length && nums[stk[stk.length - 1]] <= nums[i]) {\n stk.pop()\n }\n stk.push(i)\n if(i >= k - 1) {\n res.push(nums[stk[0]])\n }\n }\n \n return res\n};\n\n// another\n\n/**\n * @param {number[]} nums\n * @param {number} k\n * @return {number[]}\n */\nvar maxSlidingWindow = function (nums, k) {\n if (k === 0) return []\n const deque = new Deque()\n for (let i = 0; i < k - 1; i++) {\n while (!deque.isEmpty() && deque.last().val <= nums[i]) deque.pop()\n deque.enqueue({ val: nums[i], idx: i })\n }\n const result = []\n for (let i = k - 1; i < nums.length; i++) {\n if (!deque.isEmpty() && deque.first().idx <= i - k) deque.dequeue()\n while (!deque.isEmpty() && deque.last().val <= nums[i]) deque.pop()\n deque.enqueue({ val: nums[i], idx: i })\n result.push(deque.first().val)\n }\n return result\n}\n\nclass Deque {\n constructor() {\n this.head = new Node()\n this.tail = this.head\n }\n\n isEmpty() {\n return this.head.next === null\n }\n\n first() {\n return this.head.next.value\n }\n\n last() {\n return this.tail.value\n }\n\n dequeue() {\n this.head = this.head.next\n this.head.prev = null\n }\n\n enqueue(value) {\n this.tail.next = new Node(value)\n this.tail.next.prev = this.tail\n this.tail = this.tail.next\n }\n\n pop() {\n this.tail = this.tail.prev\n this.tail.next = null\n }\n}\n\nclass Node {\n constructor(value) {\n this.value = value\n this.next = null\n this.prev = null\n }\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720b5e", + "questionid": 147, + "title": "Different Ways to Add Parentheses", + "slug": "different-ways-to-add-parentheses", + "description": "Given a string expression of numbers and operators, return all possible results from computing all the different possible ways to group numbers and operators. You may return the answer in any order. ", + "category": [ + "Math", + "String", + "Dynamic Programming", + "Recursion", + "Memoization" + ], + "complexity": "Medium", + "successrate": 61.5, + "totalsubmissions": 259836, + "totalaccepted": 159798, + "likes": 3513, + "dislikes": 171, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "expression = "2-1-1"", + "expected_output": "[0,2]", + "explanation": "((2-1)-1) = 0 \n(2-(1-1)) = 2" + }, + { + "example_num": 2, + "expected_input": "expression = "2*3-4*5"", + "expected_output": "[-34,-14,-10,-10,10]", + "explanation": "(2*(3-(4*5))) = -34 \n((2*3)-(4*5)) = -14 \n((2*(3-4))*5) = -10 \n(2*((3-4)*5)) = -10 \n(((2*3)-4)*5) = 10" + } + ], + "solution": "/**\n * @param {string} input\n * @return {number[]}\n */\nconst diffWaysToCompute = function(input) {\n const res = [];\n let left;\n let right;\n for (let i = 0; i < input.length; i++) {\n if (input[i] < \"0\") {\n left = diffWaysToCompute(input.slice(0, i));\n right = diffWaysToCompute(input.slice(i + 1));\n for (let rl of left) {\n for (let rr of right) {\n switch (input[i]) {\n case \"+\":\n res.push(rl + rr);\n break;\n case \"-\":\n res.push(rl - rr);\n break;\n case \"*\":\n res.push(rl * rr);\n break;\n default:\n break;\n }\n }\n }\n }\n }\n if (res.length === 0) {\n res.push(+input);\n }\n return res;\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720b5f", + "questionid": 148, + "title": "Valid Anagram", + "slug": "valid-anagram", + "description": "Given two strings s and t, return true if t is an anagram of s, and false otherwise. An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. ", + "category": [ + "Hash Table", + "String", + "Sorting" + ], + "complexity": "Easy", + "successrate": 61.4, + "totalsubmissions": 1961949, + "totalaccepted": 1203937, + "likes": 4620, + "dislikes": 209, + "hints": "", + "deleted": false, + "examples": [], + "solution": "/**\n * @param {string} s\n * @param {string} t\n * @return {boolean}\n */\nconst isAnagram = function(s, t) {\n if (s.length !== t.length) return false;\n const sh = strHash(s);\n const th = strHash(t);\n for (let key in sh) {\n if (sh.hasOwnProperty(key) && sh[key] !== th[key]) {\n return false;\n }\n }\n return true;\n};\n\nfunction strHash(str) {\n let res = {};\n for (let i = 0; i < str.length; i++) {\n if (res.hasOwnProperty(str[i])) {\n res[str[i]] += 1;\n } else {\n res[str[i]] = 1;\n }\n }\n return res;\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720b61", + "questionid": 150, + "title": "Add Digits", + "slug": "add-digits", + "description": "Given an integer num, repeatedly add all its digits until the result has only one digit, and return it. ", + "category": [ + "Math", + "Simulation", + "Number Theory" + ], + "complexity": "Easy", + "successrate": 62.4, + "totalsubmissions": 743480, + "totalaccepted": 463936, + "likes": 2409, + "dislikes": 1642, + "hints": "A naive implementation of the above process is trivial. Could you come up with other methods? What are all the possible results? How do they occur, periodically or randomly? You may find this Wikipedia article useful.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "num = 38", + "expected_output": "2", + "explanation": "The process is\n38 --> 3 + 8 --> 11\n11 --> 1 + 1 --> 2 \nSince 2 has only one digit, return it." + }, + { + "example_num": 2, + "expected_input": "num = 0", + "expected_output": "0", + "explanation": "" + } + ], + "solution": "/**\n * @param {number} num\n * @return {number}\n */\nconst addDigits = function(num) {\n let arr = (\"\" + num).split(\"\");\n let res = num;\n\n while (arr.length > 1) {\n res = arr.reduce((ac, el) => +ac + +el, 0);\n arr = (\"\" + res).split(\"\");\n }\n return +res;\n};\n\n// another\n\n/**\n * @param {number} num\n * @return {number}\n */\nconst addDigits = function(num) {\n return 1 + (num - 1) % 9;\n};\n\nconsole.log(addDigits(0));\nconsole.log(addDigits(38));\n" + }, + { + "_id": "66f925ddfdfb8e1665720b6a", + "questionid": 159, + "title": "Move Zeroes", + "slug": "move-zeroes", + "description": "Given an integer array nums, move all 0's to the end of it while maintaining the relative order of the non-zero elements. Note that you must do this in-place without making a copy of the array. ", + "category": [ + "Array", + "Two Pointers" + ], + "complexity": "Easy", + "successrate": 60.6, + "totalsubmissions": 2674454, + "totalaccepted": 1619817, + "likes": 8830, + "dislikes": 239, + "hints": "In-place means we should not be allocating any space for extra array. But we are allowed to modify the existing array. However, as a first step, try coming up with a solution that makes use of additional space. For this problem as well, first apply the idea discussed using an additional array and the in-place solution will pop up eventually. A two-pointer approach could be helpful here. The idea would be to have one pointer for iterating the array and another pointer that just works on the non-zero elements of the array.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [0,1,0,3,12]", + "expected_output": "[1,3,12,0,0]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "nums = [0]", + "expected_output": "[0]", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} nums\n * @return {void} Do not return anything, modify nums in-place instead.\n */\nconst moveZeroes = function(nums) {\n const len = nums.length;\n let l = len;\n for (let i = 0; i < l; ) {\n if (nums[i] === 0) {\n nums.splice(i, 1);\n nums.push(0);\n l -= 1;\n } else {\n i += 1;\n }\n }\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720b6b", + "questionid": 160, + "title": "Find the Duplicate Number", + "slug": "find-the-duplicate-number", + "description": "Given an array of integers nums containing\u00a0n + 1 integers where each integer is in the range [1, n] inclusive. There is only one repeated number in nums, return this\u00a0repeated\u00a0number. You must solve the problem without modifying the array nums\u00a0and uses only constant extra space. ", + "category": [ + "Array", + "Two Pointers", + "Binary Search", + "Bit Manipulation" + ], + "complexity": "Medium", + "successrate": 58.8, + "totalsubmissions": 1384998, + "totalaccepted": 814172, + "likes": 13323, + "dislikes": 1514, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,3,4,2,2]", + "expected_output": "2", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "nums = [3,1,3,4,2]", + "expected_output": "3", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "nums = [3,3,3,3,3]", + "expected_output": "3", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} nums\n * @return {number}\n */\nconst findDuplicate = function(nums) {\n const n = nums.length;\n let ans = 0;\n let bit_max = 31;\n while (((n - 1) >> bit_max) == 0) {\n bit_max -= 1;\n }\n for (let bit = 0; bit <= bit_max; ++bit) {\n let x = 0, y = 0;\n for (let i = 0; i < n; ++i) {\n if ((nums[i] & (1 << bit)) != 0) {\n x += 1;\n }\n if (i >= 1 && ((i & (1 << bit)) != 0)) {\n y += 1;\n }\n }\n if (x > y) {\n ans |= 1 << bit;\n }\n }\n return ans;\n};\n\n// another\n\n/**\n * @param {number[]} nums\n * @return {number}\n */\nconst findDuplicate = function(nums) {\n const len = nums.length\n if(len > 0) {\n let slow = nums[0]\n let fast = nums[nums[0]]\n while(slow !== fast) {\n slow = nums[slow]\n fast = nums[nums[fast]]\n }\n slow = 0\n while(slow !== fast) {\n slow = nums[slow]\n fast = nums[fast]\n }\n return slow\n }\n return -1;\n};\n\n// another\n\n/**\n * @param {number[]} nums\n * @return {number}\n */\nconst findDuplicate = function(nums) {\n let n = nums.length - 1,\n res = 0\n for (let p = 0; p < 32; ++p) {\n let bit = 1 << p,\n a = 0,\n b = 0\n for (let i = 0; i <= n; ++i) {\n if (i > 0 && (i & bit) > 0) ++a\n if ((nums[i] & bit) > 0) ++b\n }\n if (b > a) res += bit\n }\n return res\n}\n\n// another\n\n/**\n * @param {number[]} nums\n * @return {number}\n */\nconst findDuplicate = function(nums) {\n const hash = {};\n for (let i = 0; i < nums.length; i++) {\n if (hash.hasOwnProperty(nums[i])) {\n return nums[i];\n } else {\n hash[nums[i]] = 1;\n }\n }\n};\n\n\n/**\n\n# File: FindDuplicate.py\n# Author: Keith Schwarz (htiek@cs.stanford.edu)\n#\n# An algorithm for solving the following (classic) hard interview problem:\n#\n# \"You are given an array of integers of length n, where each element ranges\n# from 0 to n - 2, inclusive. Prove that at least one duplicate element must\n# exist, and give an O(n)-time, O(1)-space algorithm for finding some\n# duplicated element. You must not modify the array elements during this \n# process.\"\n#\n# This problem (reportedly) took CS legend Don Knuth twenty-four hours to solve\n# and I have only met one person (Keith Amling) who could solve it in less time\n# than this.\n#\n# The first part of this problem - proving that at least one duplicate element\n# must exist - is a straightforward application of the pigeonhole principle.\n# If the values range from 0 to n - 2, inclusive, then there are only n - 1\n# different values. If we have an array of n elements, one must necessarily be\n# duplicated.\n#\n# The second part of this problem - finding the duplicated element subject to\n# the given constraints - is much harder. To solve this, we're going to need a\n# series of nonobvious insights that transform the problem into an instance of\n# something entirely different.\n#\n# The main trick we need to use to solve this problem is to notice that because\n# we have an array of n elements ranging from 0 to n - 2, we can think of the\n# array as defining a function f from the set {0, 1, ..., n - 1} onto itself.\n# This function is defined by f(i) = A[i]. Given this setup, a duplicated\n# value corresponds to a pair of indices i != j such that f(i) = f(j). Our\n# challenge, therefore, is to find this pair (i, j). Once we have it, we can\n# easily find the duplicated value by just picking f(i) = A[i].\n#\n# But how are we to find this repeated value? It turns out that this is a\n# well-studied problem in computer science called cycle detection. The general\n# form of the problem is as follows. We are given a function f. Define the\n# sequence x_i as\n#\n# x_0 = k (for some k)\n# x_1 = f(x_0)\n# x_2 = f(f(x_0))\n# ...\n# x_{n+1} = f(x_n)\n#\n# Assuming that f maps from a domain into itself, this function will have one\n# of three forms. First, if the domain is infinite, then the sequence could be\n# infinitely long and nonrepeating. For example, the function f(n) = n + 1 on\n# the integers has this property - no number is ever duplicated. Second, the\n# sequence could be a closed loop, which means that there is some i so that\n# x_0 = x_i. In this case, the sequence cycles through some fixed set of\n# values indefinitely. Finally, the sequence could be \"rho-shaped.\" In this\n# case, the sequence looks something like this:\n#\n# x_0 -> x_1 -> ... x_k -> x_{k+1} ... -> x_{k+j}\n# ^ |\n# | |\n# +-----------------------+\n#\n# That is, the sequence begins with a chain of elements that enters a cycle,\n# then cycles around indefinitely. We'll denote the first element of the cycle\n# that is reached in the sequence the \"entry\" of the cycle.\n#\n# For our particular problem of finding a duplicated element in the array,\n# consider the sequence formed by starting at position n - 1 and then\n# repeatedly applying f. That is, we start at the last position in the array,\n# then go to the indicated index, repeating this process. My claim is that\n# this sequence is rho-shaped. To see this, note that it must contains a cycle\n# because the array is finite and after visiting n elements, we necessarily\n# must visit some element twice. This is true no matter where we start off in\n# the array. Moreover, note that since the array elements range from 0 to\n# n - 2 inclusive, there is no array index that contains n - 1 as a value.\n# Consequently, when we leave index n - 1 after applying the function f one\n# time, we can never get back there. This means that n - 1 can't be part of a\n# cycle, but if we follow indices starting there we must eventually hit some\n# other node twice. The concatenation of the chain starting at n - 1 with the\n# cycle it hits must be rho-shaped.\n#\n# Moreover, think about the node we encounter that starts at the entry of the\n# cycle. Since this node is at the entry of the cycle, there must be two\n# inputs to the function f that both result in that index being generated. For\n# this to be possible, it must be that there are indices i != j with\n# f(i) = f(j), meaning that A[i] = A[j]. Thus the index of the entry of the\n# cycle must be one of the values that is duplicated in the array.\n#\n# There is a famous algorithm due to Robert Floyd that, given a rho-shaped\n# sequence, finds the entry point of the cycle in linear time and using only\n# constant space. This algorithm is often referred to as the \"tortoise and\n# hare\" algorithm, for reasons that will become clearer shortly.\n#\n# The idea behind the algorithm is to define two quantities. First, let c be\n# the length of the chain that enters the cycle, and let l be the length of the\n# cycle. Next, let l' be the smallest multiple of l that's larger than c.\n# I claim that for any rho-shaped sequence l' defined above, that\n#\n# x_{l'} = x_{2l'}\n#\n# The proof is actually straightforward and very illustrative - it's one of my\n# favorite proofs in computer science. The idea is that since l' is at least\n# c, it must be contained in the cycle. Moreover, since l' is a multiple of\n# the length of the loop, we can write it as ml for some constant m. If we\n# start at position x_{l'}, which is inside the loop, then take l' more steps\n# forward to get to x_{2l'}, then we will just walk around the loop m times,\n# ending up right back where we started.\n#\n# One key trick of Floyd's algorithm is that even if we don't explicitly know l\n# or c, we can still find the value l' in O(l') time. The idea is as follows.\n# We begin by keeping track of two values \"slow\" and \"fast,\" both starting at\n# x_0. We then iteratively compute\n#\n# slow = f(slow)\n# fast = f(f(fast))\n#\n# We repeat this process until we find that slow and fast are equal to one\n# another. When this happens, we know that slow = x_j for some j, and\n# fast = x_{2j} for that same j. Since x_j = x_{2j}, we know that j must be at\n# least c, since it has to be contained in the cycle. Moreover, we know that j\n# must be a multiple of l, since the fact that x_j = x_{2j} means that taking j\n# steps while in the cycle ends up producing the same result. Finally, j must\n# be the smallest multiple of l greater than c, since if there were a smaller\n# multiple of l greater than c then we would have reached that multiple before\n# we reached j. Consequently, we must have that j = l', meaning that we can\n# find l' without knowing anything about the length or shape of the cycle!\n#\n# To complete the construction, we need to show how to use our information\n# about l' to find the entry to the cycle (which is at position x_c). To do\n# this, we start off one final variable, which we call \"finder,\" at x_0. We\n# then iteratively repeat the following:\n#\n# finder = f(finder)\n# slow = f(slow)\n#\n# until finder = slow. We claim that (1) the two will eventually hit each\n# other, and (2) they will hit each other at the entry to the cycle. To see\n# this, we remark that since slow is at position x_{l'}, if we take c steps\n# forward, then we have that slow will be at position x_{l' + c}. Since l' is\n# a multiple of the loop length, this is equivalent to taking c steps forward,\n# then walking around the loop some number of times back to where you started.\n# In other words, x_{l' + c} = x_c. Moreover, consider the position of the\n# finder variable after c steps. It starts at x_0, so after c steps it will be\n# at position x_c. This proves both (1) and (2), since we've shown that the\n# two must eventually hit each other, and when they do they hit at position x_c\n# at the entry to the cycle.\n#\n# The beauty of this algorithm is that it uses only O(1) external memory to\n# keep track of two different pointers - the slow pointer, and then the fast\n# pointer (for the first half) and the finder pointer (for the second half).\n# But on top of that, it runs in O(n) time. To see this, note that the time\n# required for the slow pointer to hit the fast pointer is O(l'). Since l' is\n# the smallest multiple of l greater than c, we have two cases to consider.\n# First, if l > c, then this is l. Otherwise, if l < c, then we have that\n# there must be some multiple of l between c and 2c. To see this, note that\n# in the range c and 2c there are c different values, and since l < c at least\n# one of them must be equal to 0 mod l. Finally, the time required to find the\n# start of the cycle from this point is O(c). This gives a total runtime of at\n# most O(c + max{l, 2c}). All of these values are at most n, so this algorithm\n# runs in time O(n).\n\ndef findArrayDuplicate(array):\n assert len(array) > 0\n\n # The \"tortoise and hare\" step. We start at the end of the array and try\n # to find an intersection point in the cycle.\n slow = len(array) - 1\n fast = len(array) - 1\n\n # Keep advancing 'slow' by one step and 'fast' by two steps until they\n # meet inside the loop.\n while True:\n slow = array[slow]\n fast = array[array[fast]]\n\n if slow == fast:\n break\n\n # Start up another pointer from the end of the array and march it forward\n # until it hits the pointer inside the array.\n finder = len(array) - 1\n while True:\n slow = array[slow]\n finder = array[finder]\n\n # If the two hit, the intersection index is the duplicate element.\n if slow == finder:\n return slow\n\n\n*/\n" + }, + { + "_id": "66f925ddfdfb8e1665720b6d", + "questionid": 162, + "title": "Longest Increasing Subsequence", + "slug": "longest-increasing-subsequence", + "description": "Given an integer array nums, return the length of the longest strictly increasing subsequence. A subsequence is a sequence that can be derived from an array by deleting some or no elements without changing the order of the remaining elements. For example, [3,6,2,7] is a subsequence of the array [0,3,1,6,2,2,7]. ", + "category": [ + "Array", + "Binary Search", + "Dynamic Programming" + ], + "complexity": "Medium", + "successrate": 49.1, + "totalsubmissions": 1685924, + "totalaccepted": 827984, + "likes": 11472, + "dislikes": 227, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [10,9,2,5,3,7,101,18]", + "expected_output": "4", + "explanation": "The longest increasing subsequence is [2,3,7,101], therefore the length is 4." + }, + { + "example_num": 2, + "expected_input": "nums = [0,1,0,3,2,3]", + "expected_output": "4", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "nums = [7,7,7,7,7,7,7]", + "expected_output": "1", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} nums\n * @return {number}\n */\nconst lengthOfLIS = function(nums) {\n const stack = []\n for(let e of nums) {\n if(stack.length === 0 || e > stack[stack.length - 1]) {\n stack.push(e)\n continue\n }\n let l = 0, r = stack.length - 1, mid\n while(l < r) {\n const mid = l + ((r - l) >> 1)\n if(e > stack[mid]) l = mid + 1\n else r = mid\n }\n stack[l] = e\n }\n return stack.length\n};\n\n// another\n\n/**\n * @param {number[]} nums\n * @return {number}\n */\nconst lengthOfLIS = function(nums) {\n if (nums.length === 0) {\n return 0\n }\n const dp = new Array(nums.length).fill(0)\n dp[0] = 1\n let maxans = 1\n for(let i = 1; i < dp.length; i++) {\n let maxval = 0\n for(let j = 0; j < i; j++) {\n if(nums[i] > nums[j]) {\n maxval = Math.max(maxval, dp[j])\n }\n }\n dp[i] = maxval + 1\n maxans = Math.max(maxans, dp[i])\n }\n return maxans\n};\n\n// another\n\n/**\n * @param {number[]} nums\n * @return {number}\n */\nconst lengthOfLIS = function(nums) {\n const n = nums.length\n const tails = []\n let res = 0\n for(let e of nums) {\n let i = 0, j = res\n while(i !== j) {\n const mid = i + ((j - i) >> 1)\n if(tails[mid] < e) i = mid + 1\n else j = mid\n }\n tails[i] = e\n if(i === res) res++\n }\n return res\n};\n\n// another\n\n/**\n * @param {number[]} nums\n * @return {number}\n */\nconst lengthOfLIS = function(nums) {\n const n = nums.length, stack = []\n let res = 0\n stack.push(nums[0])\n for(let i = 1; i < n; i++) {\n const cur = nums[i]\n if(cur > stack[stack.length - 1]) {\n stack.push(cur)\n } else {\n let l = 0, r = stack.length - 1\n while(l < r) {\n let mid = ~~((l + r) / 2)\n if(stack[mid] < cur) {\n l = mid + 1\n } else {\n r = mid\n }\n }\n stack[l] = cur\n }\n }\n \n return stack.length\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720b70", + "questionid": 165, + "title": "Burst Balloons", + "slug": "burst-balloons", + "description": "You are given n balloons, indexed from 0 to n - 1. Each balloon is painted with a number on it represented by an array nums. You are asked to burst all the balloons. If you burst the ith balloon, you will get nums[i - 1] * nums[i] * nums[i + 1] coins. If i - 1 or i + 1 goes out of bounds of the array, then treat it as if there is a balloon with a 1 painted on it. Return the maximum coins you can collect by bursting the balloons wisely. ", + "category": [ + "Array", + "Dynamic Programming" + ], + "complexity": "Hard", + "successrate": 56.3, + "totalsubmissions": 325121, + "totalaccepted": 182895, + "likes": 5795, + "dislikes": 157, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [3,1,5,8]", + "expected_output": "167", + "explanation": "nums = [3,1,5,8] --> [3,5,8] --> [3,8] --> [8] --> []\ncoins = 3*1*5 + 3*5*8 + 1*3*8 + 1*8*1 = 167" + }, + { + "example_num": 2, + "expected_input": "nums = [1,5]", + "expected_output": "10", + "explanation": "" + } + ], + "solution": "function maxCoins(arr) {\n const len = arr.length\n const nums = Array(len + 2).fill(0);\n let n = 1;\n for (const x of arr) if (x > 0) nums[n++] = x;\n nums[0] = nums[n++] = 1;\n\n const dp = Array.from({ length: n }, () => Array(n).fill(0));\n for (let k = 2; k < n; k++) {\n for (let left = 0; left < n - k; left++) {\n let right = left + k;\n for (let i = left + 1; i < right; i++) {\n dp[left][right] = Math.max(\n dp[left][right],\n nums[left] * nums[i] * nums[right] + dp[left][i] + dp[i][right],\n );\n }\n }\n }\n\n return dp[0][n - 1];\n}\n\n// another\n\n/**\n * @param {number[]} nums\n * @return {number}\n */\nconst maxCoins = iNums => {\n const nums = new Array(iNums.length + 2);\n let n = 1;\n for (let x of iNums) if (x > 0) nums[n++] = x;\n nums[0] = nums[n++] = 1;\n\n const memo = Array.from({ length: n }, () => new Array(n));\n return burst(memo, nums, 0, n - 1);\n};\n\nfunction burst(memo, nums, left, right) {\n if (left + 1 === right) return 0;\n if (memo[left][right] > 0) return memo[left][right];\n let ans = 0;\n for (let i = left + 1; i < right; ++i)\n ans = Math.max(\n ans,\n nums[left] * nums[i] * nums[right] +\n burst(memo, nums, left, i) +\n burst(memo, nums, i, right)\n );\n memo[left][right] = ans;\n return ans;\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720b71", + "questionid": 166, + "title": "Super Ugly Number", + "slug": "super-ugly-number", + "description": "A super ugly number is a positive integer whose prime factors are in the array primes. Given an integer n and an array of integers primes, return the nth super ugly number. The nth super ugly number is guaranteed to fit in a 32-bit signed integer. ", + "category": [ + "Array", + "Hash Table", + "Math", + "Dynamic Programming", + "Heap (Priority Queue)" + ], + "complexity": "Medium", + "successrate": 45.8, + "totalsubmissions": 226970, + "totalaccepted": 103863, + "likes": 1460, + "dislikes": 278, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 12, primes = [2,7,13,19]", + "expected_output": "32", + "explanation": "[1,2,4,7,8,13,14,16,19,26,28,32] is the sequence of the first 12 super ugly numbers given primes = [2,7,13,19]." + }, + { + "example_num": 2, + "expected_input": "n = 1, primes = [2,3,5]", + "expected_output": "1", + "explanation": "1 has no prime factors, therefore all of its prime factors are in the array primes = [2,3,5]." + } + ], + "solution": "/**\n * @param {number} n\n * @param {number[]} primes\n * @return {number}\n */\nconst nthSuperUglyNumber = function(n, primes) {\n if (n === 1) return 1\n const indexes = new Array(primes.length).fill(0)\n const arr = [1]\n for (let i = 1; i <= n - 1; i++) {\n arr[i] = +Infinity\n for (let j = 0; j < primes.length; j++) {\n arr[i] = Math.min(arr[i], arr[indexes[j]] * primes[j])\n }\n for (let j = 0; j < primes.length; j++) {\n if (arr[i] === arr[indexes[j]] * primes[j]) {\n indexes[j]++\n }\n }\n }\n return arr[n - 1]\n}\n\n// another\n\n/**\n * @param {number} n\n * @param {number[]} primes\n * @return {number}\n */\nconst nthSuperUglyNumber = function(n, primes) {\n const ugly = Array(n).fill(0)\n const pq = new PriorityQueue((a, b) => a[0] < b[0])\n \n for(let i = 0; i < primes.length; i++) pq.push([primes[i], 1, primes[i]])\n ugly[0] = 1\n for(let i = 1; i < n; i++) {\n ugly[i] = pq.peek()[0]\n while(pq.peek()[0] === ugly[i]) {\n const next = pq.pop()\n pq.push([next[2] * ugly[next[1]], next[1] + 1, next[2]])\n }\n }\n \n return ugly[n - 1]\n};\n\nclass PriorityQueue {\n constructor(comparator = (a, b) => a > b) {\n this.heap = []\n this.top = 0\n this.comparator = comparator\n }\n size() {\n return this.heap.length\n }\n isEmpty() {\n return this.size() === 0\n }\n peek() {\n return this.heap[this.top]\n }\n push(...values) {\n values.forEach((value) => {\n this.heap.push(value)\n this.siftUp()\n })\n return this.size()\n }\n pop() {\n const poppedValue = this.peek()\n const bottom = this.size() - 1\n if (bottom > this.top) {\n this.swap(this.top, bottom)\n }\n this.heap.pop()\n this.siftDown()\n return poppedValue\n }\n replace(value) {\n const replacedValue = this.peek()\n this.heap[this.top] = value\n this.siftDown()\n return replacedValue\n }\n\n parent = (i) => ((i + 1) >>> 1) - 1\n left = (i) => (i << 1) + 1\n right = (i) => (i + 1) << 1\n greater = (i, j) => this.comparator(this.heap[i], this.heap[j])\n swap = (i, j) => ([this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]])\n siftUp = () => {\n let node = this.size() - 1\n while (node > this.top && this.greater(node, this.parent(node))) {\n this.swap(node, this.parent(node))\n node = this.parent(node)\n }\n }\n siftDown = () => {\n let node = this.top\n while (\n (this.left(node) < this.size() && this.greater(this.left(node), node)) ||\n (this.right(node) < this.size() && this.greater(this.right(node), node))\n ) {\n let maxChild =\n this.right(node) < this.size() &&\n this.greater(this.right(node), this.left(node))\n ? this.right(node)\n : this.left(node)\n this.swap(node, maxChild)\n node = maxChild\n }\n }\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720b76", + "questionid": 171, + "title": "Create Maximum Number", + "slug": "create-maximum-number", + "description": "You are given two integer arrays nums1 and nums2 of lengths m and n respectively. nums1 and nums2 represent the digits of two numbers. You are also given an integer k. Create the maximum number of length k <= m + n from digits of the two numbers. The relative order of the digits from the same array must be preserved. Return an array of the k digits representing the answer. ", + "category": [ + "Stack", + "Greedy", + "Monotonic Stack" + ], + "complexity": "Hard", + "successrate": 28.4, + "totalsubmissions": 173497, + "totalaccepted": 49224, + "likes": 1323, + "dislikes": 307, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums1 = [3,4,6,5], nums2 = [9,1,2,5,8,3], k = 5", + "expected_output": "[9,8,6,5,3]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "nums1 = [6,7], nums2 = [6,0,4], k = 5", + "expected_output": "[6,7,6,0,4]", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "nums1 = [3,9], nums2 = [8,9], k = 3", + "expected_output": "[9,8,9]", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} nums1\n * @param {number[]} nums2\n * @param {number} k\n * @return {number[]}\n */\nconst maxNumber = function(nums1, nums2, k) {\n const n = nums1.length\n const m = nums2.length\n let ans = new Array(k).fill(0)\n for (let i = Math.max(0, k - m); i <= k && i <= n; i++) {\n const candidate = merge(maxArray(nums1, i), maxArray(nums2, k - i), k)\n if (greater(candidate, 0, ans, 0)) ans = candidate\n }\n return ans\n}\n\nfunction merge(nums1, nums2, k) {\n const ans = new Array(k)\n for (let i = 0, j = 0, r = 0; r < k; r++) {\n ans[r] = greater(nums1, i, nums2, j) ? nums1[i++] : nums2[j++]\n }\n return ans\n}\n\nfunction greater(nums1, i, nums2, j) {\n while (i < nums1.length && j < nums2.length && nums1[i] === nums2[j]) {\n i++\n j++\n }\n return j === nums2.length || (i < nums1.length && nums1[i] > nums2[j])\n}\n\nfunction maxArray(nums, k) {\n const n = nums.length\n const ans = new Array(k)\n for (let i = 0, j = 0; i < n; i++) {\n while (n - i > k - j && j > 0 && ans[j - 1] < nums[i]) j--\n if (j < k) ans[j++] = nums[i]\n }\n return ans\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720b78", + "questionid": 173, + "title": "Wiggle Sort II", + "slug": "wiggle-sort-ii", + "description": "Given an integer array nums, reorder it such that nums[0] < nums[1] > nums[2] < nums[3].... You may assume the input array always has a valid answer. ", + "category": [ + "Array", + "Divide and Conquer", + "Sorting", + "Quickselect" + ], + "complexity": "Medium", + "successrate": 32.2, + "totalsubmissions": 372665, + "totalaccepted": 119965, + "likes": 2055, + "dislikes": 793, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,5,1,1,6,4]", + "expected_output": "[1,6,1,5,1,4]", + "explanation": "[1,4,1,5,1,6] is also accepted." + }, + { + "example_num": 2, + "expected_input": "nums = [1,3,2,2,3,1]", + "expected_output": "[2,3,1,3,1,2]", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} nums\n * @return {void} Do not return anything, modify nums in-place instead.\n */\nconst wiggleSort = function(nums) {\n nums.sort((a, b) => a - b)\n const ref = [...nums]\n let j = nums.length - 1\n for (let i = 1; i < nums.length; i += 2, j--) nums[i] = ref[j]\n for (let i = 0; i < nums.length; i += 2, j--) nums[i] = ref[j]\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720b79", + "questionid": 174, + "title": "Power of Three", + "slug": "power-of-three", + "description": "Given an integer n, return true if it is a power of three. Otherwise, return false. An integer n is a power of three, if there exists an integer x such that n == 3x. ", + "category": [ + "Math", + "Recursion" + ], + "complexity": "Easy", + "successrate": 43.4, + "totalsubmissions": 1046656, + "totalaccepted": 454534, + "likes": 902, + "dislikes": 118, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 27", + "expected_output": "true", + "explanation": "27 = 33" + }, + { + "example_num": 2, + "expected_input": "n = 0", + "expected_output": "false", + "explanation": "There is no x where 3x = 0." + }, + { + "example_num": 3, + "expected_input": "n = -1", + "expected_output": "false", + "explanation": "There is no x where 3x = (-1)." + } + ], + "solution": "/**\n * @param {number} n\n * @return {boolean}\n */\nconst isPowerOfThree = function(n) {\n const maxInt = Math.pow(3,30)\n if(n < 0) {\n return false\n }\n return maxInt % n === 0\n} \n\n// another\n\nconst isPowerOfThree = function(n) {\n if (n == 1) return true\n if (n === 0) return false\n if (n % 3 !== 0) return false\n if (n == 3) return true\n return isPowerOfThree(n / 3)\n}\n\n// another\n\nconst isPowerOfThree = function(n) {\n if(n == null || n === 0) return false\n let num = 1\n while(num < n) {\n num *= 3\n } \n return num > n ? false : true\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720b7b", + "questionid": 176, + "title": "Odd Even Linked List", + "slug": "odd-even-linked-list", + "description": "Given the head of a singly linked list, group all the nodes with odd indices together followed by the nodes with even indices, and return the reordered list. The first node is considered odd, and the second node is even, and so on. Note that the relative order inside both the even and odd groups should remain as it was in the input. You must solve the problem\u00a0in O(1)\u00a0extra space complexity and O(n) time complexity. ", + "category": [ + "Linked List" + ], + "complexity": "Medium", + "successrate": 59.5, + "totalsubmissions": 871544, + "totalaccepted": 518520, + "likes": 5183, + "dislikes": 383, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "head = [1,2,3,4,5]", + "expected_output": "[1,3,5,2,4]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "head = [2,1,3,5,6,4,7]", + "expected_output": "[2,3,6,7,1,5,4]", + "explanation": "" + } + ], + "solution": "/**\n * Definition for singly-linked list.\n * function ListNode(val) {\n * this.val = val;\n * this.next = null;\n * }\n */\n/**\n * @param {ListNode} head\n * @return {ListNode}\n */\nconst oddEvenList = function(head) {\n if (head === null) return null;\n let odd = head,\n even = head.next,\n evenHead = even;\n while (even !== null && even.next !== null) {\n odd.next = even.next;\n odd = odd.next;\n even.next = odd.next;\n even = even.next;\n }\n odd.next = evenHead;\n return head;\n};\n\n// another\n\n/**\n * Definition for singly-linked list.\n * function ListNode(val, next) {\n * this.val = (val===undefined ? 0 : val)\n * this.next = (next===undefined ? null : next)\n * }\n */\n/**\n * @param {ListNode} head\n * @return {ListNode}\n */\nfunction oddEvenList(head) {\n if(head == null) return head\n const dummyOdd = new ListNode()\n const dummyEven = new ListNode()\n \n dummyOdd.next = head\n let odd = head, even = dummyEven\n let idx = 2, cur = head.next\n while(cur) {\n if (idx % 2 === 1) {\n odd.next = cur\n odd = odd.next\n } else {\n even.next = cur\n even = even.next\n }\n cur = cur.next\n idx++\n }\n odd.next = dummyEven.next\n even.next = null\n return dummyOdd.next\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720b7d", + "questionid": 178, + "title": "Reconstruct Itinerary", + "slug": "reconstruct-itinerary", + "description": "You are given a list of airline tickets where tickets[i] = [fromi, toi] represent the departure and the arrival airports of one flight. Reconstruct the itinerary in order and return it. All of the tickets belong to a man who departs from \"JFK\", thus, the itinerary must begin with \"JFK\". If there are multiple valid itineraries, you should return the itinerary that has the smallest lexical order when read as a single string. You may assume all tickets form at least one valid itinerary. You must use all the tickets once and only once. ", + "category": [ + "Depth-First Search", + "Graph", + "Eulerian Circuit" + ], + "complexity": "Hard", + "successrate": 40.1, + "totalsubmissions": 689553, + "totalaccepted": 276521, + "likes": 3766, + "dislikes": 1545, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "tickets = [["MUC","LHR"],["JFK","MUC"],["SFO","SJC"],["LHR","SFO"]]", + "expected_output": "["JFK","MUC","LHR","SFO","SJC"]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "tickets = [["JFK","SFO"],["JFK","ATL"],["SFO","ATL"],["ATL","JFK"],["ATL","SFO"]]", + "expected_output": "["JFK","ATL","JFK","SFO","ATL","SFO"]", + "explanation": "Another possible reconstruction is ["JFK","SFO","ATL","JFK","ATL","SFO"] but it is larger in lexical order." + } + ], + "solution": "/**\n * @param {string[][]} tickets\n * @return {string[]}\n */\nconst findItinerary = function (tickets) {\n const result = []\n const map = new Map()\n for (const [from, to] of tickets) {\n if (!map.has(from)) {\n map.set(from, [])\n }\n map.get(from).push(to)\n }\n for (const key of map.keys()) {\n map.get(key).sort()\n }\n function dfs(departure) {\n const destination = map.get(departure)\n while (destination && destination.length) {\n const newDeparture = destination.shift()\n dfs(newDeparture)\n }\n result.push(departure)\n }\n dfs('JFK')\n return result.reverse()\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720b81", + "questionid": 182, + "title": "House Robber III", + "slug": "house-robber-iii", + "description": "The thief has found himself a new place for his thievery again. There is only one entrance to this area, called root. Besides the root, each house has one and only one parent house. After a tour, the smart thief realized that all houses in this place form a binary tree. It will automatically contact the police if two directly-linked houses were broken into on the same night. Given the root of the binary tree, return the maximum amount of money the thief can rob without alerting the police. ", + "category": [ + "Dynamic Programming", + "Tree", + "Depth-First Search", + "Binary Tree" + ], + "complexity": "Medium", + "successrate": 53.5, + "totalsubmissions": 528529, + "totalaccepted": 282635, + "likes": 6128, + "dislikes": 93, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [3,2,3,null,3,null,1]", + "expected_output": "7", + "explanation": "Maximum amount of money the thief can rob = 3 + 3 + 1 = 7." + }, + { + "example_num": 2, + "expected_input": "root = [3,4,5,1,3,null,1]", + "expected_output": "9", + "explanation": "Maximum amount of money the thief can rob = 4 + 5 = 9." + } + ], + "solution": "/**\n * Definition for a binary tree node.\n * function TreeNode(val, left, right) {\n * this.val = (val===undefined ? 0 : val)\n * this.left = (left===undefined ? null : left)\n * this.right = (right===undefined ? null : right)\n * }\n */\n/**\n * @param {TreeNode} root\n * @return {number}\n */\nconst rob = function(root) {\n if(root == null) return 0\n return Math.max(...dfs(root))\n \n function dfs(node) {\n if(node == null) return [0, 0]\n const l = dfs(node.left), r = dfs(node.right)\n return [node.val + l[1] + r[1], Math.max(...l) + Math.max(...r)]\n }\n};\n\n// another\n\n\n/**\n * Definition for a binary tree node.\n * function TreeNode(val) {\n * this.val = val;\n * this.left = this.right = null;\n * }\n */\n/**\n * @param {TreeNode} root\n * @return {number}\n */\nconst rob = function(root) {\n return Math.max(...dfs(root))\n}\n\nfunction dfs(node) {\n if (node == null) return [0, 0]\n const left = dfs(node.left)\n const right = dfs(node.right)\n return [\n node.val + left[1] + right[1],\n Math.max(left[0], left[1]) + Math.max(right[0], right[1])\n ]\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720b84", + "questionid": 185, + "title": "Integer Break", + "slug": "integer-break", + "description": "Given an integer n, break it into the sum of k positive integers, where k >= 2, and maximize the product of those integers. Return the maximum product you can get. ", + "category": [ + "Math", + "Dynamic Programming" + ], + "complexity": "Medium", + "successrate": 54, + "totalsubmissions": 337951, + "totalaccepted": 182547, + "likes": 2696, + "dislikes": 324, + "hints": "There is a simple O(n) solution to this problem. You may check the breaking results of n ranging from 7 to 10 to discover the regularities.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 2", + "expected_output": "1", + "explanation": "2 = 1 + 1, 1 × 1 = 1." + }, + { + "example_num": 2, + "expected_input": "n = 10", + "expected_output": "36", + "explanation": "10 = 3 + 3 + 4, 3 × 3 × 4 = 36." + } + ], + "solution": "/**\n * @param {number} n\n * @return {number}\n */\nconst integerBreak = function(n) {\n const dp = Array(n + 1).fill(0)\n dp[2] = 1\n for(let i = 3; i <= n; i++) {\n for(let j = 1; j < i; j++) {\n dp[i] = Math.max(dp[i], j * Math.max(i - j, dp[i - j]))\n }\n }\n return dp[n]\n};\n\n// another\n\n/**\n * @param {number} n\n * @return {number}\n */\nconst integerBreak = function(n) {\n if (n <= 2) return 1;\n\n const maxArr = [];\n for (let i = 0; i < n + 1; i++) {\n maxArr[i] = 0;\n }\n\n /** For a number i: write i as a sum of integers, then take the product of those integers.\n maxArr[i] = maximum of all the possible products */\n\n maxArr[1] = 0;\n maxArr[2] = 1; // 2=1+1 so maxArr[2] = 1*1\n\n for (let i = 3; i <= n; i++) {\n for (let j = 1; j < i; j++) {\n /** Try to write i as: i = j + S where S=i-j corresponds to either one number or a sum of two or more numbers\n \n Assuming that j+S corresponds to the optimal solution for maxArr[i], we have two cases:\n (1) i is the sum of two numbers, i.e. S=i-j is one number, and so maxArr[i]=j*(i-j)\n (2) i is the sum of at least three numbers, i.e. S=i-j is a sum of at least 2 numbers,\n and so the product of the numbers in this sum for S is maxArr[i-j]\n (=maximum product after breaking up i-j into a sum of at least two integers):\n maxArr[i] = j*maxArr[i-j]\n */\n maxArr[i] = Math.max(maxArr[i], j * (i - j), j * maxArr[i - j]);\n }\n }\n return maxArr[n];\n};\n\n// another\n\n/**\n * @param {number} n\n * @return {number}\n */\nconst integerBreak = function(n) {\n if(n === 2) return 1\n if(n === 3) return 2\n let num = ~~(n / 3)\n let rem = n % 3\n if(rem === 1) {\n rem += 3\n num--\n }\n return rem === 0 ? Math.pow(3, num) : Math.pow(3, num) * rem\n};\n\n/**\n\nIf an optimal product contains a factor f >= 4, \nthen you can replace it with factors 2 and f-2 without losing optimality,\nas 2*(f-2) = 2f-4 >= f. So you never need a factor greater than or equal to 4,\nmeaning you only need factors 1, 2 and 3 (and 1 is of course wasteful and you'd only use it for n=2 and n=3, where it's needed).\n\nFor the rest I agree, 3*3 is simply better than 2*2*2, so you'd never use 2 more than twice.\n\n*/\n" + }, + { + "_id": "66f925ddfdfb8e1665720b89", + "questionid": 190, + "title": "Intersection of Two Arrays II", + "slug": "intersection-of-two-arrays-ii", + "description": "Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must appear as many times as it shows in both arrays and you may return the result in any order. ", + "category": [ + "Array", + "Hash Table", + "Two Pointers", + "Binary Search", + "Sorting" + ], + "complexity": "Easy", + "successrate": 54.8, + "totalsubmissions": 1412120, + "totalaccepted": 774103, + "likes": 4292, + "dislikes": 684, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums1 = [1,2,2,1], nums2 = [2,2]", + "expected_output": "[2,2]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "nums1 = [4,9,5], nums2 = [9,4,9,8,4]", + "expected_output": "[4,9]", + "explanation": "[9,4] is also accepted." + } + ], + "solution": "/**\n * @param {number[]} nums1\n * @param {number[]} nums2\n * @return {number[]}\n */\nconst intersect = function(nums1, nums2) {\n const res = []\n const map = {}\n for(let i = 0; i < nums1.length; i++) {\n if(map.hasOwnProperty(nums1[i])) {\n map[nums1[i]] += 1\n } else {\n map[nums1[i]] = 1\n }\n }\n \n for(let j = 0; j < nums2.length; j++) {\n if(map.hasOwnProperty(nums2[j]) && map[nums2[j]] > 0) {\n res.push(nums2[j])\n map[nums2[j]] -= 1\n }\n }\n \n return res\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720b8a", + "questionid": 191, + "title": "Count Numbers with Unique Digits", + "slug": "count-numbers-with-unique-digits", + "description": "Given an integer n, return the count of all numbers with unique digits, x, where 0 <= x < 10n. ", + "category": [ + "Math", + "Dynamic Programming", + "Backtracking" + ], + "complexity": "Medium", + "successrate": 50.6, + "totalsubmissions": 200530, + "totalaccepted": 101429, + "likes": 870, + "dislikes": 1223, + "hints": "A direct way is to use the backtracking approach. Backtracking should contains three states which are (the current number, number of steps to get that number and a bitmask which represent which number is marked as visited so far in the current number). Start with state (0,0,0) and count all valid number till we reach number of steps equals to 10n. This problem can also be solved using a dynamic programming approach and some knowledge of combinatorics. Let f(k) = count of numbers with unique digits with length equals k. f(1) = 10, ..., f(k) = 9 * 9 * 8 * ... (9 - k + 2) [The first factor is 9 because a number cannot start with 0].", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 2", + "expected_output": "91", + "explanation": "The answer should be the total numbers in the range of 0 ≤ x < 100, excluding 11,22,33,44,55,66,77,88,99" + }, + { + "example_num": 2, + "expected_input": "n = 0", + "expected_output": "1", + "explanation": "" + } + ], + "solution": "/**\n * @param {number} n\n * @return {number}\n */\nconst countNumbersWithUniqueDigits = function(n) {\n if(n === 0) return 1\n let res = 10\n let uniqueDigits = 9, avail = 9\n while(n > 1 && avail) {\n uniqueDigits = uniqueDigits * avail\n res += uniqueDigits\n avail--\n n--\n }\n \n return res\n};\n\n// another\n\n/**\n * @param {number} n\n * @return {number}\n */\nconst countNumbersWithUniqueDigits = function(n) {\n if (n === 0) return 1;\n let res = 10;\n let tmp = 9;\n let remainDigitNum = 9;\n while (n - 1 > 0 && remainDigitNum > 0) {\n tmp = tmp * remainDigitNum;\n res += tmp;\n n -= 1;\n remainDigitNum -= 1;\n }\n\n return res;\n};\n\n\n// another\n\n/**\n * @param {number} n\n * @return {number}\n */\nconst countNumbersWithUniqueDigits = function(n) {\n const limit = 10 ** n\n let res = 1\n let m = 1\n if(n === 0) return 1\n while(10**m <= limit) {\n res += 9 * helper(9, m - 1)\n m++\n }\n \n return res\n \n function helper(m, n) {\n return n === 0 ? 1 : helper(m, n - 1) * (m - n + 1)\n }\n};\n\n// another\n\n/**\n * @param {number} n\n * @return {number}\n */\nconst countNumbersWithUniqueDigits = function(n) {\n if(n === 0) return 1\n let res = 10\n let tmp = 9, digits = 9\n while(n > 1 && digits > 0) {\n tmp *= digits \n res += tmp\n n--\n digits--\n }\n \n return res\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720b8b", + "questionid": 192, + "title": "Max Sum of Rectangle No Larger Than K", + "slug": "max-sum-of-rectangle-no-larger-than-k", + "description": "Given an m x n matrix matrix and an integer k, return the max sum of a rectangle in the matrix such that its sum is no larger than k. It is guaranteed that there will be a rectangle with a sum no larger than k. ", + "category": [ + "Array", + "Binary Search", + "Dynamic Programming", + "Matrix", + "Ordered Set" + ], + "complexity": "Hard", + "successrate": 40.1, + "totalsubmissions": 195205, + "totalaccepted": 78325, + "likes": 1887, + "dislikes": 107, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "matrix = [[1,0,1],[0,-2,3]], k = 2", + "expected_output": "2", + "explanation": "Because the sum of the blue rectangle [[0, 1], [-2, 3]] is 2, and 2 is the max number no larger than k (k = 2)." + }, + { + "example_num": 2, + "expected_input": "matrix = [[2,2,-1]], k = 3", + "expected_output": "3", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[][]} matrix\n * @param {number} k\n * @return {number}\n */\nconst maxSumSubmatrix = function(matrix, k) {\n const row = matrix.length,\n col = matrix[0].length\n let result = -Infinity\n for (let i = 0; i < col; i++) {\n let rowSum = Array(row).fill(0)\n for (let j = i; j < col; j++) {\n let sum = 0,\n max = -Infinity\n for (let r = 0; r < row; r++) {\n rowSum[r] += matrix[r][j]\n if (sum < 0) sum = 0\n sum += rowSum[r]\n max = Math.max(max, sum)\n }\n if (max <= k) result = Math.max(result, max)\n else {\n max = -Infinity\n for (let m = 0; m < row; m++) {\n sum = 0\n for (let n = m; n < row; n++) {\n sum += rowSum[n]\n if (sum <= k) max = Math.max(max, sum)\n }\n }\n result = Math.max(result, max)\n }\n if (result === k) return k\n }\n }\n return result\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720b4e", + "questionid": 131, + "title": "Kth Largest Element in an Array", + "slug": "kth-largest-element-in-an-array", + "description": "Given an integer array nums and an integer k, return the kth largest element in the array. Note that it is the kth largest element in the sorted order, not the kth distinct element. ", + "category": [ + "Array", + "Divide and Conquer", + "Sorting", + "Heap (Priority Queue)", + "Quickselect" + ], + "complexity": "Medium", + "successrate": 63.3, + "totalsubmissions": 2021242, + "totalaccepted": 1279643, + "likes": 8917, + "dislikes": 480, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [3,2,1,5,6,4], k = 2", + "expected_output": "5", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "nums = [3,2,3,1,2,4,5,5,6], k = 4", + "expected_output": "4", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} nums\n * @param {number} k\n * @return {number}\n */\nconst findKthLargest = function(nums, k) {\n if (!nums || k > nums.length) return 0;\n\n const larger = [];\n const smaller = [];\n const pivot = nums[parseInt(nums.length / 2)];\n let pivotCount = 0;\n\n for (let i = 0; i < nums.length; i++) {\n const ele = nums[i];\n\n if (ele > pivot) larger.push(ele);\n else if (ele === pivot) pivotCount++;\n else smaller.push(ele);\n }\n\n if (larger.length >= k) return findKthLargest(larger, k);\n else if (k - larger.length - pivotCount <= 0) return pivot;\n else return findKthLargest(smaller, k - larger.length - pivotCount);\n};\n\n// another\n\n/**\n * @param {number[]} nums\n * @param {number} k\n * @return {number}\n */\nconst findKthLargest = function(nums, k) {\n return quickselect(nums, 0, nums.length - 1, k)\n};\nfunction quickselect(arr, lo, hi, k) {\n let pivtIdx = Math.floor(Math.random() * (hi - lo + 1)) + lo\n let pivtVal = arr[pivtIdx]\n ;[arr[hi], arr[pivtIdx]] = [arr[pivtIdx], arr[hi]]\n let i = lo\n let j = hi - 1\n\n while (i <= j) {\n if (arr[i] <= pivtVal) {\n i++\n } else {\n ;[arr[j], arr[i]] = [arr[i], arr[j]]\n j--\n }\n }\n\n ;[arr[i], arr[hi]] = [arr[hi], arr[i]]\n\n pivtIdx = i\n\n if (pivtIdx === arr.length - k) return arr[pivtIdx]\n if (pivtIdx < arr.length - k) return quickselect(arr, pivtIdx + 1, hi, k)\n return quickselect(arr, lo, pivtIdx - 1, k)\n}\n\n// another\n\n/**\n * @param {number[]} nums\n * @param {number} k\n * @return {number}\n */\nconst findKthLargest = function(nums, k) {\n const n = nums.length\n let l = 0, r = n - 1, t = n - k\n while(l < r) {\n const mid = partition(nums, l, r)\n if(mid < t) {\n l = mid + 1\n } else {\n if(mid === t) break\n else r = mid - 1\n }\n }\n return nums[t]\n};\n\nfunction partition(arr, left, right) {\n let pivot = arr[right]\n let l = left, r = right - 1, j = left\n for(let i = left; i < right; i++) {\n if(arr[i] <= pivot) {\n swap(arr, i, j)\n j++\n }\n }\n swap(arr, j, right)\n return j\n}\n\nfunction swap(arr, i, j) {\n const tmp = arr[i]\n arr[i] = arr[j]\n arr[j] = tmp\n}\n\n// another\n\n/**\n * @param {number[]} nums\n * @param {number} k\n * @return {number}\n */\nconst findKthLargest = function(nums, k) {\n const n = nums.length\n let l = 0, r = n - 1, t = n - k\n while(l < r) {\n const idx = partition(nums, l, r)\n if (idx === t) return nums[t]\n if (idx < t) l = idx + 1\n else r = idx - 1\n }\n return nums[l]\n};\n\nfunction partition(arr, l, r) {\n let tmp = l, pivot = arr[l]\n while(l < r) {\n while(l < r && arr[r] >= pivot) r--\n while(l < r && arr[l] <= pivot) l++\n swap(arr, l, r)\n }\n swap(arr, l, tmp)\n return l\n}\n\nfunction swap(arr, i, j) {\n const tmp = arr[i]\n arr[i] = arr[j]\n arr[j] = tmp\n}\n\n\n" + }, + { + "_id": "66f925ddfdfb8e1665720b51", + "questionid": 134, + "title": "Contains Duplicate III", + "slug": "contains-duplicate-iii", + "description": "Given an integer array nums and two integers k and t, return true if there are two distinct indices i and j in the array such that abs(nums[i] - nums[j]) <= t and abs(i - j) <= k. ", + "category": [ + "Array", + "Sliding Window", + "Sorting", + "Bucket Sort", + "Ordered Set" + ], + "complexity": "Medium", + "successrate": 21.7, + "totalsubmissions": 920049, + "totalaccepted": 199738, + "likes": 2264, + "dislikes": 2212, + "hints": "Time complexity O(n logk) - This will give an indication that sorting is involved for k elements. Use already existing state to evaluate next state - Like, a set of k sorted numbers are only needed to be tracked. When we are processing the next number in array, then we can utilize the existing sorted state and it is not necessary to sort next overlapping set of k numbers again.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,2,3,1], indexDiff = 3, valueDiff = 0", + "expected_output": "true", + "explanation": "We can choose (i, j) = (0, 3).\nWe satisfy the three conditions:\ni != j --> 0 != 3\nabs(i - j) <= indexDiff --> abs(0 - 3) <= 3\nabs(nums[i] - nums[j]) <= valueDiff --> abs(1 - 1) <= 0" + }, + { + "example_num": 2, + "expected_input": "nums = [1,5,9,1,5,9], indexDiff = 2, valueDiff = 3", + "expected_output": "false", + "explanation": "After trying all the possible pairs (i, j), we cannot satisfy the three conditions, so we return false." + } + ], + "solution": "/**\n * @param {number[]} nums\n * @param {number} k\n * @param {number} t\n * @return {boolean}\n */\nconst containsNearbyAlmostDuplicate = function(nums, k, t) {\n if (k < 1 || t < 0) {\n return false\n }\n const array = new Map()\n const num = 10 ** 10\n for (let i = 0, iL = nums.length; i < iL; ++i) {\n const noNegative = nums[i] + num\n const factor = Math.floor(noNegative / (t + 1))\n if (\n array.has(factor) ||\n (array.has(factor - 1) && noNegative - array.get(factor - 1) <= t) ||\n (array.has(factor + 1) && array.get(factor + 1) - noNegative <= t)\n ) {\n return true\n }\n if (array.size >= k) {\n array.delete(Math.floor((nums[i - k] + num) / (t + 1)))\n }\n array.set(factor, noNegative)\n }\n return false\n}\n\n// another\n\n/**\n * @param {number[]} nums\n * @param {number} k\n * @param {number} t\n * @return {boolean}\n */\nconst containsNearbyAlmostDuplicate = function(nums, k, t) {\n const map = nums\n .map((val, idx) => ({ val, idx }))\n .sort((a, b) => a.val - b.val)\n let l = 0\n let r = 1\n while (r < map.length) {\n const diff = Math.abs(map[r].val - map[l].val)\n const range = Math.abs(map[r].idx - map[l].idx)\n if (diff <= t && range <= k) return true\n else if (diff > t) l++\n else if (range > k) r++\n if (l === r) r++\n }\n return false\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720b57", + "questionid": 140, + "title": "Kth Smallest Element in a BST", + "slug": "kth-smallest-element-in-a-bst", + "description": "Given the root of a binary search tree, and an integer k, return the kth smallest value (1-indexed) of all the values of the nodes in the tree. ", + "category": [ + "Tree", + "Depth-First Search", + "Binary Search Tree", + "Binary Tree" + ], + "complexity": "Medium", + "successrate": 66.6, + "totalsubmissions": 1100066, + "totalaccepted": 732943, + "likes": 6137, + "dislikes": 123, + "hints": "Try to utilize the property of a BST. Try in-order traversal. (Credits to @chan13) What if you could modify the BST node's structure? The optimal runtime complexity is O(height of BST).", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [3,1,4,null,2], k = 1", + "expected_output": "1", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "root = [5,3,6,2,4,null,null,1], k = 3", + "expected_output": "3", + "explanation": "" + } + ], + "solution": "/**\n * Definition for a binary tree node.\n * function TreeNode(val, left, right) {\n * this.val = (val===undefined ? 0 : val)\n * this.left = (left===undefined ? null : left)\n * this.right = (right===undefined ? null : right)\n * }\n */\n/**\n * @param {TreeNode} root\n * @param {number} k\n * @return {number}\n */\nconst kthSmallest = function (root, k) {\n const st = []\n while (root !== null) {\n st.push(root)\n root = root.left\n }\n while (k !== 0) {\n const n = st.pop()\n k--\n if (k === 0) return n.val\n let right = n.right\n while (right !== null) {\n st.push(right)\n right = right.left\n }\n }\n return -1\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720b58", + "questionid": 141, + "title": "Power of Two", + "slug": "power-of-two", + "description": "Given an integer n, return true if it is a power of two. Otherwise, return false. An integer n is a power of two, if there exists an integer x such that n == 2x. ", + "category": [ + "Math", + "Bit Manipulation", + "Recursion" + ], + "complexity": "Easy", + "successrate": 44.9, + "totalsubmissions": 1354147, + "totalaccepted": 608583, + "likes": 3100, + "dislikes": 288, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 1", + "expected_output": "true\nExplanation: 20 = 1", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "n = 16", + "expected_output": "true\nExplanation: 24 = 16", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "n = 3", + "expected_output": "false", + "explanation": "" + } + ], + "solution": "/**\n * @param {number} n\n * @return {boolean}\n */\nconst isPowerOfTwo = function(n) {\n let tmp = 0\n let idx = 0\n while(tmp <= n) {\n if((tmp = Math.pow(2, idx)) === n) {\n return true\n } else {\n idx += 1\n }\n }\n return false\n};\n\n// another\n\n/**\n * @param {number} n\n * @return {boolean}\n */\nconst isPowerOfTwo = function(n) {\n return Math.log2(n)%1 === 0\n};\n\n// another\n\n/**\n * @param {number} n\n * @return {boolean}\n */\nconst isPowerOfTwo = n => n < 1 ? false : Number.MAX_VALUE % n === 0\n\n// another\n\n/**\n * @param {number} n\n * @return {boolean}\n */\nconst isPowerOfTwo = x => x > 0 ? !(x & (x - 1)) : false;\n\n" + }, + { + "_id": "66f925ddfdfb8e1665720b5c", + "questionid": 145, + "title": "Product of Array Except Self", + "slug": "product-of-array-except-self", + "description": "Given an integer array nums, return an array answer such that answer[i] is equal to the product of all the elements of nums except nums[i]. The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer. You must write an algorithm that runs in\u00a0O(n)\u00a0time and without using the division operation. ", + "category": [ + "Array", + "Prefix Sum" + ], + "complexity": "Medium", + "successrate": 63.9, + "totalsubmissions": 1754180, + "totalaccepted": 1120129, + "likes": 11850, + "dislikes": 724, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,2,3,4]", + "expected_output": "[24,12,8,6]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "nums = [-1,1,0,-3,3]", + "expected_output": "[0,0,9,0,0]", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} nums\n * @return {number[]}\n */\nconst productExceptSelf = function(nums) {\n const zeroIdx = new Set();\n const p = nums.reduce((ac, el, idx) => {\n if (el === 0) {\n zeroIdx.add(idx);\n return ac;\n } else {\n return ac * el;\n }\n }, 1);\n const res = [];\n for (let i = 0; i < nums.length; i++) {\n if (zeroIdx.size > 1) {\n res.push(0);\n } else if (zeroIdx.size === 1) {\n res.push(i === [...zeroIdx.values()][0] ? p : 0);\n } else {\n res.push(p / nums[i]);\n }\n }\n return res;\n};\n\n" + }, + { + "_id": "66f925ddfdfb8e1665720b62", + "questionid": 151, + "title": "Single Number III", + "slug": "single-number-iii", + "description": "Given an integer array nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once. You can return the answer in any order. You must write an\u00a0algorithm that runs in linear runtime complexity and uses\u00a0only constant extra space. ", + "category": [ + "Array", + "Bit Manipulation" + ], + "complexity": "Medium", + "successrate": 67.1, + "totalsubmissions": 372615, + "totalaccepted": 250144, + "likes": 3806, + "dislikes": 182, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,2,1,3,2,5]", + "expected_output": "[3,5]\nExplanation: [5, 3] is also a valid answer.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "nums = [-1,0]", + "expected_output": "[-1,0]", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "nums = [0,1]", + "expected_output": "[1,0]", + "explanation": "" + } + ], + "solution": null + }, + { + "_id": "66f925ddfdfb8e1665720b64", + "questionid": 153, + "title": "Ugly Number II", + "slug": "ugly-number-ii", + "description": "An ugly number is a positive integer whose prime factors are limited to 2, 3, and 5. Given an integer n, return the nth ugly number. ", + "category": [ + "Hash Table", + "Math", + "Dynamic Programming", + "Heap (Priority Queue)" + ], + "complexity": "Medium", + "successrate": 45.2, + "totalsubmissions": 563935, + "totalaccepted": 254942, + "likes": 3941, + "dislikes": 210, + "hints": "The naive approach is to call isUgly for every number until you reach the nth one. Most numbers are not ugly. Try to focus your effort on generating only the ugly ones. An ugly number must be multiplied by either 2, 3, or 5 from a smaller ugly number. The key is how to maintain the order of the ugly numbers. Try a similar approach of merging from three sorted lists: L1, L2, and L3. Assume you have Uk, the kth ugly number. Then Uk+1 must be Min(L1 * 2, L2 * 3, L3 * 5).", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 10", + "expected_output": "12", + "explanation": "[1, 2, 3, 4, 5, 6, 8, 9, 10, 12] is the sequence of the first 10 ugly numbers." + }, + { + "example_num": 2, + "expected_input": "n = 1", + "expected_output": "1", + "explanation": "1 has no prime factors, therefore all of its prime factors are limited to 2, 3, and 5." + } + ], + "solution": "/**\n * @param {number} n\n * @return {number}\n */\nconst nthUglyNumber = function (n) {\n if (n <= 0) return false\n if (n === 1) return true\n let t2 = 0,\n t3 = 0,\n t5 = 0\n const k = Array(n).fill(1)\n k[0] = 1\n for (let i = 1; i < n; i++) {\n k[i] = Math.min(k[t2] * 2, k[t3] * 3, k[t5] * 5)\n if (k[i] == k[t2] * 2) t2++\n if (k[i] == k[t3] * 3) t3++\n if (k[i] == k[t5] * 5) t5++\n }\n return k[n - 1]\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720b67", + "questionid": 156, + "title": "First Bad Version", + "slug": "first-bad-version", + "description": "You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad. Suppose you have n versions [1, 2, ..., n] and you want to find out the first bad one, which causes all the following ones to be bad. You are given an API bool isBadVersion(version) which returns whether version is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API. ", + "category": [ + "Binary Search", + "Interactive" + ], + "complexity": "Easy", + "successrate": 41.5, + "totalsubmissions": 2305289, + "totalaccepted": 956971, + "likes": 4654, + "dislikes": 1743, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 5, bad = 4", + "expected_output": "4", + "explanation": "call isBadVersion(3) -> false\ncall isBadVersion(5) -> true\ncall isBadVersion(4) -> true\nThen 4 is the first bad version." + }, + { + "example_num": 2, + "expected_input": "n = 1, bad = 1", + "expected_output": "1", + "explanation": "" + } + ], + "solution": "/**\n * Definition for isBadVersion()\n * \n * @param {integer} version number\n * @return {boolean} whether the version is bad\n * isBadVersion = function(version) {\n * ...\n * };\n */\n\n/**\n * @param {function} isBadVersion()\n * @return {function}\n */\nconst solution = function(isBadVersion) {\n /**\n * @param {integer} n Total versions\n * @return {integer} The first bad version\n */\n return function(n) {\n let left = 1;\n let right = n;\n while (left < right) {\n let mid = left + Math.floor( (right - left) / 2 );\n if (isBadVersion(mid)) {\n right = mid;\n } else {\n left = mid + 1;\n }\n }\n return left;\n };\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720b6e", + "questionid": 163, + "title": "Remove Invalid Parentheses", + "slug": "remove-invalid-parentheses", + "description": "Given a string s that contains parentheses and letters, remove the minimum number of invalid parentheses to make the input string valid. Return all the possible results. You may return the answer in any order. ", + "category": [ + "String", + "Backtracking", + "Breadth-First Search" + ], + "complexity": "Hard", + "successrate": 46.8, + "totalsubmissions": 735686, + "totalaccepted": 344520, + "likes": 4569, + "dislikes": 233, + "hints": "Since we don't know which of the brackets can possibly be removed, we try out all the options! We can use recursion to try out all possibilities for the given expression. For each of the brackets, we have 2 options:\r\n\r\n\n We keep the bracket and add it to the expression that we are building on the fly during recursion.\n OR, we can discard the bracket and move on. The one thing all these valid expressions have in common is that they will all be of the same length i.e. as compared to the original expression, all of these expressions will have the same number of characters removed. \r\n\r\nCan we somehow find the number of misplaced parentheses and use it in our solution? For every left parenthesis, we should have a corresponding right parenthesis. We can make use of two counters which keep track of misplaced left and right parenthesis and in one iteration we can find out these two values. \r\n\r\n\r\n0 1 2 3 4 5 6 7\r\n( ) ) ) ( ( ( ) \r\ni = 0, left = 1, right = 0\r\ni = 1, left = 0, right = 0\r\ni = 2, left = 0, right = 1\r\ni = 3, left = 0, right = 2\r\ni = 4, left = 1, right = 2\r\ni = 5, left = 2, right = 2\r\ni = 6, left = 3, right = 2\r\ni = 7, left = 2, right = 2\r\n\r\n\r\nWe have 2 misplaced left and 2 misplaced right parentheses. We found out that the exact number of left and right parenthesis that has to be removed to get a valid expression. So, e.g. in a 1000 parentheses string, if there are 2 misplaced left and 2 misplaced right parentheses, after we are done discarding 2 left and 2 right parentheses, we will have only one option per remaining character in the expression i.e. to consider them. We can't discard them.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "()())()"", + "expected_output": "["(())()","()()()"]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "s = "(a)())()"", + "expected_output": "["(a())()","(a)()()"]", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "s = ")("", + "expected_output": "[""]", + "explanation": "" + } + ], + "solution": "/**\n * @param {string} s\n * @return {string[]}\n */\nconst removeInvalidParentheses = function(s) {\n const res = []\n helper(s, 0, 0, ['(', ')'])\n return res\n\n function helper(str, lastI, lastJ, pair) {\n let openNum = 0, closeNum = 0\n for(let i = lastI; i < str.length; i++) {\n if(str[i] === pair[0]) openNum++\n if(str[i] === pair[1]) closeNum++\n if(closeNum > openNum) {\n for(let j = lastJ; j <= i; j++) {\n if(str[j] === pair[1] && (j === lastJ || str[j - 1] !== pair[1])) {\n helper(str.slice(0, j) + str.slice(j + 1), i, j, pair)\n }\n }\n return\n }\n }\n let rev = str.split('').reverse().join('')\n if(pair[0] === '(') {\n helper(rev, 0, 0, [')', '('])\n } else {\n res.push(rev)\n }\n }\n};\n\n// another\n\n/**\n * @param {string} s\n * @return {string[]}\n */\nconst removeInvalidParentheses = function(s) {\n const ans = [];\n remove(s, ans, 0, 0, [\"(\", \")\"]);\n return ans;\n};\n\nfunction remove(s, ans, last_i, last_j, par) {\n for (let stack = 0, i = last_i; i < s.length; i++) {\n if (s.charAt(i) === par[0]) stack++;\n if (s.charAt(i) === par[1]) stack--;\n if (stack >= 0) continue;\n for (let j = last_j; j <= i; j++) {\n if (\n s.charAt(j) === par[1] &&\n (j === last_j || s.charAt(j - 1) != par[1])\n ) {\n remove(s.slice(0, j) + s.slice(j + 1), ans, i, j, par);\n }\n }\n return;\n }\n const reversed = s\n .split(\"\")\n .reverse()\n .join(\"\");\n if (par[0] === \"(\") {\n remove(reversed, ans, 0, 0, [\")\", \"(\"]);\n } else {\n ans.push(reversed);\n }\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720b74", + "questionid": 169, + "title": "Maximum Product of Word Lengths", + "slug": "maximum-product-of-word-lengths", + "description": "Given a string array words, return the maximum value of length(word[i]) * length(word[j]) where the two words do not share common letters. If no such two words exist, return 0. ", + "category": [ + "Array", + "String", + "Bit Manipulation" + ], + "complexity": "Medium", + "successrate": 56.6, + "totalsubmissions": 251492, + "totalaccepted": 142365, + "likes": 1700, + "dislikes": 94, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "words = ["abcw","baz","foo","bar","xtfn","abcdef"]", + "expected_output": "16", + "explanation": "The two words can be "abcw", "xtfn"." + }, + { + "example_num": 2, + "expected_input": "words = ["a","ab","abc","d","cd","bcd","abcd"]", + "expected_output": "4", + "explanation": "The two words can be "ab", "cd"." + }, + { + "example_num": 3, + "expected_input": "words = ["a","aa","aaa","aaaa"]", + "expected_output": "0", + "explanation": "No such pair of words." + } + ], + "solution": "/**\n * @param {string[]} words\n * @return {number}\n */\nconst maxProduct = function(words) {\n if (words == null || words.length === 0) return 0;\n let len = words.length;\n let value = [];\n for (let i = 0; i < len; i++) {\n let tmp = words[i];\n value[i] = 0;\n for (let j = 0; j < tmp.length; j++) {\n value[i] |= 1 << (tmp.charAt(j).charCodeAt(0) - \"a\".charCodeAt(0));\n }\n }\n let maxProductNum = 0;\n for (let i = 0; i < len; i++)\n for (let j = i + 1; j < len; j++) {\n if (\n (value[i] & value[j]) === 0 &&\n words[i].length * words[j].length > maxProductNum\n )\n maxProductNum = words[i].length * words[j].length;\n }\n return maxProductNum;\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720b80", + "questionid": 181, + "title": "Palindrome Pairs", + "slug": "palindrome-pairs", + "description": "Given a list of unique words, return all the pairs of the\u00a0distinct indices (i, j) in the given list, so that the concatenation of the two words\u00a0words[i] + words[j] is a palindrome. ", + "category": [ + "Array", + "Hash Table", + "String", + "Trie" + ], + "complexity": "Hard", + "successrate": 35.9, + "totalsubmissions": 409115, + "totalaccepted": 146725, + "likes": 2618, + "dislikes": 244, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "words = ["abcd","dcba","lls","s","sssll"]", + "expected_output": "[[0,1],[1,0],[3,2],[2,4]]", + "explanation": "The palindromes are ["abcddcba","dcbaabcd","slls","llssssll"]" + }, + { + "example_num": 2, + "expected_input": "words = ["bat","tab","cat"]", + "expected_output": "[[0,1],[1,0]]", + "explanation": "The palindromes are ["battab","tabbat"]" + }, + { + "example_num": 3, + "expected_input": "words = ["a",""]", + "expected_output": "[[0,1],[1,0]]", + "explanation": "The palindromes are ["a","a"]" + } + ], + "solution": "/**\n\nGiven a list of unique words, find all pairs of distinct indices (i, j) in the given list,\nso that the concatenation of the two words, i.e. words[i] + words[j] is a palindrome.\n\nExample 1:\n\nInput: [\"abcd\",\"dcba\",\"lls\",\"s\",\"sssll\"]\nOutput: [[0,1],[1,0],[3,2],[2,4]] \nExplanation: The palindromes are [\"dcbaabcd\",\"abcddcba\",\"slls\",\"llssssll\"]\nExample 2:\n\nInput: [\"bat\",\"tab\",\"cat\"]\nOutput: [[0,1],[1,0]] \nExplanation: The palindromes are [\"battab\",\"tabbat\"]\n\n*/\n\n/**\n * @param {string[]} words\n * @return {number[][]}\n */\nconst palindromePairs = function(words) {\n const root = new Trie();\n const pairs = [];\n words.forEach((word, index) => addWord(word, index, root));\n words.forEach((word, index) => searchWord(word, index, root, pairs));\n return pairs;\n};\n\nconst addWord = (word, wordIndex, root) => { \n const length = word.length;\n let curr = root;\n for (let i = length - 1; i >= 0; i--) {\n let char = word.charAt(i);\n if (!curr.children[char]) curr.children[char] = new Trie();\n if (isPalindrome(0, i, word)) curr.words.push(wordIndex);\n curr = curr.children[char];\n }\n curr.wordIndex = wordIndex;\n curr.words.push(wordIndex);\n}\n\nconst searchWord = (word, wordIndex, root, pairs) => {\n const length = word.length;\n let curr = root;\n for (let i = 0; i < length; i++) {\n let char = word.charAt(i);\n if (curr.wordIndex >= 0 && curr.wordIndex !== wordIndex && isPalindrome(i, length - 1, word)) {\n pairs.push([wordIndex, curr.wordIndex]);\n }\n curr = curr.children[char];\n if (!curr) return;\n }\n \n curr.words.forEach((suffix) => {\n if (suffix !== wordIndex) pairs.push([wordIndex, suffix]);\n })\n}\n\nconst isPalindrome = (left, right, word) => {\n while (left < right) {\n if (word.charAt(left++) !== word.charAt(right--)) return false;\n }\n return true;\n}\n\nclass Trie {\n constructor() {\n this.wordIndex = -1;\n this.children = {};\n this.words = [];\n }\n}\n\n// another\n\nconst reverseStr = s => {\n let str = ''\n for (let i = 0; i < s.length; i++) {\n str = s[i] + str\n }\n return str\n}\nconst isPalindrome = str => {\n for (let i = 0; i < str.length / 2; i++) {\n if (str[i] !== str[str.length - 1 - i]) return false\n }\n return true\n}\n/**\n * @param {string[]} words\n * @return {number[][]}\n */\nconst palindromePairs = function(words) {\n const map = new Map()\n words.forEach((word, idx) => map.set(word, idx))\n const result = []\n if (map.has('')) {\n const idx = map.get('')\n words.forEach((word, i) => {\n if (i !== idx && isPalindrome(word)) {\n result.push([idx, map.get(word)])\n result.push([map.get(word), idx])\n }\n })\n }\n map.delete('')\n words.forEach((word, idx) => {\n for (let i = 0; i < word.length; i++) {\n const left = word.slice(0, i)\n const right = word.slice(i)\n if (isPalindrome(left)) {\n const reversedRight = reverseStr(right)\n if (map.has(reversedRight) && map.get(reversedRight) !== idx) {\n result.push([map.get(reversedRight), idx])\n }\n }\n if (isPalindrome(right)) {\n const reversedLeft = reverseStr(left)\n if (map.has(reversedLeft) && map.get(reversedLeft) !== idx) {\n result.push([idx, map.get(reversedLeft)])\n }\n }\n }\n })\n return result\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720b82", + "questionid": 183, + "title": "Counting Bits", + "slug": "counting-bits", + "description": "Given an integer n, return an array ans of length n + 1 such that for each i (0 <= i <= n), ans[i] is the number of 1's in the binary representation of i. ", + "category": [ + "Dynamic Programming", + "Bit Manipulation" + ], + "complexity": "Easy", + "successrate": 74.2, + "totalsubmissions": 759000, + "totalaccepted": 563251, + "likes": 6774, + "dislikes": 317, + "hints": "You should make use of what you have produced already. Divide the numbers in ranges like [2-3], [4-7], [8-15] and so on. And try to generate new range from previous. Or does the odd/even status of the number help you in calculating the number of 1s?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 2", + "expected_output": "[0,1,1]", + "explanation": "0 --> 0\n1 --> 1\n2 --> 10" + }, + { + "example_num": 2, + "expected_input": "n = 5", + "expected_output": "[0,1,1,2,1,2]", + "explanation": "0 --> 0\n1 --> 1\n2 --> 10\n3 --> 11\n4 --> 100\n5 --> 101" + } + ], + "solution": "/**\n * @param {number} num\n * @return {number[]}\n */\nconst countBits = function (num) {\n const f = new Array(num + 1).fill(0)\n for (let i = 1; i <= num; i++) f[i] = f[i >> 1] + (i & 1)\n return f\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720b83", + "questionid": 184, + "title": "Power of Four", + "slug": "power-of-four", + "description": "Given an integer n, return true if it is a power of four. Otherwise, return false. An integer n is a power of four, if there exists an integer x such that n == 4x. ", + "category": [ + "Math", + "Bit Manipulation", + "Recursion" + ], + "complexity": "Easy", + "successrate": 43.9, + "totalsubmissions": 663170, + "totalaccepted": 291168, + "likes": 1445, + "dislikes": 285, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 16", + "expected_output": "true", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "n = 5", + "expected_output": "false", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "n = 1", + "expected_output": "true", + "explanation": "" + } + ], + "solution": "/**\n * @param {number} num\n * @return {boolean}\n */\nconst isPowerOfFour = function(num) {\n if (num === 1) { return true; }\n let f = 4;\n while (f <= num) {\n if (f === num) {\n return true;\n }\n f *= 4;\n }\n return false;\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720b85", + "questionid": 186, + "title": "Reverse String", + "slug": "reverse-string", + "description": "Write a function that reverses a string. The input string is given as an array of characters s. You must do this by modifying the input array in-place with O(1) extra memory. ", + "category": [ + "Two Pointers", + "String", + "Recursion" + ], + "complexity": "Easy", + "successrate": 74.7, + "totalsubmissions": 2078623, + "totalaccepted": 1553675, + "likes": 4831, + "dislikes": 937, + "hints": "The entire logic for reversing a string is based on using the opposite directional two-pointer approach!", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = [\"h\",\"e\",\"l\",\"l\",\"o\"]", + "expected_output": "[\"o\",\"l\",\"l\",\"e\",\"h\"]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "s = [\"H\",\"a\",\"n\",\"n\",\"a\",\"h\"]", + "expected_output": "[\"h\",\"a\",\"n\",\"n\",\"a\",\"H\"]", + "explanation": "" + } + ], + "solution": "/**\n * @param {character[]} s\n * @return {void} Do not return anything, modify s in-place instead.\n */\nconst reverseString = function(s) {\n s.reverse()\n};\n\n// another\n\n/**\n * @param {character[]} s\n * @return {void} Do not return anything, modify s in-place instead.\n */\nconst reverseString = function(s) {\n\tfor(let i = 0; i < s.length / 2; i++){\n\t\t[ s[i] , s[s.length - 1 - i] ] = [ s[s.length - 1 - i] , s[i] ];\n\t}\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720b86", + "questionid": 187, + "title": "Reverse Vowels of a String", + "slug": "reverse-vowels-of-a-string", + "description": "Given a string s, reverse only all the vowels in the string and return it. The vowels are 'a', 'e', 'i', 'o', and 'u', and they can appear in both cases. ", + "category": [ + "Two Pointers", + "String" + ], + "complexity": "Easy", + "successrate": 46.9, + "totalsubmissions": 737331, + "totalaccepted": 345831, + "likes": 1560, + "dislikes": 1823, + "hints": "", + "deleted": false, + "examples": [], + "solution": "/**\n * @param {string} s\n * @return {string}\n */\nconst reverseVowels = function(s) {\n if(s == null || s === '') return ''\n const arr = s.split('')\n let p = 0\n const len = s.length\n let e = s.length - 1\n const v = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']\n while(p < e) {\n while(v.indexOf(arr[p]) === -1 && p < e) p++\n while(v.indexOf(arr[e]) === -1 && p < e) e--\n const tmp = arr[p]\n arr[p] = arr[e]\n arr[e] = tmp \n p++\n e--\n }\n return arr.join('')\n};\n\n\n// another\n\nconst reverseVowels = function(s) {\n let vowels = s.match(/[aeiou]/gi)\n let k = 0\n if (vowels) {\n vowels = vowels.reverse``\n } else {\n return s\n }\n return s.replace(/[aeiou]/gi, () => vowels[k++])\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720b87", + "questionid": 188, + "title": "Top K Frequent Elements", + "slug": "top-k-frequent-elements", + "description": "Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order. ", + "category": [ + "Array", + "Hash Table", + "Divide and Conquer", + "Sorting", + "Heap (Priority Queue)", + "Bucket Sort", + "Counting", + "Quickselect" + ], + "complexity": "Medium", + "successrate": 65.1, + "totalsubmissions": 1418616, + "totalaccepted": 923599, + "likes": 8858, + "dislikes": 360, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,1,1,2,2,3], k = 2", + "expected_output": "[1,2]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "nums = [1], k = 1", + "expected_output": "[1]", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} nums\n * @param {number} k\n * @return {number[]}\n */\nconst topKFrequent = function(nums, k) {\n const hash = {}\n for(let i = 0; i < nums.length; i++) {\n if(hash.hasOwnProperty(nums[i])) hash[nums[i]]++\n else hash[nums[i]] = 1\n }\n const res = new Array()\n const keys = Object.keys(hash)\n \n const bucket = new Array(nums.length)\n \n for(let k of keys) {\n let freq = hash[k]\n if(bucket[freq] == null) {\n bucket[freq] = []\n }\n bucket[freq].push(k)\n }\n \n for(let i = bucket.length - 1; i >= 0 && res.length < k; i--) {\n if(bucket[i] != null) {\n res.push(...bucket[i])\n }\n }\n \n return res\n};\n\n// another\n\n/**\n * @param {number[]} nums\n * @param {number} k\n * @return {number[]}\n */\nconst topKFrequent = function(nums, k) {\n const hash = {}\n for(let n of nums) {\n if(hash[n] == null) hash[n] = 0\n hash[n]++\n }\n const entries = Object.entries(hash)\n let min = Infinity, max = -Infinity\n const reverse = {}\n for(let [k, freq] of entries) {\n if(freq < min) min = freq\n if(freq > max) max = freq\n if(reverse[freq] == null) reverse[freq] = []\n reverse[freq].push(k)\n }\n const n = max - min + 1\n const arr = Array(n)\n let res = []\n let limit = max\n while(limit) {\n if(reverse[limit]) res.push(...reverse[limit])\n limit--\n if(res.length >= k) break\n }\n res.splice(k)\n return res\n};\n\n// another\n\n\n/**\n * @param {number[]} nums\n * @param {number} k\n * @return {number[]}\n */\n const topKFrequent = function(nums, k) {\n const n = nums.length\n const freq = Array(n + 1).fill(null)\n const hash = {}\n for(let e of nums) {\n if(hash[e] == null) hash[e] = 0\n hash[e]++\n }\n for(let k in hash) {\n if(hash.hasOwnProperty(k)) {\n const v = hash[k]\n if(freq[v] == null) freq[v] = []\n freq[v].push(k)\n }\n }\n const res = []\n for(let i = n; i >= 0; i--) {\n if(freq[i] != null) res.push(...freq[i])\n if(res.length >= k) break\n }\n if(res.length > k) res.splice(k)\n return res\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720b4c", + "questionid": 129, + "title": "House Robber II", + "slug": "house-robber-ii", + "description": "You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed. All houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, adjacent houses have a security system connected, and\u00a0it will automatically contact the police if two adjacent houses were broken into on the same night. Given an integer array nums representing the amount of money of each house, return the maximum amount of money you can rob tonight without alerting the police. ", + "category": [ + "Array", + "Dynamic Programming" + ], + "complexity": "Medium", + "successrate": 39.8, + "totalsubmissions": 960606, + "totalaccepted": 382370, + "likes": 5261, + "dislikes": 91, + "hints": "Since House[1] and House[n] are adjacent, they cannot be robbed together. Therefore, the problem becomes to rob either House[1]-House[n-1] or House[2]-House[n], depending on which choice offers more money. Now the problem has degenerated to the House Robber, which is already been solved.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [2,3,2]", + "expected_output": "3", + "explanation": "You cannot rob house 1 (money = 2) and then rob house 3 (money = 2), because they are adjacent houses." + }, + { + "example_num": 2, + "expected_input": "nums = [1,2,3,1]", + "expected_output": "4", + "explanation": "Rob house 1 (money = 1) and then rob house 3 (money = 3).\nTotal amount you can rob = 1 + 3 = 4." + }, + { + "example_num": 3, + "expected_input": "nums = [1,2,3]", + "expected_output": "3", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} nums\n * @return {number}\n */\nconst rob = function(nums) {\n if(nums.length === 0) return 0\n if(nums.length < 3) return Math.max(...nums)\n \n const startFromFirst = [0,nums[0]]\n const startFromSecond = [0,0]\n \n for(let i = 2; i <= nums.length; i++) {\n startFromFirst[i] = Math.max(startFromFirst[i - 1], startFromFirst[i - 2] + nums[i - 1])\n startFromSecond[i] = Math.max(startFromSecond[i - 1], startFromSecond[i - 2] + nums[i - 1])\n }\n \n return Math.max(startFromFirst[nums.length - 1], startFromSecond[nums.length])\n \n};\n\n// another\n\n/**\n * @param {number[]} nums\n * @return {number}\n */\nconst rob = function(nums) {\n if(nums.length === 1) return nums[0]\n return Math.max(helper(0, nums.length - 2), helper(1, nums.length - 1))\n\n function helper(l, r) {\n let inc = 0, exc = 0\n for(let i = l; i <= r; i++) {\n const pi = inc, pe = exc\n inc = exc + nums[i]\n exc = Math.max(pi, pe)\n }\n return Math.max(inc, exc)\n }\n};\n\n// another\n\n/**\n * @param {number[]} nums\n * @return {number}\n */\nconst rob = function(nums) {\n const n = nums.length\n nums = nums.concat(nums)\n let res = 0\n for(let i = 0; i < n; i++) {\n let tmp = nums[i]\n let pp = 0\n let p = 0\n for(let j = i; j < n + i - 1; j++) {\n tmp = Math.max(tmp, pp + nums[j], p);\n [pp, p] = [p, tmp]\n }\n res = Math.max(res, tmp)\n }\n \n return res\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720b53", + "questionid": 136, + "title": "Count Complete Tree Nodes", + "slug": "count-complete-tree-nodes", + "description": "Given the root of a complete binary tree, return the number of the nodes in the tree. According to Wikipedia, every level, except possibly the last, is completely filled in a complete binary tree, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h. Design an algorithm that runs in less than\u00a0O(n)\u00a0time complexity. ", + "category": [ + "Binary Search", + "Tree", + "Depth-First Search", + "Binary Tree" + ], + "complexity": "Medium", + "successrate": 55.1, + "totalsubmissions": 719342, + "totalaccepted": 396136, + "likes": 4722, + "dislikes": 312, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [1,2,3,4,5,6]", + "expected_output": "6", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "root = []", + "expected_output": "0", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "root = [1]", + "expected_output": "1", + "explanation": "" + } + ], + "solution": "/**\n * Definition for a binary tree node.\n * function TreeNode(val) {\n * this.val = val;\n * this.left = this.right = null;\n * }\n */\n/**\n * @param {TreeNode} root\n * @return {number}\n */\nconst countNodes = function(root) {\n if (root == null) return 0;\n const payload = { depth: 0, numOfLast: 0, total: 0 };\n traverse([root], 0, payload);\n return payload.total;\n};\n\nfunction traverse(row, depth, obj) {\n const next = [];\n for (let i = 0; i < row.length; i++) {\n if (row[i].left) next.push(row[i].left);\n if (row[i].right) next.push(row[i].right);\n }\n if (Math.pow(2, depth + 1) !== next.length) {\n obj.total = Math.pow(2, depth + 1) - 1 + next.length;\n return;\n }\n if (next.length) traverse(next, depth + 1, obj);\n}\n\n// another\n\n/**\n * @param {TreeNode} root\n * @return {number}\n */\nconst countNodes = function(root) {\n if (!root) {\n return 0;\n }\n\n return 1 + countNodes(root.left) + countNodes(root.right);\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720b56", + "questionid": 139, + "title": "Majority Element II", + "slug": "majority-element-ii", + "description": "Given an integer array of size n, find all elements that appear more than n/3 times. ", + "category": [ + "Array", + "Hash Table", + "Sorting", + "Counting" + ], + "complexity": "Medium", + "successrate": 42.2, + "totalsubmissions": 667653, + "totalaccepted": 282018, + "likes": 4680, + "dislikes": 277, + "hints": "How many majority elements could it possibly have?\r\n\r\nDo you have a better hint? Suggest it!", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [3,2,3]", + "expected_output": "[3]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "nums = [1]", + "expected_output": "[1]", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "nums = [1,2]", + "expected_output": "[1,2]", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} nums\n * @return {number[]}\n */\nconst majorityElement = function(nums) {\n let candidate1 = 0, candidate2 = 0, cnt1 = 0, cnt2 = 0\n for(const e of nums) {\n if(e === candidate1) {\n cnt1++\n } else if(e === candidate2) {\n cnt2++\n } else if(cnt1 === 0) {\n candidate1 = e\n cnt1++\n } else if(cnt2 === 0) {\n candidate2 = e\n cnt2++\n } else {\n cnt1--\n cnt2--\n }\n }\n \n const n = nums.length\n let c1 = 0, c2 = 0\n for(const e of nums) {\n if(e === candidate1) c1++\n if(e === candidate2) c2++\n }\n const k = Math.floor(n / 3)\n const res = []\n if(c1 > k) res.push(candidate1)\n if(c2 > k) res.push(candidate2)\n if(res[0] === res[1]) res.pop()\n return res\n};\n\n// another\n\n/**\n * @param {number[]} nums\n * @return {number[]}\n */\nconst majorityElement = function(nums) {\n const res = []\n const hash = {}\n const len = nums.length\n const limit = Math.floor(len / 3)\n nums.forEach(el => {\n if(hash.hasOwnProperty(''+el)) {\n hash[el] += 1\n } else {\n hash[el] = 1\n }\n })\n Object.keys(hash).forEach(el => {\n if(hash[el] > limit) res.push(+el)\n })\n \n return res\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720b65", + "questionid": 154, + "title": "Missing Number", + "slug": "missing-number", + "description": "Given an array nums containing n distinct numbers in the range [0, n], return the only number in the range that is missing from the array. ", + "category": [ + "Array", + "Hash Table", + "Math", + "Bit Manipulation", + "Sorting" + ], + "complexity": "Easy", + "successrate": 59.3, + "totalsubmissions": 1649957, + "totalaccepted": 977912, + "likes": 5317, + "dislikes": 2830, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [3,0,1]", + "expected_output": "2", + "explanation": "n = 3 since there are 3 numbers, so all numbers are in the range [0,3]. 2 is the missing number in the range since it does not appear in nums." + }, + { + "example_num": 2, + "expected_input": "nums = [0,1]", + "expected_output": "2", + "explanation": "n = 2 since there are 2 numbers, so all numbers are in the range [0,2]. 2 is the missing number in the range since it does not appear in nums." + }, + { + "example_num": 3, + "expected_input": "nums = [9,6,4,2,3,5,7,0,1]", + "expected_output": "8", + "explanation": "n = 9 since there are 9 numbers, so all numbers are in the range [0,9]. 8 is the missing number in the range since it does not appear in nums." + } + ], + "solution": "/**\n * @param {number[]} nums\n * @return {number}\n */\nconst missingNumber = function(nums) {\n const n = nums.length\n let xor = 0 ^ nums[0]\n for(let i = 1; i < n; i++) xor = xor ^ i ^ nums[i]\n return xor ^ n\n};\n\n// another\n\n/**\n * @param {number[]} nums\n * @return {number}\n */\nconst missingNumber = function(nums) {\n const len = nums.length;\n return (len * (len + 1)) / 2 - sum(nums);\n};\n\nfunction sum(arr) {\n return arr.reduce((ac, el) => ac + el, 0);\n}\n\n// another\n/**\n * @param {number[]} nums\n * @return {number}\n */\nvar missingNumber = function(nums) {\n const n = nums.length\n const sum = nums.reduce((ac, e) => ac + e, 0)\n const target = (n + 1) * n / 2\n return target - sum\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720b66", + "questionid": 155, + "title": "Integer to English Words", + "slug": "integer-to-english-words", + "description": "Convert a non-negative integer num to its English words representation. ", + "category": [ + "Math", + "String", + "Recursion" + ], + "complexity": "Hard", + "successrate": 29.6, + "totalsubmissions": 1008214, + "totalaccepted": 298067, + "likes": 2025, + "dislikes": 4942, + "hints": "Did you see a pattern in dividing the number into chunk of words? For example, 123 and 123000. Group the number by thousands (3 digits). You can write a helper function that takes a number less than 1000 and convert just that chunk to words. There are many edge cases. What are some good test cases? Does your code work with input such as 0? Or 1000010? (middle chunk is zero and should not be printed out)", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "num = 123", + "expected_output": ""One Hundred Twenty Three"", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "num = 12345", + "expected_output": ""Twelve Thousand Three Hundred Forty Five"", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "num = 1234567", + "expected_output": ""One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"", + "explanation": "" + } + ], + "solution": "/**\n * @param {number} num\n * @return {string}\n */\nconst numberToWords = function(num) {\n if (num === 0) return \"Zero\";\n if (num <= 20) return translations.get(num);\n const result = [];\n\n for (let [value, translation] of translations) {\n const times = Math.floor(num / value);\n if (times === 0) continue;\n num -= times * value;\n if (times === 1 && value >= 100) {\n result.push(\"One\", translation);\n continue;\n }\n if (times === 1) {\n result.push(translation);\n continue;\n }\n result.push(numberToWords(times), translation);\n }\n return result.join(\" \");\n};\n\nconst translations = new Map([\n [1000000000, \"Billion\"],\n [1000000, \"Million\"],\n [1000, \"Thousand\"],\n [100, \"Hundred\"],\n [90, \"Ninety\"],\n [80, \"Eighty\"],\n [70, \"Seventy\"],\n [60, \"Sixty\"],\n [50, \"Fifty\"],\n [40, \"Forty\"],\n [30, \"Thirty\"],\n [20, \"Twenty\"],\n [19, \"Nineteen\"],\n [18, \"Eighteen\"],\n [17, \"Seventeen\"],\n [16, \"Sixteen\"],\n [15, \"Fifteen\"],\n [14, \"Fourteen\"],\n [13, \"Thirteen\"],\n [12, \"Twelve\"],\n [11, \"Eleven\"],\n [10, \"Ten\"],\n [9, \"Nine\"],\n [8, \"Eight\"],\n [7, \"Seven\"],\n [6, \"Six\"],\n [5, \"Five\"],\n [4, \"Four\"],\n [3, \"Three\"],\n [2, \"Two\"],\n [1, \"One\"]\n]);\n" + }, + { + "_id": "66f925ddfdfb8e1665720b6f", + "questionid": 164, + "title": "Minimum Height Trees", + "slug": "minimum-height-trees", + "description": "A tree is an undirected graph in which any two vertices are connected by\u00a0exactly\u00a0one path. In other words, any connected graph without simple cycles is a tree. Given a tree of n nodes\u00a0labelled from 0 to n - 1, and an array of\u00a0n - 1\u00a0edges where edges[i] = [ai, bi] indicates that there is an undirected edge between the two nodes\u00a0ai and\u00a0bi in the tree,\u00a0you can choose any node of the tree as the root. When you select a node x as the root, the result tree has height h. Among all possible rooted trees, those with minimum height (i.e. min(h))\u00a0 are called minimum height trees (MHTs). Return a list of all MHTs' root labels.\u00a0You can return the answer in any order. The height of a rooted tree is the number of edges on the longest downward path between the root and a leaf. ", + "category": [ + "Depth-First Search", + "Breadth-First Search", + "Graph", + "Topological Sort" + ], + "complexity": "Medium", + "successrate": 38.1, + "totalsubmissions": 507493, + "totalaccepted": 193328, + "likes": 5092, + "dislikes": 210, + "hints": "How many MHTs can a graph have at most?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 4, edges = [[1,0],[1,2],[1,3]]", + "expected_output": "[1]", + "explanation": "As shown, the height of the tree is 1 when the root is the node with label 1 which is the only MHT." + }, + { + "example_num": 2, + "expected_input": "n = 6, edges = [[3,0],[3,1],[3,2],[3,4],[5,4]]", + "expected_output": "[3,4]", + "explanation": "" + } + ], + "solution": "/**\n * @param {number} n\n * @param {number[][]} edges\n * @return {number[]}\n */\nconst findMinHeightTrees = function (n, edges) {\n const graph = {}\n\n for(const [u, v] of edges) {\n if(graph[u] == null) graph[u] = new Set()\n if(graph[v] == null) graph[v] = new Set()\n graph[u].add(v)\n graph[v].add(u)\n }\n\n let q = []\n for(let i = 0; i < n; i++) {\n if(graph[i].size === 1) q.push(i)\n }\n\n while(n > 2) {\n const size = q.length, nxt = []\n n -= size\n for(let i = 0; i < size; i++) {\n const cur = q[i]\n for(const e of (graph[cur] || [])) {\n graph[e].delete(cur)\n if(graph[e].size === 1) nxt.push(e)\n }\n }\n\n q = nxt\n }\n\n return q\n}\n\n// another\n\n/**\n * @param {number} n\n * @param {number[][]} edges\n * @return {number[]}\n */\n const findMinHeightTrees = function(n, edges) {\n if(n === 1) return [0]\n const res = [], graph = {}\n for(const [u, v] of edges) {\n if(graph[u] == null) graph[u] = new Set()\n if(graph[v] == null) graph[v] = new Set()\n graph[u].add(v)\n graph[v].add(u)\n }\n\n let leaves = []\n Object.keys(graph).forEach(k => {\n if(graph[k].size === 1) leaves.push(+k)\n })\n while(n > 2) {\n const newLeaves = []\n const size = leaves.length\n for (let i = 0; i < size; i++) {\n const cur = leaves.pop()\n for (const next of graph[cur]) {\n graph[next].delete(cur)\n if(graph[next].size === 1) newLeaves.push(next)\n }\n }\n n -= size\n leaves = newLeaves\n }\n \n return leaves\n};\n\n// another\n\n/**\n * @param {number} n\n * @param {number[][]} edges\n * @return {number[]}\n */\nconst findMinHeightTrees = function(n, edges) {\n if (n === 1) {\n return [0];\n }\n const adj = [];\n for (let i = 0; i < n; i++) {\n adj.push([]);\n }\n for (let edge of edges) {\n adj[edge[0]].push(edge[1]);\n adj[edge[1]].push(edge[0]);\n }\n let leaves = [];\n for (let i = 0; i < n; i++) {\n if (adj[i].length === 1) {\n leaves.push(i);\n }\n }\n\n while (n > 2) {\n n -= leaves.length;\n let newLeaves = [];\n for (let i of leaves) {\n let j = adj[i].shift();\n let idx = adj[j].indexOf(i);\n adj[j].splice(idx, 1);\n if (adj[j].length === 1) newLeaves.push(j);\n }\n leaves = newLeaves;\n }\n\n return leaves;\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720b73", + "questionid": 168, + "title": "Remove Duplicate Letters", + "slug": "remove-duplicate-letters", + "description": "Given a string s, remove duplicate letters so that every letter appears once and only once. You must make sure your result is the smallest in lexicographical order among all possible results. ", + "category": [ + "String", + "Stack", + "Greedy", + "Monotonic Stack" + ], + "complexity": "Medium", + "successrate": 43.8, + "totalsubmissions": 432267, + "totalaccepted": 189513, + "likes": 5181, + "dislikes": 340, + "hints": "Greedily try to add one missing character. How to check if adding some character will not cause problems ? Use bit-masks to check whether you will be able to complete the sub-sequence if you add the character at some index i.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "bcabc"", + "expected_output": ""abc"", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "s = "cbacdcbc"", + "expected_output": ""acdb"", + "explanation": "" + } + ], + "solution": "/**\n * @param {string} s\n * @return {string}\n */\nconst removeDuplicateLetters = function(s) {\n const last = {}\n for (let i = 0; i < s.length; i++) last[s.charAt(i)] = i\n const added = {}\n const stack = []\n for (let i = 0; i < s.length; i++) {\n const char = s.charAt(i)\n if (added[char]) continue\n while (stack.length && char < stack[0] && last[stack[0]] > i) {\n added[stack[0]] = false\n stack.shift()\n }\n stack.unshift(char)\n added[char] = true\n }\n return stack.reverse().join('')\n}\n\n// another\n\n\n/**\n * @param {string} s\n * @return {string}\n */\nconst removeDuplicateLetters = function(s) {\n const m = new Array(26)\n const a = 'a'.charCodeAt(0)\n for (let i = 0; i < s.length; i++) {\n const k = s.charCodeAt(i) - a\n m[k] = m[k] ? m[k] + 1 : 1\n }\n const aChNo = []\n const visited = {}\n for (let i = 0; i < s.length; i++) {\n const k = s.charCodeAt(i) - a\n m[k]--\n if (visited[k]) continue\n while (aChNo.length > 0) {\n const last = aChNo[aChNo.length - 1] - a\n if (last > k && m[last] > 0) {\n visited[last] = 0\n aChNo.pop()\n } else break\n }\n visited[k] = 1\n aChNo.push(k + a)\n }\n return String.fromCharCode(...aChNo)\n}\n\n// another\n\n/**\n * @param {string} s\n * @return {string}\n */\nconst removeDuplicateLetters = function(s) {\n const last = {}\n for (let i = 0; i < s.length; i++) last[s.charAt(i)] = i\n const added = {}\n const stack = []\n for (let i = 0; i < s.length; i++) {\n const char = s.charAt(i)\n if (added[char]) continue\n while (stack.length && char < stack[stack.length - 1] && last[stack[stack.length - 1]] > i) {\n added[stack[stack.length - 1]] = false\n stack.pop()\n }\n stack.push(char)\n added[char] = true\n }\n return stack.join('')\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720b75", + "questionid": 170, + "title": "Bulb Switcher", + "slug": "bulb-switcher", + "description": "There are n bulbs that are initially off. You first turn on all the bulbs, then\u00a0you turn off every second bulb. On the third round, you toggle every third bulb (turning on if it's off or turning off if it's on). For the ith round, you toggle every i bulb. For the nth round, you only toggle the last bulb. Return the number of bulbs that are on after n rounds. ", + "category": [ + "Math", + "Brainteaser" + ], + "complexity": "Medium", + "successrate": 47.2, + "totalsubmissions": 239996, + "totalaccepted": 113307, + "likes": 907, + "dislikes": 1636, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 3", + "expected_output": "1", + "explanation": "At first, the three bulbs are [off, off, off].\nAfter the first round, the three bulbs are [on, on, on].\nAfter the second round, the three bulbs are [on, off, on].\nAfter the third round, the three bulbs are [on, off, off]. \nSo you should return 1 because there is only one bulb is on." + }, + { + "example_num": 2, + "expected_input": "n = 0", + "expected_output": "0", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "n = 1", + "expected_output": "1", + "explanation": "" + } + ], + "solution": "/**\n * @param {number} n\n * @return {number}\n */\nconst bulbSwitch = function(n) {\n return Math.floor(Math.sqrt(n));\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720b7f", + "questionid": 180, + "title": "Self Crossing", + "slug": "self-crossing", + "description": "You are given an array of integers distance. You start at point (0,0) on an X-Y plane and you move distance[0] meters to the north, then distance[1] meters to the west, distance[2] meters to the south, distance[3] meters to the east, and so on. In other words, after each move, your direction changes counter-clockwise. Return true if your path crosses itself, and false if it does not. ", + "category": [ + "Array", + "Math", + "Geometry" + ], + "complexity": "Hard", + "successrate": 29.1, + "totalsubmissions": 94557, + "totalaccepted": 27512, + "likes": 249, + "dislikes": 444, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "distance = [2,1,1,2]", + "expected_output": "true", + "explanation": "The path crosses itself at the point (0, 1)." + }, + { + "example_num": 2, + "expected_input": "distance = [1,2,3,4]", + "expected_output": "false", + "explanation": "The path does not cross itself at any point." + }, + { + "example_num": 3, + "expected_input": "distance = [1,1,1,2,1]", + "expected_output": "true", + "explanation": "The path crosses itself at the point (0, 0)." + } + ], + "solution": "/**\n * @param {number[]} x\n * @return {boolean}\n */\nconst isSelfCrossing = function(x) {\n for (let i = 3, l = x.length; 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])\n return true\n // Case 3: current line crosses the line 6 steps ahead of it\n else if (\n i >= 5 &&\n x[i - 2] >= x[i - 4] &&\n x[i] + x[i - 4] >= x[i - 2] &&\n x[i - 1] <= x[i - 3] &&\n x[i - 1] + x[i - 5] >= x[i - 3]\n )\n return true\n }\n return false\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720b88", + "questionid": 189, + "title": "Intersection of Two Arrays", + "slug": "intersection-of-two-arrays", + "description": "Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must be unique and you may return the result in any order. ", + "category": [ + "Array", + "Hash Table", + "Two Pointers", + "Binary Search", + "Sorting" + ], + "complexity": "Easy", + "successrate": 68.9, + "totalsubmissions": 939599, + "totalaccepted": 647468, + "likes": 2731, + "dislikes": 1878, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums1 = [1,2,2,1], nums2 = [2,2]", + "expected_output": "[2]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "nums1 = [4,9,5], nums2 = [9,4,9,8,4]", + "expected_output": "[9,4]", + "explanation": "[4,9] is also accepted." + } + ], + "solution": "/**\n * @param {number[]} nums1\n * @param {number[]} nums2\n * @return {number[]}\n */\n\nconst intersection = function(nums1, nums2) {\n const obj = {};\n nums1.forEach(i => (obj[i] = true));\n\n return nums2.filter(j => {\n if (obj[j]) {\n delete obj[j];\n return true;\n }\n return false;\n });\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720b50", + "questionid": 133, + "title": "Contains Duplicate II", + "slug": "contains-duplicate-ii", + "description": "Given an integer array nums and an integer k, return true if there are two distinct indices i and j in the array such that nums[i] == nums[j] and abs(i - j) <= k. ", + "category": [ + "Array", + "Hash Table", + "Sliding Window" + ], + "complexity": "Easy", + "successrate": 40.6, + "totalsubmissions": 1107769, + "totalaccepted": 450207, + "likes": 2368, + "dislikes": 1847, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,2,3,1], k = 3", + "expected_output": "true", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "nums = [1,0,1,1], k = 1", + "expected_output": "true", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "nums = [1,2,3,1,2,3], k = 2", + "expected_output": "false", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} nums\n * @param {number} k\n * @return {boolean}\n */\nconst containsNearbyDuplicate = function(nums, k) {\n const map = new Map();\n for (let i = 0; i < nums.length; i++) {\n if (map.has(nums[i])) {\n if (i - map.get(nums[i]) <= k) {\n return true;\n } else {\n map.set(nums[i], i);\n }\n } else {\n map.set(nums[i], i);\n }\n }\n return false;\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720b54", + "questionid": 137, + "title": "Rectangle Area", + "slug": "rectangle-area", + "description": "Given the coordinates of two rectilinear rectangles in a 2D plane, return the total area covered by the two rectangles. The first rectangle is defined by its bottom-left corner (ax1, ay1) and its top-right corner (ax2, ay2). The second rectangle is defined by its bottom-left corner (bx1, by1) and its top-right corner (bx2, by2). ", + "category": [ + "Math", + "Geometry" + ], + "complexity": "Medium", + "successrate": 40.1, + "totalsubmissions": 337644, + "totalaccepted": 135232, + "likes": 745, + "dislikes": 1008, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "ax1 = -3, ay1 = 0, ax2 = 3, ay2 = 4, bx1 = 0, by1 = -1, bx2 = 9, by2 = 2", + "expected_output": "45", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "ax1 = -2, ay1 = -2, ax2 = 2, ay2 = 2, bx1 = -2, by1 = -2, bx2 = 2, by2 = 2", + "expected_output": "16", + "explanation": "" + } + ], + "solution": "/**\n * @param {number} A\n * @param {number} B\n * @param {number} C\n * @param {number} D\n * @param {number} E\n * @param {number} F\n * @param {number} G\n * @param {number} H\n * @return {number}\n */\nconst computeArea = function(A, B, C, D, E, F, G, H) {\n const areaA = (C - A) * (D - B)\n const areaB = (G - E) * (H - F)\n const intersectionArea =\n Math.max(0, Math.min(C, G) - Math.max(A, E)) *\n Math.max(0, Math.min(D, H) - Math.max(B, F))\n return areaA + areaB - intersectionArea\n}\n\n\n// another\n\n\n/**\n * @param {number} A\n * @param {number} B\n * @param {number} C\n * @param {number} D\n * @param {number} E\n * @param {number} F\n * @param {number} G\n * @param {number} H\n * @return {number}\n */\nconst computeArea = function(A, B, C, D, E, F, G, H) {\n const x1 = A,\n x2 = C,\n x3 = E,\n x4 = G\n const y1 = B,\n y2 = D,\n y3 = F,\n y4 = H\n return (\n area(x1, y1, x2, y2) +\n area(x3, y3, x4, y4) -\n delta(x1, x2, x3, x4) * delta(y1, y2, y3, y4)\n )\n}\n\nfunction area(x1, y1, x2, y2) {\n return Math.abs(x1 - x2) * Math.abs(y1 - y2)\n}\n\nfunction delta(v1, v2, v3, v4) {\n if (v1 > v2) {\n let tmp = v1\n v1 = v2\n v2 = tmp\n }\n if (v3 > v4) {\n let tmp = v3\n v3 = v4\n v4 = tmp\n }\n if (v3 >= v2 || v4 <= v1) return 0\n return Math.min(v2, v4) - Math.max(v1, v3)\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720b55", + "questionid": 138, + "title": "Invert Binary Tree", + "slug": "invert-binary-tree", + "description": "Given the root of a binary tree, invert the tree, and return its root. ", + "category": [ + "Tree", + "Depth-First Search", + "Breadth-First Search", + "Binary Tree" + ], + "complexity": "Easy", + "successrate": 71.4, + "totalsubmissions": 1394634, + "totalaccepted": 995662, + "likes": 8061, + "dislikes": 110, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [4,2,7,1,3,6,9]", + "expected_output": "[4,7,2,9,6,3,1]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "root = [2,1,3]", + "expected_output": "[2,3,1]", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "root = []", + "expected_output": "[]", + "explanation": "" + } + ], + "solution": "/**\n * Definition for a binary tree node.\n * function TreeNode(val, left, right) {\n * this.val = (val===undefined ? 0 : val)\n * this.left = (left===undefined ? null : left)\n * this.right = (right===undefined ? null : right)\n * }\n */\n/**\n * @param {TreeNode} root\n * @return {TreeNode}\n */\nconst invertTree = function (root) {\n if (root) {\n ;[root.left, root.right] = [invertTree(root.right), invertTree(root.left)]\n }\n return root\n}\n\n// another\n\n/**\n * Definition for a binary tree node.\n * function TreeNode(val, left, right) {\n * this.val = (val===undefined ? 0 : val)\n * this.left = (left===undefined ? null : left)\n * this.right = (right===undefined ? null : right)\n * }\n */\n/**\n * @param {TreeNode} root\n * @return {TreeNode}\n */\nconst invertTree = function (root) {\n if (!root) return root\n let queue = [root]\n while (queue.length) {\n let node = queue.shift()\n if (node.left) {\n queue.push(node.left)\n }\n if (node.right) {\n queue.push(node.right)\n }\n let left = node.left\n node.left = node.right\n node.right = left\n }\n return root\n}\n\n// anoother\n\n/**\n * Definition for a binary tree node.\n * function TreeNode(val, left, right) {\n * this.val = (val===undefined ? 0 : val)\n * this.left = (left===undefined ? null : left)\n * this.right = (right===undefined ? null : right)\n * }\n */\n/**\n * @param {TreeNode} root\n * @return {TreeNode}\n */\nconst invertTree = function(root) {\n if(root == null) return root\n let tmp = root.left\n root.left = invertTree(root.right)\n root.right = invertTree(tmp)\n return root\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720b5b", + "questionid": 144, + "title": "Delete Node in a Linked List", + "slug": "delete-node-in-a-linked-list", + "description": "Write a function to delete a node in a singly-linked list. You will not be given access to the head of the list, instead you will be given access to the node to be deleted directly. It is guaranteed that the node to be deleted is not a tail node in the list. ", + "category": [ + "Linked List" + ], + "complexity": "Easy", + "successrate": 71.7, + "totalsubmissions": 1093877, + "totalaccepted": 784762, + "likes": 4258, + "dislikes": 11520, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "head = [4,5,1,9], node = 5", + "expected_output": "[4,1,9]\nExplanation: You are given the second node with value 5, the linked list should become 4 -> 1 -> 9 after calling your function.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "head = [4,5,1,9], node = 1", + "expected_output": "[4,5,9]\nExplanation: You are given the third node with value 1, the linked list should become 4 -> 5 -> 9 after calling your function.", + "explanation": "" + } + ], + "solution": "/**\n * Definition for singly-linked list.\n * function ListNode(val) {\n * this.val = val;\n * this.next = null;\n * }\n */\n/**\n * @param {ListNode} node\n * @return {void} Do not return anything, modify node in-place instead.\n */\nconst deleteNode = function(node) {\n if (node.next !== null) {\n node.val = node.next.val;\n node.next = node.next.next;\n }\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720b60", + "questionid": 149, + "title": "Binary Tree Paths", + "slug": "binary-tree-paths", + "description": "Given the root of a binary tree, return all root-to-leaf paths in any order. A leaf is a node with no children. ", + "category": [ + "String", + "Backtracking", + "Tree", + "Depth-First Search", + "Binary Tree" + ], + "complexity": "Easy", + "successrate": 58.5, + "totalsubmissions": 857207, + "totalaccepted": 501173, + "likes": 3949, + "dislikes": 181, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [1,2,3,null,5]", + "expected_output": "["1->2->5","1->3"]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "root = [1]", + "expected_output": "["1"]", + "explanation": "" + } + ], + "solution": "/**\n * Definition for a binary tree node.\n * function TreeNode(val) {\n * this.val = val;\n * this.left = this.right = null;\n * }\n */\n/**\n * @param {TreeNode} root\n * @return {string[]}\n */\nconst binaryTreePaths = function(root) {\n const res = [];\n traverse(root, res, []);\n return res;\n};\n\nfunction traverse(node, res, p) {\n if (node === null) return;\n p.push(node.val);\n if (node.left === null && node.right === null) {\n res.push(p.join(\"->\"));\n }\n if (node.left) {\n traverse(node.left, res, p.slice(0));\n }\n if (node.right) {\n traverse(node.right, res, p.slice(0));\n }\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720b63", + "questionid": 152, + "title": "Ugly Number", + "slug": "ugly-number", + "description": "An ugly number is a positive integer whose prime factors are limited to 2, 3, and 5. Given an integer n, return true if n is an ugly number. ", + "category": [ + "Math" + ], + "complexity": "Easy", + "successrate": 41.8, + "totalsubmissions": 699108, + "totalaccepted": 292500, + "likes": 1376, + "dislikes": 1018, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 6", + "expected_output": "true", + "explanation": "6 = 2 × 3" + }, + { + "example_num": 2, + "expected_input": "n = 1", + "expected_output": "true", + "explanation": "1 has no prime factors, therefore all of its prime factors are limited to 2, 3, and 5." + }, + { + "example_num": 3, + "expected_input": "n = 14", + "expected_output": "false", + "explanation": "14 is not ugly since it includes the prime factor 7." + } + ], + "solution": "/**\n * @param {number} num\n * @return {boolean}\n */\nconst isUgly = function(num) {\n if (num < 1) return false\n while (num >= 2) {\n if (num % 2 === 0) num = num / 2\n else if (num % 3 === 0) num = num / 3\n else if (num % 5 === 0) num = num / 5\n else return false\n }\n return true\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720b68", + "questionid": 157, + "title": "Perfect Squares", + "slug": "perfect-squares", + "description": "Given an integer n, return the least number of perfect square numbers that sum to n. A perfect square is an integer that is the square of an integer; in other words, it is the product of some integer with itself. For example, 1, 4, 9, and 16 are perfect squares while 3 and 11 are not. ", + "category": [ + "Math", + "Dynamic Programming", + "Breadth-First Search" + ], + "complexity": "Medium", + "successrate": 51.8, + "totalsubmissions": 1002301, + "totalaccepted": 519105, + "likes": 6581, + "dislikes": 291, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 12", + "expected_output": "3", + "explanation": "12 = 4 + 4 + 4." + }, + { + "example_num": 2, + "expected_input": "n = 13", + "expected_output": "2", + "explanation": "13 = 4 + 9." + } + ], + "solution": "/**\n * @param {number} n\n * @return {number}\n */\nconst numSquares = function(n) {\n const dp = new Array(n+1).fill(Number.MAX_VALUE)\n dp[0] = 0\n for(let i = 1; i <= n; i++) {\n let min = Number.MAX_VALUE\n let j = 1\n while(i - j*j >= 0) {\n min = Math.min(min, dp[i-j*j] + 1)\n ++j\n }\n dp[i] = min\n }\n return dp[n]\n};\n\n// another\n\n/**\n * @param {number} n\n * @return {number}\n */\nconst numSquares = function (n) {\n if (n <= 0) return 0\n // cntPerfectSquares[i] = the least number of perfect square numbers\n const cntPerfectSquares = [0]\n // While cntPerfectSquares.length <= n, we need to incrementally\n // calculate the next result until we get the result for n.\n while (cntPerfectSquares.length <= n) {\n const m = cntPerfectSquares.length\n let cntSquares = Number.MAX_VALUE\n for (let i = 1; i * i <= m; i++) {\n cntSquares = Math.min(cntSquares, cntPerfectSquares[m - i * i] + 1)\n }\n cntPerfectSquares.push(cntSquares)\n }\n return cntPerfectSquares[n]\n}\n\n// another\n\n/**\n * @param {number} n\n * @return {number}\n */\nconst numSquares = function (n) {\n // Based on Lagrange's Four Square theorem, there\n // are only 4 possible results: 1, 2, 3, 4.\n // If n is a perfect square, return 1.\n if (is_square(n)) {\n return 1\n }\n // The result is 4 if and only if n can be written in the\n // form of 4^k*(8*m + 7). Please refer to\n // Legendre's three-square theorem.\n while ((n & 3) === 0) {\n // n%4 == 0\n n >>= 2\n }\n if ((n & 7) === 7) {\n // n%8 == 7\n return 4\n }\n // Check whether 2 is the result.\n let sqrt_n = Math.sqrt(n) >> 0\n for (let i = 1; i <= sqrt_n; i++) {\n if (is_square(n - i * i)) {\n return 2\n }\n }\n return 3\n function is_square(n) {\n const sqrt_n = Math.sqrt(n) >> 0\n return sqrt_n * sqrt_n == n\n }\n}\n\n" + }, + { + "_id": "66f925ddfdfb8e1665720b69", + "questionid": 158, + "title": "Expression Add Operators", + "slug": "expression-add-operators", + "description": "Given a string num that contains only digits and an integer target, return all possibilities to insert the binary operators '+', '-', and/or '*' between the digits of num so that the resultant expression evaluates to the target value. Note that operands in the returned expressions should not contain leading zeros. ", + "category": [ + "Math", + "String", + "Backtracking" + ], + "complexity": "Hard", + "successrate": 39.2, + "totalsubmissions": 460309, + "totalaccepted": 180213, + "likes": 2475, + "dislikes": 420, + "hints": "Note that a number can contain multiple digits. Since the question asks us to find all of the valid expressions, we need a way to iterate over all of them. (Hint: Recursion!) We can keep track of the expression string and evaluate it at the very end. But that would take a lot of time. Can we keep track of the expression's value as well so as to avoid the evaluation at the very end of recursion? Think carefully about the multiply operator. It has a higher precedence than the addition and subtraction operators. \r\n\r\n 1 + 2 = 3 \r\n1 + 2 - 4 --> 3 - 4 --> -1 \r\n1 + 2 - 4 * 12 --> -1 * 12 --> -12 (WRONG!) \r\n1 + 2 - 4 * 12 --> -1 - (-4) + (-4 * 12) --> 3 + (-48) --> -45 (CORRECT!) We simply need to keep track of the last operand in our expression and reverse it's effect on the expression's value while considering the multiply operator.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "num = "123", target = 6", + "expected_output": "["1*2*3","1+2+3"]", + "explanation": "Both "1*2*3" and "1+2+3" evaluate to 6." + }, + { + "example_num": 2, + "expected_input": "num = "232", target = 8", + "expected_output": "["2*3+2","2+3*2"]", + "explanation": "Both "2*3+2" and "2+3*2" evaluate to 8." + }, + { + "example_num": 3, + "expected_input": "num = "3456237490", target = 9191", + "expected_output": "[]", + "explanation": "There are no expressions that can be created from "3456237490" to evaluate to 9191." + } + ], + "solution": "/**\n * @param {string} num\n * @param {number} target\n * @return {string[]}\n */\nconst addOperators = function(num, target) {\n let res = [];\n let n = num.length;\n function recursive(k, str, add, mul, last) {\n let sum = add + mul * last;\n if (k === n) {\n if (sum === target) {\n res.push(str);\n }\n return;\n }\n let x = num[k] - \"0\";\n if (last !== 0) {\n recursive(k + 1, str + num[k], add, mul, last * 10 + x);\n }\n recursive(k + 1, str + \"*\" + num[k], add, mul * last, x);\n recursive(k + 1, str + \"+\" + num[k], sum, 1, x);\n recursive(k + 1, str + \"-\" + num[k], sum, -1, x);\n }\n if (n) recursive(1, num[0], 0, 1, num[0] - \"0\");\n return res;\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720b6c", + "questionid": 161, + "title": "Word Pattern", + "slug": "word-pattern", + "description": "Given a pattern and a string s, find if s\u00a0follows the same pattern. Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in s. ", + "category": [ + "Hash Table", + "String" + ], + "complexity": "Easy", + "successrate": 40.2, + "totalsubmissions": 886230, + "totalaccepted": 356008, + "likes": 3477, + "dislikes": 402, + "hints": "", + "deleted": false, + "examples": [], + "solution": "/**\n * @param {string} pattern\n * @param {string} str\n * @return {boolean}\n */\nconst wordPattern = function(pattern, str) {\n const pm = {}\n const sm = {}\n const sa = str.trim().split(' ')\n if(pattern.length !== sa.length) return false\n for(let i = 0; i< pattern.length; i++) {\n if(!pm.hasOwnProperty(pattern[i])) {\n pm[pattern[i]] = sa[i]\n }\n if(!sm.hasOwnProperty(sa[i])) {\n sm[sa[i]] = pattern[i]\n }\n\n if( !(pm[pattern[i]] === sa[i] && sm[sa[i]] === pattern[i] ) ) {\n return false \n }\n \n }\n return true\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720b72", + "questionid": 167, + "title": "Count of Smaller Numbers After Self", + "slug": "count-of-smaller-numbers-after-self", + "description": "You are given an integer array nums and you have to return a new counts array. The counts array has the property where counts[i] is the number of smaller elements to the right of nums[i]. ", + "category": [ + "Array", + "Binary Search", + "Divide and Conquer", + "Binary Indexed Tree", + "Segment Tree", + "Merge Sort", + "Ordered Set" + ], + "complexity": "Hard", + "successrate": 42, + "totalsubmissions": 531794, + "totalaccepted": 223619, + "likes": 5393, + "dislikes": 154, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [5,2,6,1]", + "expected_output": "[2,1,1,0]", + "explanation": "To the right of 5 there are 2 smaller elements (2 and 1).\nTo the right of 2 there is only 1 smaller element (1).\nTo the right of 6 there is 1 smaller element (1).\nTo the right of 1 there is 0 smaller element." + }, + { + "example_num": 2, + "expected_input": "nums = [-1]", + "expected_output": "[0]", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "nums = [-1,-1]", + "expected_output": "[0,0]", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} nums\n * @return {number[]}\n */\nconst countSmaller = function(nums) {\n const numsAndIndexes = nums.map((x, i) => [x, i])\n const output = [...new Array(nums.length)].map(_ => 0)\n mergeSort(numsAndIndexes, output)\n return output\n}\n\nfunction mergeSort(arr, output) {\n if (arr.length <= 1) return arr\n const middle = Math.floor(arr.length / 2)\n const left = mergeSort(arr.slice(0, middle), output),\n right = mergeSort(arr.slice(middle), output)\n const sorted = []\n let i = 0,\n j = 0\n while (i < left.length || j < right.length) {\n if (i >= left.length) {\n sorted.push(right[j])\n j++\n } else if (j >= right.length) {\n sorted.push(left[i])\n i++\n } else {\n if (left[i][0] > right[j][0]) {\n sorted.push(left[i])\n output[left[i][1]] += right.length - j\n i++\n } else {\n sorted.push(right[j])\n j++\n }\n }\n }\n\n return sorted\n}\n\n// another\n\nclass Node {\n constructor(v, s) {\n this.val = v\n this.sum = s\n this.left = null\n this.right = null\n this.dup = 1\n }\n}\n/**\n * @param {number[]} nums\n * @return {number[]}\n */\nconst countSmaller = function(nums) {\n const ans = new Array(nums.length).fill(0)\n let root = null\n for (let i = nums.length - 1; i >= 0; i--) {\n root = insert(nums[i], root, ans, i, 0)\n }\n return ans\n}\n\nfunction insert(num, node, ans, i, preSum) {\n if (node == null) {\n node = new Node(num, 0)\n ans[i] = preSum\n } else if (node.val == num) {\n node.dup++\n ans[i] = preSum + node.sum\n } else if (node.val > num) {\n node.sum++\n node.left = insert(num, node.left, ans, i, preSum)\n } else {\n node.right = insert(num, node.right, ans, i, preSum + node.dup + node.sum)\n }\n return node\n}\n\n// another\n\n/**\n * @param {number[]} nums\n * @return {number[]}\n */\nconst countSmaller = function(nums) {\n \n const arr = []\n const n = nums.length\n for(let i = 0; i < n; i++) {\n arr.push([nums[i], i])\n }\n \n const res = Array(n).fill(0)\n cntSmaller(arr, 0, n - 1, res)\n \n return res\n \n function cntSmaller(arr, l, r, res) {\n if(l >= r) return\n \n const mid = ~~((l + r) / 2)\n cntSmaller(arr, l, mid, res)\n cntSmaller(arr, mid + 1, r, res)\n let leftPos = l, rightPos = mid + 1, cnt = 0\n const merged = []\n while(leftPos < mid + 1 && rightPos <= r) {\n if(arr[leftPos][0] > arr[rightPos][0]) {\n cnt++\n merged.push(arr[rightPos])\n rightPos++\n } else {\n res[arr[leftPos][1]] += cnt\n merged.push(arr[leftPos])\n leftPos++\n }\n }\n \n while(leftPos < mid + 1) {\n res[arr[leftPos][1]] += cnt\n merged.push(arr[leftPos])\n leftPos++\n }\n \n while(rightPos <= r) {\n merged.push(arr[rightPos])\n rightPos++\n }\n \n for(let i = l; i <= r; i++) {\n arr[i] = merged[i - l]\n }\n \n }\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720b77", + "questionid": 172, + "title": "Coin Change", + "slug": "coin-change", + "description": "You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money. Return the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1. You may assume that you have an infinite number of each kind of coin. ", + "category": [ + "Array", + "Dynamic Programming", + "Breadth-First Search" + ], + "complexity": "Medium", + "successrate": 40, + "totalsubmissions": 2373497, + "totalaccepted": 950323, + "likes": 10775, + "dislikes": 262, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "coins = [1,2,5], amount = 11", + "expected_output": "3", + "explanation": "11 = 5 + 5 + 1" + }, + { + "example_num": 2, + "expected_input": "coins = [2], amount = 3", + "expected_output": "-1", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "coins = [1], amount = 0", + "expected_output": "0", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} coins\n * @param {number} amount\n * @return {number}\n */\nconst coinChange = function(coins, amount) {\n const n = coins.length\n const dp = Array(amount + 1).fill(Infinity)\n dp[0] = 0\n for(const e of coins) dp[e] = 1\n for(let i = 1; i <= amount; i++) {\n for(const e of coins) {\n if(i > e) dp[i] = Math.min(dp[i], dp[i - e] + 1)\n }\n }\n // console.log(dp)\n return dp[amount] !== Infinity ? dp[amount] : -1\n};\n\n// another\n\n/**\n * @param {number[]} coins\n * @param {number} amount\n * @return {number}\n */\nconst coinChange = function(coins, amount) {\n const dp = new Array(amount + 1).fill(amount + 1)\n dp[0] = 0\n for (let i = 1; i <= amount; i++) {\n for (let coin of coins) {\n if (coin <= i) dp[i] = Math.min(dp[i], dp[i - coin] + 1)\n }\n }\n return dp[amount] === amount + 1 ? -1 : dp[amount]\n}\n\n\n// another\n\n/**\n * @param {number[]} coins\n * @param {number} amount\n * @return {number}\n */\nconst coinChange = function (coins, amount) {\n const n = coins.length\n const dp = Array.from({ length: n }, () =>\n Array(amount + 1).fill(Infinity)\n )\n\n for (let i = 0; i < n; i++) {\n dp[i][0] = 0\n for (let j = 1; j <= amount; j++) {\n if(i > 0) dp[i][j] = dp[i - 1][j]\n if (j >= coins[i]) {\n dp[i][j] = Math.min(dp[i][j], dp[i][j - coins[i]] + 1)\n }\n }\n }\n return dp[n - 1][amount] === Infinity ? -1 : dp[n - 1][amount]\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720b7a", + "questionid": 175, + "title": "Count of Range Sum", + "slug": "count-of-range-sum", + "description": "Given an integer array nums and two integers lower and upper, return the number of range sums that lie in [lower, upper] inclusive. Range sum S(i, j) is defined as the sum of the elements in nums between indices i and j inclusive, where i <= j. ", + "category": [ + "Array", + "Binary Search", + "Divide and Conquer", + "Binary Indexed Tree", + "Segment Tree", + "Merge Sort", + "Ordered Set" + ], + "complexity": "Hard", + "successrate": 36, + "totalsubmissions": 163712, + "totalaccepted": 59005, + "likes": 1502, + "dislikes": 155, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [-2,5,-1], lower = -2, upper = 2", + "expected_output": "3", + "explanation": "The three ranges are: [0,0], [2,2], and [0,2] and their respective sums are: -2, -1, 2." + }, + { + "example_num": 2, + "expected_input": "nums = [0], lower = 0, upper = 0", + "expected_output": "1", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} nums\n * @param {number} lower\n * @param {number} upper\n * @return {number}\n */\nconst countRangeSum = function (nums, lower, upper) {\n if (nums.length === 0) return 0\n const sums = [nums[0]]\n for (let i = 1; i < nums.length; i++) {\n sums[i] = sums[i - 1] + nums[i]\n }\n function merge_sort(A, lo, hi) {\n if (hi - lo === 1) {\n return sums[lo] >= lower && sums[lo] <= upper ? 1 : 0\n }\n const mid = lo + Math.floor((hi - lo) / 2)\n let counter = merge_sort(A, lo, mid) + merge_sort(A, mid, hi)\n let m = mid,\n n = mid\n for (let i = lo; i < mid; i++) {\n while (m !== hi && sums[m] - sums[i] < lower) {\n m++\n }\n while (n !== hi && sums[n] - sums[i] <= upper) {\n n++\n }\n counter += n - m\n }\n const M = A.slice(lo, mid)\n const N = A.slice(mid, hi)\n M.push(Number.MAX_SAFE_INTEGER)\n N.push(Number.MAX_SAFE_INTEGER)\n for (let k = lo, i = 0, j = 0; k < hi; k++) {\n A[k] = M[i] < N[j] ? M[i++] : N[j++]\n }\n return counter\n }\n return merge_sort(sums, 0, nums.length)\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720b7c", + "questionid": 177, + "title": "Patching Array", + "slug": "patching-array", + "description": "Given a sorted integer array nums and an integer n, add/patch elements to the array such that any number in the range [1, n] inclusive can be formed by the sum of some elements in the array. Return the minimum number of patches required. ", + "category": [ + "Array", + "Greedy" + ], + "complexity": "Hard", + "successrate": 39.5, + "totalsubmissions": 141671, + "totalaccepted": 55966, + "likes": 1085, + "dislikes": 113, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,3], n = 6", + "expected_output": "1\nExplanation:\nCombinations of nums are [1], [3], [1,3], which form possible sums of: 1, 3, 4.\nNow if we add/patch 2 to nums, the combinations are: [1], [2], [3], [1,3], [2,3], [1,2,3].\nPossible sums are 1, 2, 3, 4, 5, 6, which now covers the range [1, 6].\nSo we only need 1 patch.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "nums = [1,5,10], n = 20", + "expected_output": "2\nExplanation: The two patches can be [2, 4].", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "nums = [1,2,2], n = 5", + "expected_output": "0", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} nums\n * @param {number} n\n * @return {number}\n */\nconst minPatches = function(nums, n) {\n let sum = 1, res = 0, i = 0\n while(sum <= n) {\n if(i < nums.length && nums[i] <= sum) {\n sum += nums[i]\n i++\n } else {\n res++\n sum *= 2\n }\n }\n\n return res \n};\n\n// another\n\n/**\n * @param {number[]} nums\n * @param {number} n\n * @return {number}\n */\nconst minPatches = function(nums, n) {\n const len = nums.length\n let miss = 1, res = 0, i = 0\n while(miss <= n) {\n if(i < len && nums[i] <= miss) {\n miss += nums[i]\n i++\n } else {\n res++\n miss += miss\n }\n }\n \n return res\n};\n\n// another\n\n/**\n * @param {number[]} nums\n * @param {number} n\n * @return {number}\n */\nconst minPatches = function(nums, n) {\n let answer = 0\n for (let i = 0, next = 1; next <= n; ) {\n if (i >= nums.length || nums[i] > next) {\n answer++\n next *= 2\n } else next += nums[i++]\n }\n return answer\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720b7e", + "questionid": 179, + "title": "Increasing Triplet Subsequence", + "slug": "increasing-triplet-subsequence", + "description": "Given an integer array nums, return true if there exists a triple of indices (i, j, k) such that i < j < k and nums[i] < nums[j] < nums[k]. If no such indices exists, return false. ", + "category": [ + "Array", + "Greedy" + ], + "complexity": "Medium", + "successrate": 41.5, + "totalsubmissions": 642716, + "totalaccepted": 266546, + "likes": 3768, + "dislikes": 208, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,2,3,4,5]", + "expected_output": "true", + "explanation": "Any triplet where i < j < k is valid." + }, + { + "example_num": 2, + "expected_input": "nums = [5,4,3,2,1]", + "expected_output": "false", + "explanation": "No triplet exists." + }, + { + "example_num": 3, + "expected_input": "nums = [2,1,5,0,4,6]", + "expected_output": "true", + "explanation": "The triplet (3, 4, 5) is valid because nums[3] == 0 < nums[4] == 4 < nums[5] == 6." + } + ], + "solution": "/**\n * @param {number[]} nums\n * @return {boolean}\n */\nconst increasingTriplet = function(nums) {\n // start with two largest values, as soon as we find a number bigger than both, while both have been updated, return true.\n let small = Number.MAX_VALUE, big = Number.MAX_VALUE;\n for (let n of nums) {\n if (n <= small) { small = n; } // update small if n is smaller than both\n else if (n <= big) { big = n; } // update big only if greater than small but smaller than big\n else return true; // return if you find a number bigger than both\n }\n return false;\n};\n\n// another\n\n/**\n * @param {number[]} nums\n * @return {boolean}\n */\nconst increasingTriplet = function(nums) {\n const n = nums.length, stk = []\n for(let e of nums) {\n let l = 0, r = stk.length\n while(l < r) {\n const mid = l + Math.floor((r - l) / 2)\n if (e > stk[mid]) l = mid + 1\n else r = mid \n }\n\n stk[l] = e\n if(stk.length > 2) return true\n }\n\n return false\n};\n\n// another\n\n/**\n * @param {number[]} nums\n * @return {boolean}\n */\nconst increasingTriplet = function(nums) {\n let small = Number.MAX_VALUE, big = Number.MAX_VALUE\n \n for(const e of nums) {\n if(e <= small) small = e\n else if(e <= big) big = e\n else return true\n }\n \n return false\n};\n\n" + }, + { + "_id": "66f925ddfdfb8e1665720b8f", + "questionid": 196, + "title": "Wiggle Subsequence", + "slug": "wiggle-subsequence", + "description": "A wiggle sequence is a sequence where the differences between successive numbers strictly alternate between positive and negative. The first difference (if one exists) may be either positive or negative. A sequence with one element and a sequence with two non-equal elements are trivially wiggle sequences. A subsequence is obtained by deleting some elements (possibly zero) from the original sequence, leaving the remaining elements in their original order. Given an integer array nums, return the length of the longest wiggle subsequence of nums. ", + "category": [ + "Array", + "Dynamic Programming", + "Greedy" + ], + "complexity": "Medium", + "successrate": 44.9, + "totalsubmissions": 301689, + "totalaccepted": 135314, + "likes": 2617, + "dislikes": 93, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,7,4,9,2,5]", + "expected_output": "6", + "explanation": "The entire sequence is a wiggle sequence with differences (6, -3, 5, -7, 3)." + }, + { + "example_num": 2, + "expected_input": "nums = [1,17,5,10,13,15,10,5,16,8]", + "expected_output": "7", + "explanation": "There are several subsequences that achieve this length.\nOne is [1, 17, 10, 13, 10, 16, 8] with differences (16, -7, 3, -3, 6, -8)." + }, + { + "example_num": 3, + "expected_input": "nums = [1,2,3,4,5,6,7,8,9]", + "expected_output": "2", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} nums\n * @return {number}\n */\nconst wiggleMaxLength = function(nums) {\n if (nums.length < 2) return nums.length\n let prevdiff = nums[1] - nums[0]\n let count = prevdiff !== 0 ? 2 : 1\n for (let i = 2; i < nums.length; i++) {\n let diff = nums[i] - nums[i - 1]\n if ((diff > 0 && prevdiff <= 0) || (diff < 0 && prevdiff >= 0)) {\n count++\n prevdiff = diff\n }\n }\n return count\n}\n\n// another\n\n/**\n * @param {number[]} nums\n * @return {number}\n */\nconst wiggleMaxLength = function(nums) {\n const len = nums.length\n if (len === 0) return 0\n let up = 1\n let down = 1\n for (let i = 1; i < len; i++) {\n if (nums[i] > nums[i - 1]) {\n up = down + 1\n } else if (nums[i] < nums[i - 1]) {\n down = up + 1\n }\n }\n return Math.max(up, down)\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720b93", + "questionid": 200, + "title": "Mini Parser", + "slug": "mini-parser", + "description": "Given a string s represents the serialization of a nested list, implement a parser to deserialize it and return the deserialized NestedInteger. Each element is either an integer or a list whose elements may also be integers or other lists. ", + "category": [ + "String", + "Stack", + "Depth-First Search" + ], + "complexity": "Medium", + "successrate": 35.8, + "totalsubmissions": 133077, + "totalaccepted": 47667, + "likes": 360, + "dislikes": 1129, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "324"", + "expected_output": "324", + "explanation": "You should return a NestedInteger object which contains a single integer 324." + }, + { + "example_num": 2, + "expected_input": "s = "[123,[456,[789]]]"", + "expected_output": "[123,[456,[789]]]", + "explanation": "Return a NestedInteger object containing a nested list with 2 elements:\n1. An integer containing value 123.\n2. A nested list containing two elements:\n i. An integer containing value 456.\n ii. A nested list with one element:\n a. An integer containing value 789" + } + ], + "solution": "/**\n * // This is the interface that allows for creating nested lists.\n * // You should not implement it, or speculate about its implementation\n * function NestedInteger() {\n *\n * Return true if this NestedInteger holds a single integer, rather than a nested list.\n * @return {boolean}\n * this.isInteger = function() {\n * ...\n * };\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 * @return {integer}\n * this.getInteger = function() {\n * ...\n * };\n *\n * Set this NestedInteger to hold a single integer equal to value.\n * @return {void}\n * this.setInteger = function(value) {\n * ...\n * };\n *\n * Set this NestedInteger to hold a nested list and adds a nested integer elem to it.\n * @return {void}\n * this.add = function(elem) {\n * ...\n * };\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 * @return {NestedInteger[]}\n * this.getList = function() {\n * ...\n * };\n * };\n */\n/**\n * @param {string} s\n * @return {NestedInteger}\n */\nconst deserialize = function(s) {\n const recursion = s => {\n const re = new NestedInteger()\n if (!s || s.length === 0) {\n return re\n }\n if (s.charAt(0) !== '[') {\n re.setInteger(parseInt(s, 10))\n } else if (s.length > 2) {\n let start = 1\n let cnt = 0\n for (let i = 1; i < s.length; i++) {\n const char = s.charAt(i)\n if (cnt === 0 && (char === ',' || i === s.length - 1)) {\n re.add(recursion(s.substring(start, i)))\n start = i + 1\n } else if (char === '[') {\n cnt++\n } else if (char === ']') {\n cnt--\n }\n }\n }\n return re\n }\n return recursion(s)\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720b98", + "questionid": 205, + "title": "Is Subsequence", + "slug": "is-subsequence", + "description": "Given two strings s and t, return true if s is a subsequence of t, or false otherwise. A subsequence of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., \"ace\" is a subsequence of \"abcde\" while \"aec\" is not). ", + "category": [ + "Two Pointers", + "String", + "Dynamic Programming" + ], + "complexity": "Easy", + "successrate": 51, + "totalsubmissions": 891195, + "totalaccepted": 454214, + "likes": 4635, + "dislikes": 285, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = \"abc\", t = \"ahbgdc\"", + "expected_output": "true", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "s = \"axc\", t = \"ahbgdc\"", + "expected_output": "false", + "explanation": "" + } + ], + "solution": "/**\n * @param {string} s\n * @param {string} t\n * @return {boolean}\n */\nconst isSubsequence = function(s, t) {\n const sl = s.length\n const tl = t.length\n if(sl > tl) return false\n if(sl === 0) return true\n let si = 0\n for(let i = 0; i < tl && si < sl; i++) {\n if(s[si] === t[i]) si++\n }\n return si === sl\n};\n\n// another\n\n/**\n * @param {string} s\n * @param {string} t\n * @return {boolean}\n */\nconst isSubsequence = function(s, t) {\n let ti = 0\n let tmp = 0\n for (let i = 0; i < s.length; i++) {\n if ((tmp = chk(t, ti, s.charAt(i))) === -1) {\n return false\n } else {\n ti = tmp + 1\n }\n }\n\n return true\n}\n\nfunction chk(str, start, target) {\n let idx = start\n for (let i = start; i < str.length; i++) {\n if (str.charAt(i) === target) {\n return i\n }\n }\n return -1\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720b9b", + "questionid": 208, + "title": "Binary Watch", + "slug": "binary-watch", + "description": "A binary watch has 4 LEDs on the top which represent the hours (0-11), and the 6 LEDs on the bottom represent the minutes (0-59). Each LED represents a zero or one, with the least significant bit on the right. Given an integer turnedOn which represents the number of LEDs that are currently on, return all possible times the watch could represent. You may return the answer in any order. The hour must not contain a leading zero. The minute must be consist of two digits and may contain a leading zero. ", + "category": [ + "Backtracking", + "Bit Manipulation" + ], + "complexity": "Easy", + "successrate": 50.4, + "totalsubmissions": 215786, + "totalaccepted": 108789, + "likes": 935, + "dislikes": 1753, + "hints": "Simplify by seeking for solutions that involve comparing bit counts. Consider calculating all possible times for comparison purposes.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "turnedOn = 1", + "expected_output": "[\"0:01\",\"0:02\",\"0:04\",\"0:08\",\"0:16\",\"0:32\",\"1:00\",\"2:00\",\"4:00\",\"8:00\"]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "turnedOn = 9", + "expected_output": "[]", + "explanation": "" + } + ], + "solution": "/**\n * @param {number} num\n * @return {string[]}\n */\nconst readBinaryWatch = function(num) {\n const output = []\n for (let h = 0; h < 12; h++) {\n for (let m = 0; m < 60; m++) {\n const ones = Number(h * 64 + m)\n .toString(2)\n .split('')\n .filter(d => d === '1').length\n if (ones === num) output.push(m < 10 ? `${h}:0${m}` : `${h}:${m}`)\n }\n }\n return output\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720ba1", + "questionid": 214, + "title": "Longest Palindrome", + "slug": "longest-palindrome", + "description": "Given a string s which consists of lowercase or uppercase letters, return the length of the longest palindrome\u00a0that can be built with those letters. Letters are case sensitive, for example,\u00a0\"Aa\" is not considered a palindrome here. ", + "category": [ + "Hash Table", + "String", + "Greedy" + ], + "complexity": "Easy", + "successrate": 53.5, + "totalsubmissions": 496778, + "totalaccepted": 265829, + "likes": 2591, + "dislikes": 153, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "abccccdd"", + "expected_output": "7", + "explanation": "One longest palindrome that can be built is "dccaccd", whose length is 7." + }, + { + "example_num": 2, + "expected_input": "s = "a"", + "expected_output": "1", + "explanation": "The longest palindrome that can be built is "a", whose length is 1." + } + ], + "solution": "/**\n * @param {string} s\n * @return {number}\n */\nconst longestPalindrome = function (s) {\n const set = new Set()\n let counter = 0\n for (let i = 0; i < s.length; i++) {\n const currentChar = s[i]\n if (set.has(currentChar)) {\n counter++\n set.delete(currentChar)\n } else {\n set.add(currentChar)\n }\n }\n counter *= 2\n if (set.size > 0) counter++\n return counter\n}\n\n// another\n\n/**\n * @param {string} s\n * @return {number}\n */\nconst longestPalindrome = function(s) {\n const hash = {};\n let c;\n for (let i = 0; i < s.length; i++) {\n c = s.charAt(i);\n if (hash.hasOwnProperty(c)) {\n hash[c] += 1;\n } else {\n hash[c] = 1;\n }\n }\n let res = 0;\n let val;\n for (let k in hash) {\n if (hash.hasOwnProperty(k)) {\n val = hash[k];\n res += Math.floor(val / 2) * 2;\n if (res % 2 === 0 && val % 2 === 1) {\n res += 1;\n }\n }\n }\n\n return res;\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720ba6", + "questionid": 219, + "title": "Partition Equal Subset Sum", + "slug": "partition-equal-subset-sum", + "description": "Given a non-empty array nums containing only positive integers, find if the array can be partitioned into two subsets such that the sum of elements in both subsets is equal. ", + "category": [ + "Array", + "Dynamic Programming" + ], + "complexity": "Medium", + "successrate": 46.4, + "totalsubmissions": 925930, + "totalaccepted": 429311, + "likes": 7247, + "dislikes": 115, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,5,11,5]", + "expected_output": "true", + "explanation": "The array can be partitioned as [1, 5, 5] and [11]." + }, + { + "example_num": 2, + "expected_input": "nums = [1,2,3,5]", + "expected_output": "false", + "explanation": "The array cannot be partitioned into equal sum subsets." + } + ], + "solution": "/**\n * @param {number[]} nums\n * @return {boolean}\n */\nconst canPartition = function(nums) {\n const n = nums.length\n const sum = nums.reduce((ac, e) => ac + e, 0)\n if(sum % 2 === 1) return false\n const target = sum / 2\n const dp = Array.from({length: n + 1}, () => Array(target + 101).fill(0))\n dp[0][0] = 1\n \n for(let i = 1; i <= n ; i++) {\n const e = nums[i - 1]\n for(let s = 0; s < target + 101; s++) {\n dp[i][s] = dp[i - 1][s]\n if(s >= e) dp[i][s] += dp[i - 1][s - e]\n }\n }\n return dp[n][target] > 0\n};\n\n// another\n\n/**\n * @param {number[]} nums\n * @return {boolean}\n */\nconst canPartition = function(nums) {\n let sum = 0\n for(let num of nums) {\n sum += num\n }\n \n if(sum & 1 === 1) {\n return false\n }\n \n sum /= 2\n let n = nums.length\n const dp = Array.from(new Array(n+1), () => [])\n for(let i = 0; i < dp.length; i++) {\n dp[i] = new Array(sum+1).fill(false)\n }\n dp[0][0] = true\n for(let i = 1; i < n + 1; i++) {\n dp[i][0] = true\n }\n for(let j = 1; j < sum + 1; j++) {\n dp[0][j] = false\n }\n for(let i = 1; i < n + 1; i++) {\n for(let j = 1; j < sum + 1; j++) {\n if(j >= nums[i - 1]) {\n dp[i][j] = (dp[i -1][j] || dp[i - 1][j - nums[i - 1]])\n }\n }\n }\n return dp[n][sum]\n};\n\n// another\n\n/**\n * @param {number[]} nums\n * @return {boolean}\n */\nconst canPartition = function(nums) {\n if (nums.length < 2) return false\n\n const total = nums.reduce((a, c) => a + c)\n if (total % 2 !== 0) return false\n\n nums.sort((a, b) => b - a)\n const target = total / 2\n\n if (nums[0] > target) return false\n return findCombination(nums, target, 0)\n}\n\nfunction findCombination(nums, target, start) {\n if (target === 0) {\n return true\n } else {\n for (let i = start; i < nums.length; i++) {\n if (nums[i] <= target) {\n if (findCombination(nums, target - nums[i], i + 1)) {\n return true\n }\n }\n }\n return false\n }\n}\n\n// another\n\n/**\n * @param {number[]} nums\n * @return {boolean}\n */\nfunction helper(nums, target, pos) {\n for (let i = pos; i <= nums.length; i++) {\n if (i != pos && nums[i] == nums[i - 1]) continue\n if (nums[i] === target) return true\n if (nums[i] > target) break\n if (helper(nums, target - nums[i], i + 1)) return true\n }\n return false\n}\nconst canPartition = function(nums) {\n const sum = nums.reduce((sum, n) => (sum += n), 0) / 2\n if (sum % 1 != 0) {\n return false\n }\n\n return helper(nums, sum, 0)\n}\n\n// another\n\n/**\n * @param {number[]} nums\n * @return {boolean}\n */\nconst canPartition = function (nums) {\n const sumA = nums.reduce((acc, curr) => acc + curr, 0)\n if (sumA % 2) return false\n let row = 1n << BigInt(sumA / 2)\n for (const weight of nums) row = row | (row >> BigInt(weight))\n /*\n check the the column corresponding to my target by bitwise ANDing\n it with just 1,so if the first bit is 1,\n it will return true, otherwise false\n */\n return row & 1n\n}\n\n" + }, + { + "_id": "66f925ddfdfb8e1665720baf", + "questionid": 228, + "title": "Find Right Interval", + "slug": "find-right-interval", + "description": "You are given an array of intervals, where intervals[i] = [starti, endi] and each starti is unique. The right interval for an interval i is an interval j such that startj >= endi and startj is minimized. Note that i may equal j. Return an array of right interval indices for each interval i. If no right interval exists for interval i, then put -1 at index i. ", + "category": [ + "Array", + "Binary Search", + "Sorting" + ], + "complexity": "Medium", + "successrate": 49.4, + "totalsubmissions": 154224, + "totalaccepted": 76193, + "likes": 1169, + "dislikes": 248, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "intervals = [[1,2]]", + "expected_output": "[-1]", + "explanation": "There is only one interval in the collection, so it outputs -1." + }, + { + "example_num": 2, + "expected_input": "intervals = [[3,4],[2,3],[1,2]]", + "expected_output": "[-1,0,1]", + "explanation": "There is no right interval for [3,4].\nThe right interval for [2,3] is [3,4] since start0 = 3 is the smallest start that is >= end1 = 3.\nThe right interval for [1,2] is [2,3] since start1 = 2 is the smallest start that is >= end2 = 2." + }, + { + "example_num": 3, + "expected_input": "intervals = [[1,4],[2,3],[3,4]]", + "expected_output": "[-1,2,-1]", + "explanation": "There is no right interval for [1,4] and [3,4].\nThe right interval for [2,3] is [3,4] since start2 = 3 is the smallest start that is >= end1 = 3." + } + ], + "solution": "/**\n * @param {number[][]} intervals\n * @return {number[]}\n */\nconst findRightInterval = function(intervals) {\n const res = []\n const arrary = intervals\n .map((interval, idx) => ({ interval, idx }))\n .sort((obj1, obj2) => obj1.interval[0] - obj2.interval[0])\n for (let interval of intervals) {\n const val = interval[interval.length - 1]\n let left = 0,\n right = intervals.length\n while (left < right) {\n const mid = Math.floor((left + right) / 2)\n if (arrary[mid].interval[0] >= val) {\n right = mid\n } else {\n left = mid + 1\n }\n }\n if (left >= intervals.length) {\n res.push(-1)\n } else {\n res.push(arrary[left].idx)\n }\n }\n return res\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720bb5", + "questionid": 234, + "title": "Add Two Numbers II", + "slug": "add-two-numbers-ii", + "description": "You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list. You may assume the two numbers do not contain any leading zero, except the number 0 itself. ", + "category": [ + "Linked List", + "Math", + "Stack" + ], + "complexity": "Medium", + "successrate": 58.5, + "totalsubmissions": 523092, + "totalaccepted": 306223, + "likes": 3414, + "dislikes": 226, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "l1 = [7,2,4,3], l2 = [5,6,4]", + "expected_output": "[7,8,0,7]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "l1 = [2,4,3], l2 = [5,6,4]", + "expected_output": "[8,0,7]", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "l1 = [0], l2 = [0]", + "expected_output": "[0]", + "explanation": "" + } + ], + "solution": null + }, + { + "_id": "66f925ddfdfb8e1665720bbb", + "questionid": 240, + "title": "Minimum Number of Arrows to Burst Balloons", + "slug": "minimum-number-of-arrows-to-burst-balloons", + "description": "There are some spherical balloons taped onto a flat wall that represents the XY-plane. The balloons are represented as a 2D integer array points where points[i] = [xstart, xend] denotes a balloon whose horizontal diameter stretches between xstart and xend. You do not know the exact y-coordinates of the balloons. Arrows can be shot up directly vertically (in the positive y-direction) from different points along the x-axis. A balloon with xstart and xend is burst by an arrow shot at x if xstart <= x <= xend. There is no limit to the number of arrows that can be shot. A shot arrow keeps traveling up infinitely, bursting any balloons in its path. Given the array points, return the minimum number of arrows that must be shot to burst all balloons. ", + "category": [ + "Array", + "Greedy", + "Sorting" + ], + "complexity": "Medium", + "successrate": 52.9, + "totalsubmissions": 351182, + "totalaccepted": 185715, + "likes": 3362, + "dislikes": 97, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "points = [[10,16],[2,8],[1,6],[7,12]]", + "expected_output": "2", + "explanation": "The balloons can be burst by 2 arrows:\n- Shoot an arrow at x = 6, bursting the balloons [2,8] and [1,6].\n- Shoot an arrow at x = 11, bursting the balloons [10,16] and [7,12]." + }, + { + "example_num": 2, + "expected_input": "points = [[1,2],[3,4],[5,6],[7,8]]", + "expected_output": "4", + "explanation": "One arrow needs to be shot for each balloon for a total of 4 arrows." + }, + { + "example_num": 3, + "expected_input": "points = [[1,2],[2,3],[3,4],[4,5]]", + "expected_output": "2", + "explanation": "The balloons can be burst by 2 arrows:\n- Shoot an arrow at x = 2, bursting the balloons [1,2] and [2,3].\n- Shoot an arrow at x = 4, bursting the balloons [3,4] and [4,5]." + } + ], + "solution": "/**\n * @param {number[][]} points\n * @return {number}\n */\nconst findMinArrowShots = function(points) {\n const n = points.length\n if(n === 0) return 0\n points.sort((a, b) => a[1] - b[1])\n let res = 1\n let end = points[0][1]\n\n for(let i = 1; i < n; i++) {\n if(end >= points[i][0]) continue\n res++\n end = points[i][1]\n }\n\n return res\n};\n\n// another\n\n/**\n * @param {number[][]} points\n * @return {number}\n */\nconst findMinArrowShots = function(points) {\n const sorted = points.sort((a, b) => a[0] - b[0])\n let ans = 0\n let lastX = null\n for (let i = 0; i < sorted.length; i += 1) {\n if (lastX && sorted[i][0] <= lastX) {\n lastX = Math.min(sorted[i][1], lastX)\n } else {\n ans += 1\n lastX = sorted[i][1]\n }\n }\n return ans\n}\n\n// another\n\n/**\n * @param {number[][]} points\n * @return {number}\n */\nconst findMinArrowShots = function(points) {\n if(points == null || points.length === 0) return 0\n points.sort((a, b) => a[1] - b[1])\n let end = points[0][1], res = 1\n for(let i = 1, len = points.length; i < len; i++) {\n if(points[i][0] > end) {\n end = points[i][1]\n res++\n }\n }\n return res\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720b8c", + "questionid": 193, + "title": "Sum of Two Integers", + "slug": "sum-of-two-integers", + "description": "Given two integers a and b, return the sum of the two integers without using the operators + and -. ", + "category": [ + "Math", + "Bit Manipulation" + ], + "complexity": "Medium", + "successrate": 50.6, + "totalsubmissions": 575879, + "totalaccepted": 291580, + "likes": 2464, + "dislikes": 3695, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "a = 1, b = 2", + "expected_output": "3", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "a = 2, b = 3", + "expected_output": "5", + "explanation": "" + } + ], + "solution": "/**\n * @param {number} a\n * @param {number} b\n * @return {number}\n */\nconst getSum = function(a, b) {\n return b === 0 ? a : getSum(a ^ b, (a & b) << 1);\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720b8d", + "questionid": 194, + "title": "Super Pow", + "slug": "super-pow", + "description": "Your task is to calculate ab mod 1337 where a is a positive integer and b is an extremely large positive integer given in the form of an array. ", + "category": [ + "Math", + "Divide and Conquer" + ], + "complexity": "Medium", + "successrate": 37.6, + "totalsubmissions": 129129, + "totalaccepted": 48553, + "likes": 464, + "dislikes": 1081, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "a = 2, b = [3]", + "expected_output": "8", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "a = 2, b = [1,0]", + "expected_output": "1024", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "a = 1, b = [4,3,3,8,5,2]", + "expected_output": "1", + "explanation": "" + } + ], + "solution": "/**\n * @param {number} a\n * @param {number[]} b\n * @return {number}\n */\nconst superPow = function(a, b) {\n const base = 1337\n function powmod(a, k) {\n a %= base\n let res = 1\n for(let i = 0; i < k; i++) res = res * a % base\n return res\n }\n if(b.length === 0) return 1\n const last = b.pop()\n return powmod(superPow(a, b), 10) * powmod(a, last) % base\n}; \n" + }, + { + "_id": "66f925ddfdfb8e1665720b92", + "questionid": 199, + "title": "Ransom Note", + "slug": "ransom-note", + "description": "Given two strings ransomNote and magazine, return true if ransomNote can be constructed from magazine and false otherwise. Each letter in magazine can only be used once in ransomNote. ", + "category": [ + "Hash Table", + "String", + "Counting" + ], + "complexity": "Easy", + "successrate": 55.8, + "totalsubmissions": 659531, + "totalaccepted": 367856, + "likes": 1646, + "dislikes": 297, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "ransomNote = \"a\", magazine = \"b\"", + "expected_output": "false", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "ransomNote = \"aa\", magazine = \"ab\"", + "expected_output": "false", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "ransomNote = \"aa\", magazine = \"aab\"", + "expected_output": "true", + "explanation": "" + } + ], + "solution": "/**\n * @param {string} ransomNote\n * @param {string} magazine\n * @return {boolean}\n */\nconst canConstruct = function(ransomNote, magazine) {\n const m = new Map()\n for(let c of magazine) {\n m.set(c, (m.get(c) || 0) + 1 )\n }\n for(let c of ransomNote) {\n if(!m.has(c) || m.get(c) <= 0) return false\n m.set(c, m.get(c) - 1)\n }\n return true\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720b95", + "questionid": 202, + "title": "First Unique Character in a String", + "slug": "first-unique-character-in-a-string", + "description": "Given a string s, find the first non-repeating character in it and return its index. If it does not exist, return -1. ", + "category": [ + "Hash Table", + "String", + "Queue", + "Counting" + ], + "complexity": "Easy", + "successrate": 57, + "totalsubmissions": 1798969, + "totalaccepted": 1025564, + "likes": 4844, + "dislikes": 193, + "hints": "", + "deleted": false, + "examples": [], + "solution": "/**\n * @param {string} s\n * @return {number}\n */\nconst firstUniqChar = function(s) {\n const arr = [];\n const res = [];\n const hash = {};\n let tmp;\n let idx;\n for (let i = 0; i < s.length; i++) {\n tmp = s.charAt(i);\n if (hash.hasOwnProperty(tmp)) {\n idx = arr.indexOf(tmp);\n if (idx >= 0) {\n arr.splice(idx, 1);\n res.splice(idx, 1);\n }\n\n hash[tmp] += 1;\n } else {\n arr.push(tmp);\n res.push(i);\n hash[tmp] = 1;\n }\n }\n return res[0] == null ? -1 : res[0];\n};\n\n// another\n\n/**\n * @param {string} s\n * @return {number}\n */\nconst firstUniqChar = function(s) {\n if(s === '') return -1\n const map = new Map()\n for(let i = 0, len = s.length; i < len; i++) {\n if(!map.has(s[i])) map.set(s[i], [i, 0])\n map.get(s[i])[1] += 1\n }\n for(let [key, val] of map) {\n if(val[1] === 1) return val[0]\n }\n return -1\n \n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720b96", + "questionid": 203, + "title": "Find the Difference", + "slug": "find-the-difference", + "description": "You are given two strings s and t. String t is generated by random shuffling string s and then add one more letter at a random position. Return the letter that was added to t. ", + "category": [ + "Hash Table", + "String", + "Bit Manipulation", + "Sorting" + ], + "complexity": "Easy", + "successrate": 60.5, + "totalsubmissions": 635903, + "totalaccepted": 384938, + "likes": 2700, + "dislikes": 381, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "abcd", t = "abcde"", + "expected_output": ""e"", + "explanation": "'e' is the letter that was added." + }, + { + "example_num": 2, + "expected_input": "s = "", t = "y"", + "expected_output": ""y"", + "explanation": "" + } + ], + "solution": "/**\n * @param {string} s\n * @param {string} t\n * @return {character}\n */\nconst findTheDifference = function(s, t) {\n let xor = 0\n for(let i = 0, len = s.length; i < len; i++) xor = xor ^ s.charCodeAt(i) ^ t.charCodeAt(i)\n xor = xor ^ t.charCodeAt(t.length - 1)\n return String.fromCharCode(xor)\n};\n\n// another\n\n/**\n * @param {string} s\n * @param {string} t\n * @return {character}\n */\nconst findTheDifference = function(s, t) {\n const arr = s.split(\"\");\n let idx;\n for (let i = 0; i < t.length; i++) {\n idx = arr.indexOf(t[i]);\n if (idx === -1) {\n return t[i];\n } else {\n arr.splice(idx, 1);\n }\n }\n};\n\nconsole.log(findTheDifference(\"abcd\", \"abcde\"));\n" + }, + { + "_id": "66f925ddfdfb8e1665720b9a", + "questionid": 207, + "title": "Nth Digit", + "slug": "nth-digit", + "description": "Given an integer n, return the nth digit of the infinite integer sequence [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ...]. ", + "category": [ + "Math", + "Binary Search" + ], + "complexity": "Medium", + "successrate": 33.5, + "totalsubmissions": 223742, + "totalaccepted": 74920, + "likes": 656, + "dislikes": 1499, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 3", + "expected_output": "3", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "n = 11", + "expected_output": "0", + "explanation": "The 11th digit of the sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ... is a 0, which is part of the number 10." + } + ], + "solution": "/**\n * @param {number} n\n * @return {number}\n */\nconst findNthDigit = function(n) {\n let start = 1\n let len = 1\n let base = 9\n while(n > len * base) {\n n = n - len * base\n len++\n start *= 10\n base *= 10\n }\n let target = start + Math.floor((n - 1) / len)\n let reminder = (n - 1) % len\n return (''+target).charAt(reminder)\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720ba2", + "questionid": 215, + "title": "Split Array Largest Sum", + "slug": "split-array-largest-sum", + "description": "Given an array nums which consists of non-negative integers and an integer m, you can split the array into m non-empty continuous subarrays. Write an algorithm to minimize the largest sum among these m subarrays. ", + "category": [ + "Array", + "Binary Search", + "Dynamic Programming", + "Greedy" + ], + "complexity": "Hard", + "successrate": 52, + "totalsubmissions": 393533, + "totalaccepted": 204494, + "likes": 5728, + "dislikes": 149, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [7,2,5,10,8], k = 2", + "expected_output": "18", + "explanation": "There are four ways to split nums into two subarrays.\nThe best way is to split it into [7,2,5] and [10,8], where the largest sum among the two subarrays is only 18." + }, + { + "example_num": 2, + "expected_input": "nums = [1,2,3,4,5], k = 2", + "expected_output": "9", + "explanation": "There are four ways to split nums into two subarrays.\nThe best way is to split it into [1,2,3] and [4,5], where the largest sum among the two subarrays is only 9." + } + ], + "solution": "/**\n * @param {number[]} nums\n * @param {number} m\n * @return {number}\n */\nfunction doable(nums, cuts, max) {\n let acc = 0\n for(let num of nums) {\n if(num > max) return false\n else if(acc + num <= max) acc += num\n else {\n --cuts;\n acc = num;\n if(cuts < 0) return false\n }\n }\n return true\n}\n\n\nfunction splitArray(nums, m) {\n let left = 0\n let right = 0\n for(let num of nums) {\n left = Math.max(left, num)\n right += num\n }\n while(left < right) {\n let mid = Math.floor(left + (right - left) / 2)\n if(doable(nums, m - 1, mid)) right = mid\n else left = mid + 1 \n }\n return left\n}\n\n\n/**\n * @param {number[]} nums\n * @param {number} m\n * @return {number}\n */\nconst splitArray = function(nums, m) {\n let l = 0,\n r = 0\n for (let el of nums) {\n if (el > l) l = el\n r += el\n }\n while (l < r) {\n let mid = Math.floor((l + r) / 2)\n if (numOfSubArrLessOrEqualThanM(nums, mid, m)) r = mid\n else l = mid + 1\n }\n return l\n}\n\nfunction numOfSubArrLessOrEqualThanM(nums, target, m) {\n let sum = 0,\n count = 1\n for (let el of nums) {\n sum += el\n if (sum > target) {\n sum = el\n count++\n }\n if (count > m) return false\n }\n return true\n}\n\n/**\n\nIntroduction to this problem:\nWe can break this problem into two smaller problems:\n\nGiven an array (A), number of cuts (CUTS), and the Largest sum of sub-arrays (MAX). Can you use at most CUTS cuts to segment array A into CUTS + 1 sub-arrays, such that the sum of each sub-array is smaller or equal to MAX?\nGiven a lower bound (left), an upper bound (right), an unknown bool array (B), and an API uses i as input and tells you whether B[i] is true. If we know there exists an index k, that B[i] is false when i < k, and B[i] is true when i >= k. What is the fastest way to find this k (the lower bound)?\nSolution to the first sub-problem (Skip this part if you already knew how to solve 1st sub-problem):\nFor the first question, we can follow these steps:\n\nFor each element in the array, if its value is larger than MAX, we know it's not possible to cut this array into groups that the sum of all groups are smaller than MAX. (Reason is straightforward, if A is [10, 2, 3, 5] and MAX is 6, even you have 3 cuts by which you can cut A as [[10], [2], [3], [5]], the group containing 10 will still be larger than 6).\nUse greedy algorithm to cut A. Use an accumulator ACC to store the sum of the currently processed group, and process elements in A one by one. For each element num, if we add num with ACC and the new sum is still no larger than MAX, we update ACC to ACC + num, which means we can merge num into the current group. If not, we must use a cut before num to segment this array, then num will be the first element in the new group.\nIf we didn't go through A but already used up all cuts, then it's not possible only using CUTS cuts to segment this array into groups to make sure sum of each sub-array is smaller than MAX. Otherwise, if we can reach the end of A with cuts left (or use exactly CUTS cuts). It's possible to do so.\nThen the first question is solved.\n\nSolution to the second sub-problem(Skip this part if you already knew how to solve 2nd sub-problem):\nThe array B will be something like [false, false, ..., false, true, true, ..., true]. We want to find the index of the first true.\nUse binary search to find this k. Keep a value mid, mid = (left + right) / 2. If B[mid] = false, then move the search range to the upper half of the original search range, a.k.a left = mid + 1, otherwise move search range to the lower half, a.k.a right = mid.\nWhy this algorithm is correct...\nNo matter how we cut the array A, the Largest sum of sub-arrays will fall into a range [left, right]. Left is the value of the largest element in this array. right is the sum of this array. (e.g., Given array [1, 2, 3, 4, 5], if we have 4 cuts and cut it as [[1], [2], [3], [4], [5]], the Largest sum of sub-arrays is 5, it cannot be smaller. And if we have 0 cut, and the only sub-array is [[1, 2, 3, 4, 5]], the Largest sum of sub-arrays is 15, it cannot be larger).\nHowever, we cannot decide the number of cuts (CUTS), this is an given constraint. But we know there must be a magic number k, which is the smallest value of the Largest sum of sub-arrays when given CUTS cuts. When the Largest sum of sub-arrays is larger than k, we can always find a way to cut A within CUTS cuts. When the Largest sum of sub-arrays is smaller than k, there is no way to do this.\nExample\nFor example, given array A [1, 2, 3, 4, 5]. We can use 2 cuts.\n\nNo matter how many cuts are allowed, the range of the possible value of the Largest sum of sub-arrays is [5, 15].\nWhen given 2 cuts, we can tell the magic number k here is 6, the result of segmentation is [[1, 2, 3], [4], [5]].\nWhen Largest sum of sub-arrays is in range [6, 15], we can always find a way to cut this array within two cuts. You can have a try.\nHowever, when Largest sum of sub-arrays is in range [5, 5], there is no way to do this.\nThis mapped this problem into the second sub-problem. Bool array B here is [5:false, 6:true, 7:true, 8:true, ..., 15:true]. We want to find the index i of the first true in B, which is the answer of this entire question, and by solving the first sub-problem, we have an API that can tell us given an i (Largest sum of sub-arrays), whether B[i] is true (whether we can find a way to cut A to satisfy the constraint). \n */\n\n\n// another\n\n/**\n * @param {number[]} nums\n * @param {number} m\n * @return {number}\n */\nconst splitArray = (nums, m) => {\n let max = -Infinity, sum = 0\n for(let num of nums) {\n sum += num\n max = Math.max(max, num)\n }\n if (m === 1) return sum\n let l = max, r = sum\n while(l < r) {\n let mid = l + ((r - l) >> 1)\n if(valid(mid, nums, m)) {\n r = mid\n } else {\n l = mid + 1\n }\n }\n return l\n}\n\nfunction valid(target, nums, m) {\n let cnt = 1, sum = 0\n for(let num of nums) {\n sum += num\n if(sum > target) {\n cnt++\n sum = num\n if(cnt > m) return false\n }\n }\n\n return true\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720ba3", + "questionid": 216, + "title": "Arithmetic Slices", + "slug": "arithmetic-slices", + "description": "An integer array is called arithmetic if it consists of at least three elements and if the difference between any two consecutive elements is the same. Given an integer array nums, return the number of arithmetic subarrays of nums. A subarray is a contiguous subsequence of the array. ", + "category": [ + "Array", + "Dynamic Programming" + ], + "complexity": "Medium", + "successrate": 64.4, + "totalsubmissions": 350296, + "totalaccepted": 225542, + "likes": 3847, + "dislikes": 249, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,2,3,4]", + "expected_output": "3", + "explanation": "We have 3 arithmetic slices in nums: [1, 2, 3], [2, 3, 4] and [1,2,3,4] itself." + }, + { + "example_num": 2, + "expected_input": "nums = [1]", + "expected_output": "0", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} A\n * @return {number}\n */\nconst numberOfArithmeticSlices = function(A) {\n const arr = [];\n let count = 0;\n for (let i = 1; i < A.length - 1; i++) {\n if (A[i] - A[i - 1] === A[i + 1] - A[i]) {\n count += 1;\n } else {\n arr.push(count);\n count = 0;\n }\n }\n arr.push(count);\n return arr.reduce((ac, el) => ac + calc(el), 0);\n};\n\nfunction calc(num) {\n return (num * (num + 1)) / 2;\n}\n\nconsole.log(numberOfArithmeticSlices([1, 2, 3, 4]));\n" + }, + { + "_id": "66f925ddfdfb8e1665720ba5", + "questionid": 218, + "title": "Add Strings", + "slug": "add-strings", + "description": "Given two non-negative integers, num1 and num2 represented as string, return the sum of num1 and num2 as a string. You must solve the problem without using any built-in library for handling large integers (such as BigInteger). You must also not convert the inputs to integers directly. ", + "category": [ + "Math", + "String", + "Simulation" + ], + "complexity": "Easy", + "successrate": 52.1, + "totalsubmissions": 888575, + "totalaccepted": 462692, + "likes": 3167, + "dislikes": 538, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "num1 = "11", num2 = "123"", + "expected_output": ""134"", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "num1 = "456", num2 = "77"", + "expected_output": ""533"", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "num1 = "0", num2 = "0"", + "expected_output": ""0"", + "explanation": "" + } + ], + "solution": "/**\n * @param {string} num1\n * @param {string} num2\n * @return {string}\n */\nconst addStrings = function(num1, num2) {\n let sb = \"\";\n let carry = 0;\n for (\n let i = num1.length - 1, j = num2.length - 1;\n i >= 0 || j >= 0 || carry == 1;\n i--, j--\n ) {\n let x = i < 0 ? 0 : +num1.charAt(i);\n let y = j < 0 ? 0 : +num2.charAt(j);\n sb = (+(x + y + carry) % 10) + sb;\n carry = x + y + carry >= 10 ? 1 : 0;\n }\n return sb;\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720ba9", + "questionid": 222, + "title": "Maximum XOR of Two Numbers in an Array", + "slug": "maximum-xor-of-two-numbers-in-an-array", + "description": "Given an integer array nums, return the maximum result of nums[i] XOR nums[j], where 0 <= i <= j < n. ", + "category": [ + "Array", + "Hash Table", + "Bit Manipulation", + "Trie" + ], + "complexity": "Medium", + "successrate": 54.3, + "totalsubmissions": 223851, + "totalaccepted": 121492, + "likes": 3837, + "dislikes": 324, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [3,10,5,25,2,8]", + "expected_output": "28", + "explanation": "The maximum result is 5 XOR 25 = 28." + }, + { + "example_num": 2, + "expected_input": "nums = [14,70,53,83,49,91,36,80,92,51,66,70]", + "expected_output": "127", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} nums\n * @return {number}\n */\nconst findMaximumXOR = function(nums) {\n let res = 0, mask = 0\n for(let i = 31; i >= 0; i--) {\n mask = mask | (1 << i)\n const set = new Set()\n for(let e of nums) set.add(e & mask)\n const tmp = res | (1 << i)\n for(let e of set) {\n if(set.has(e ^ tmp)) {\n res = tmp\n break\n }\n }\n }\n return res\n};\n\n// another\n\n/*\n\nThis algorithm's idea is:\nto iteratively determine what would be each bit of the final result from left to right.\nAnd it narrows down the candidate group iteration by iteration. e.g. assume input are a,b,c,d,...z, 26 integers in total.\nIn first iteration, if you found that a, d, e, h, u differs on the MSB(most significant bit),\nso you are sure your final result's MSB is set. Now in second iteration,\nyou try to see if among a, d, e, h, u there are at least two numbers make the 2nd MSB differs,\nif yes, then definitely, the 2nd MSB will be set in the final result.\nAnd maybe at this point the candidate group shinks from a,d,e,h,u to a, e, h.\nImplicitly, every iteration, you are narrowing down the candidate group,\nbut you don't need to track how the group is shrinking, you only cares about the final result.\n\n*/\n/*\n * @lc app=leetcode id=421 lang=javascript\n *\n * [421] Maximum XOR of Two Numbers in an Array\n */\n/**\n * @param {number[]} nums\n * @return {number}\n */\nconst findMaximumXOR = function(nums) {\n let maxResult = 0\n let mask = 0\n /*The maxResult is a record of the largest XOR we got so far. if it's 11100 at i = 2, it means \n before we reach the last two bits, 11100 is the biggest XOR we have, and we're going to explore\n whether we can get another two '1's and put them into maxResult\n \n This is a greedy part, since we're looking for the largest XOR, we start \n from the very begining, aka, the 31st postition of bits. */\n for (let i = 31; i >= 0; i--) {\n //The mask will grow like 100..000 , 110..000, 111..000, then 1111...111\n //for each iteration, we only care about the left parts\n mask = mask | (1 << i)\n\n let set = new Set()\n for (let num of nums) {\n /* we only care about the left parts, for example, if i = 2, then we have\n {1100, 1000, 0100, 0000} from {1110, 1011, 0111, 0010}*/\n let leftPartOfNum = num & mask\n set.add(leftPartOfNum)\n }\n\n // if i = 1 and before this iteration, the maxResult we have now is 1100,\n // my wish is the maxResult will grow to 1110, so I will try to find a candidate\n // which can give me the greedyTry;\n let greedyTry = maxResult | (1 << i)\n\n for (let leftPartOfNum of set) {\n //This is the most tricky part, coming from a fact that if a ^ b = c, then a ^ c = b;\n // now we have the 'c', which is greedyTry, and we have the 'a', which is leftPartOfNum\n // If we hope the formula a ^ b = c to be valid, then we need the b,\n // and to get b, we need a ^ c, if a ^ c exisited in our set, then we're good to go\n let anotherNum = leftPartOfNum ^ greedyTry\n if (set.has(anotherNum)) {\n maxResult = greedyTry\n break\n }\n }\n\n // If unfortunately, we didn't get the greedyTry, we still have our max,\n // So after this iteration, the max will stay at 1100.\n }\n return maxResult\n}\n\n// another\n\n/**\n * @param {number[]} nums\n * @return {number}\n */\nconst findMaximumXOR = function (nums) {\n if (nums == null || nums.length == 0) {\n return 0\n }\n const root = new Trie()\n for (let num of nums) {\n let curNode = root\n for (let i = 31; i >= 0; i--) {\n let curBit = (num >>> i) & 1\n if (curNode.children[curBit] == null) {\n curNode.children[curBit] = new Trie()\n }\n curNode = curNode.children[curBit]\n }\n }\n let max = Number.MIN_VALUE\n for (let num of nums) {\n let curNode = root\n let curSum = 0\n for (let i = 31; i >= 0; i--) {\n let curBit = (num >>> i) & 1\n if (curNode.children[curBit ^ 1] != null) {\n curSum += 1 << i\n curNode = curNode.children[curBit ^ 1]\n } else {\n curNode = curNode.children[curBit]\n }\n }\n max = Math.max(curSum, max)\n }\n return max\n}\n\nclass Trie {\n constructor() {\n this.children = {}\n }\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720bb1", + "questionid": 230, + "title": "Find All Anagrams in a String", + "slug": "find-all-anagrams-in-a-string", + "description": "Given two strings s and p, return an array of all the start indices of p's anagrams in s. You may return the answer in any order. An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. ", + "category": [ + "Hash Table", + "String", + "Sliding Window" + ], + "complexity": "Medium", + "successrate": 48.2, + "totalsubmissions": 1076189, + "totalaccepted": 518606, + "likes": 7285, + "dislikes": 251, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "cbaebabacd", p = "abc"", + "expected_output": "[0,6]", + "explanation": "The substring with start index = 0 is "cba", which is an anagram of "abc".\nThe substring with start index = 6 is "bac", which is an anagram of "abc"." + }, + { + "example_num": 2, + "expected_input": "s = "abab", p = "ab"", + "expected_output": "[0,1,2]", + "explanation": "The substring with start index = 0 is "ab", which is an anagram of "ab".\nThe substring with start index = 1 is "ba", which is an anagram of "ab".\nThe substring with start index = 2 is "ab", which is an anagram of "ab"." + } + ], + "solution": "/**\n * @param {string} s\n * @param {string} p\n * @return {number[]}\n */\nconst findAnagrams = function (s, p) {\n const slen = s.length;\n const plen = p.length;\n if (plen > slen) return [];\n const aCode = \"a\".charCodeAt(0);\n const count = new Array(26).fill(0);\n for (let i = 0; i < plen; i++) count[p.charCodeAt(i) - aCode] += 1;\n const res = [];\n for (let i = 0; i < slen; i++) {\n count[s.charCodeAt(i) - aCode] -= 1;\n if (i >= plen - 1) {\n if (i - plen >= 0) count[s.charCodeAt(i - plen) - aCode] += 1;\n if (allZero(count)) res.push(i - plen + 1);\n }\n }\n return res;\n};\nfunction allZero(count) {\n for (let el of count) {\n if (el !== 0) return false;\n }\n return true;\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720bb6", + "questionid": 235, + "title": "Arithmetic Slices II - Subsequence", + "slug": "arithmetic-slices-ii-subsequence", + "description": "Given an integer array nums, return the number of all the arithmetic subsequences of nums. A sequence of numbers is called arithmetic if it consists of at least three elements and if the difference between any two consecutive elements is the same. A subsequence of an array is a sequence that can be formed by removing some elements (possibly none) of the array. The test cases are generated so that the answer fits in 32-bit integer. ", + "category": [ + "Array", + "Dynamic Programming" + ], + "complexity": "Hard", + "successrate": 39.4, + "totalsubmissions": 110325, + "totalaccepted": 43491, + "likes": 1340, + "dislikes": 85, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [2,4,6,8,10]", + "expected_output": "7", + "explanation": "All arithmetic subsequence slices are:\n[2,4,6]\n[4,6,8]\n[6,8,10]\n[2,4,6,8]\n[4,6,8,10]\n[2,4,6,8,10]\n[2,6,10]" + }, + { + "example_num": 2, + "expected_input": "nums = [7,7,7,7,7]", + "expected_output": "16", + "explanation": "Any subsequence of this array is arithmetic." + } + ], + "solution": "/**\n * @param {number[]} A\n * @return {number}\n */\nconst numberOfArithmeticSlices = function(A) {\n if (!A || A.length < 3) return 0;\n let res = 0;\n const dp = Array(A.length);\n for (let i = 0; i < A.length; i++) {\n dp[i] = new Map();\n for (let j = 0; j < i; j++) {\n const diff = A[i] - A[j];\n const prevCount = dp[j].get(diff) || 0;\n res += prevCount;\n const currCount = (dp[i].get(diff) || 0) + 1;\n dp[i].set(diff, prevCount + currCount);\n }\n }\n return res;\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720bbd", + "questionid": 242, + "title": "Assign Cookies", + "slug": "assign-cookies", + "description": "Assume you are an awesome parent and want to give your children some cookies. But, you should give each child at most one cookie. Each child i has a greed factor g[i], which is the minimum size of a cookie that the child will be content with; and each cookie j has a size s[j]. If s[j] >= g[i], we can assign the cookie j to the child i, and the child i will be content. Your goal is to maximize the number of your content children and output the maximum number. ", + "category": [ + "Array", + "Greedy", + "Sorting" + ], + "complexity": "Easy", + "successrate": 50.7, + "totalsubmissions": 319993, + "totalaccepted": 162255, + "likes": 1404, + "dislikes": 157, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "g = [1,2,3], s = [1,1]", + "expected_output": "1", + "explanation": "You have 3 children and 2 cookies. The greed factors of 3 children are 1, 2, 3. \nAnd even though you have 2 cookies, since their size is both 1, you could only make the child whose greed factor is 1 content.\nYou need to output 1." + }, + { + "example_num": 2, + "expected_input": "g = [1,2], s = [1,2,3]", + "expected_output": "2", + "explanation": "You have 2 children and 3 cookies. The greed factors of 2 children are 1, 2. \nYou have 3 cookies and their sizes are big enough to gratify all of the children, \nYou need to output 2." + } + ], + "solution": "/**\n * @param {number[]} g\n * @param {number[]} s\n * @return {number}\n */\nconst findContentChildren = function(g, s) {\n s.sort((a, b) => a - b);\n g.sort((a, b) => a - b);\n\n let i = 0;\n for (let j = 0; i < g.length && j < s.length; j++) {\n if (g[i] <= s[j]) i++;\n }\n return i;\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720bbe", + "questionid": 243, + "title": "132 Pattern", + "slug": "132-pattern", + "description": "Given an array\u00a0of n integers nums, a 132 pattern is a subsequence of three integers nums[i], nums[j] and nums[k] such that i < j < k and nums[i] < nums[k] < nums[j]. Return true if there is a 132 pattern in nums, otherwise, return false. ", + "category": [ + "Array", + "Binary Search", + "Stack", + "Monotonic Stack", + "Ordered Set" + ], + "complexity": "Medium", + "successrate": 30.9, + "totalsubmissions": 344145, + "totalaccepted": 106371, + "likes": 3199, + "dislikes": 176, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,2,3,4]", + "expected_output": "false", + "explanation": "There is no 132 pattern in the sequence." + }, + { + "example_num": 2, + "expected_input": "nums = [3,1,4,2]", + "expected_output": "true", + "explanation": "There is a 132 pattern in the sequence: [1, 4, 2]." + }, + { + "example_num": 3, + "expected_input": "nums = [-1,3,2,0]", + "expected_output": "true", + "explanation": "There are three 132 patterns in the sequence: [-1, 3, 2], [-1, 3, 0] and [-1, 2, 0]." + } + ], + "solution": "/**\n * @param {number[]} nums\n * @return {boolean}\n */\nconst find132pattern = function(nums) {\n let [stack, s3] = [[], -Infinity]\n for (let i = nums.length - 1; i >= 0; i--) {\n if (nums[i] < s3) {\n return true\n }\n while (stack[stack.length - 1] < nums[i]) {\n s3 = stack.pop()\n }\n stack.push(nums[i])\n }\n return false\n}\n\n// another\n\n/**\n * @param {number[]} nums\n * @return {boolean}\n */\nconst find132pattern = function(nums) {\n let idx = nums.length\n let s3 = Number.NEGATIVE_INFINITY\n for(let len = nums.length, i = len - 1; i >= 0; i--) {\n if(nums[i] < s3) return true\n while(idx < nums.length && nums[i] > nums[idx]) {\n s3 = nums[idx++]\n }\n nums[--idx] = nums[i] \n }\n return false\n}\n\n" + }, + { + "_id": "66f925ddfdfb8e1665720bbf", + "questionid": 244, + "title": "Repeated Substring Pattern", + "slug": "repeated-substring-pattern", + "description": "Given a string s, check if it can be constructed by taking a substring of it and appending multiple copies of the substring together. ", + "category": [ + "String", + "String Matching" + ], + "complexity": "Easy", + "successrate": 43.6, + "totalsubmissions": 545164, + "totalaccepted": 237600, + "likes": 3266, + "dislikes": 312, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "abab"", + "expected_output": "true", + "explanation": "It is the substring "ab" twice." + }, + { + "example_num": 2, + "expected_input": "s = "aba"", + "expected_output": "false", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "s = "abcabcabcabc"", + "expected_output": "true", + "explanation": "It is the substring "abc" four times or the substring "abcabc" twice." + } + ], + "solution": "/**\n * @param {string} s\n * @return {boolean}\n */\nconst repeatedSubstringPattern = function(s) {\n \n const len = s.length\n const table = build(s)\n return table[len] && (table[len] % (len - table[len]) === 0)\n \n function build(str) {\n const n = str.length\n const table = Array(n + 1).fill(0)\n let i = 1, j = 0\n table[0] = -1\n while(i < n) {\n if(str[i] === str[j]) {\n i++\n j++\n table[i] = j\n } else {\n if(j > 0) j = table[j]\n else i++\n }\n }\n \n return table\n }\n};\n\n// another\n\n/**\n * @param {string} s\n * @return {boolean}\n */\nconst repeatedSubstringPattern = function(s) {\n const len = s.length\n let tmp = ''\n for(let i = 1; i <= len; i++) {\n tmp = s.substr(0, i)\n if (tmp.length === len) {\n return false\n }\n if (s === genStr(tmp, len)) {\n return true\n }\n }\n return false\n};\nfunction genStr(sub, limit) {\n let str = sub\n while(str.length < limit) {\n str += sub\n }\n return str\n}\n\n// another\n\n/**\n * @param {string} s\n * @return {boolean}\n */\nconst repeatedSubstringPattern = function (s) {\n const l = s.length\n const arr = DFA(s)\n return arr[l] && arr[l] % (l - arr[l]) === 0\n function DFA(s) {\n let i = 1\n let j = 0\n const len = s.length\n const prefix = Array(len + 1).fill(0)\n prefix[0] = -1\n prefix[1] = 0\n while (i < len) {\n if (s[j] === s[i]) {\n j++\n i++\n prefix[i] = j\n } else {\n if (j > 0) j = prefix[j]\n else i++\n }\n }\n return prefix\n }\n}\n\n// another\n\n/**\n * @param {string} s\n * @return {boolean}\n */\nconst repeatedSubstringPattern = function(s) {\n let i = 1, j = 0, n = s.length;\n const dp = Array(n + 1).fill(0);\n while( i < s.length ){\n if( s[i] === s[j] ) dp[++i] = ++j;\n else if( j === 0 ) i++;\n else j = dp[j];\n }\n return dp[n] && (dp[n] % (n - dp[n]) === 0); \n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720bc0", + "questionid": 245, + "title": "Hamming Distance", + "slug": "hamming-distance", + "description": "The Hamming distance between two integers is the number of positions at which the corresponding bits are different. Given two integers x and y, return the Hamming distance between them. ", + "category": [ + "Bit Manipulation" + ], + "complexity": "Easy", + "successrate": 74.5, + "totalsubmissions": 630915, + "totalaccepted": 469900, + "likes": 3021, + "dislikes": 197, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "x = 1, y = 4", + "expected_output": "2", + "explanation": "1 (0 0 0 1)\n4 (0 1 0 0)\n ↑ ↑\nThe above arrows point to positions where the corresponding bits are different." + }, + { + "example_num": 2, + "expected_input": "x = 3, y = 1", + "expected_output": "1", + "explanation": "" + } + ], + "solution": "/**\n * @param {number} x\n * @param {number} y\n * @return {number}\n */\nconst hammingDistance = function (x, y) {\n let d = 0\n let h = x ^ y\n while (h > 0) {\n d++\n h &= h - 1\n }\n return d\n}\n\n// another\n\n/**\n * @param {number} x\n * @param {number} y\n * @return {number}\n */\nconst hammingDistance = function (x, y) {\n let n = x ^ y\n n = n - ((n >> 1) & 0x55555555)\n n = (n & 0x33333333) + ((n >> 2) & 0x33333333)\n return (((n + (n >> 4)) & 0xf0f0f0f) * 0x1010101) >> 24\n}\n\n// another\n\n/**\n * @param {number} x\n * @param {number} y\n * @return {number}\n */\nconst hammingDistance = function (x, y) {\n let n = x ^ y\n let tmp = n - ((n >> 1) & 033333333333) - ((n >> 2) & 011111111111);\n return ((tmp + (tmp >> 3)) & 030707070707) % 63;\n}\n\n// https://tech.liuchao.me/2016/11/count-bits-of-integer/\n" + }, + { + "_id": "66f925ddfdfb8e1665720bc2", + "questionid": 247, + "title": "Island Perimeter", + "slug": "island-perimeter", + "description": "You are given row x col grid representing a map where grid[i][j] = 1 represents\u00a0land and grid[i][j] = 0 represents water. Grid cells are connected horizontally/vertically (not diagonally). The grid is completely surrounded by water, and there is exactly one island (i.e., one or more connected land cells). The island doesn't have \"lakes\", meaning the water inside isn't connected to the water around the island. One cell is a square with side length 1. The grid is rectangular, width and height don't exceed 100. Determine the perimeter of the island. ", + "category": [ + "Array", + "Depth-First Search", + "Breadth-First Search", + "Matrix" + ], + "complexity": "Easy", + "successrate": 68.9, + "totalsubmissions": 522927, + "totalaccepted": 360401, + "likes": 4279, + "dislikes": 237, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "grid = [[0,1,0,0],[1,1,1,0],[0,1,0,0],[1,1,0,0]]", + "expected_output": "16", + "explanation": "The perimeter is the 16 yellow stripes in the image above." + }, + { + "example_num": 2, + "expected_input": "grid = [[1]]", + "expected_output": "4", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "grid = [[1,0]]", + "expected_output": "4", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[][]} grid\n * @return {number}\n */\nconst islandPerimeter = function(grid) {\n let len = 0;\n for (let r = 0; r < grid.length; r++) {\n for (let c = 0; c < grid[0].length; c++) {\n if (grid[r][c] === 1) {\n len += cell(grid, r, c);\n }\n }\n }\n return len;\n};\n\nfunction cell(grid, r, c) {\n let len = 0;\n // top\n if (r === 0 || grid[r - 1][c] !== 1) {\n len += 1;\n }\n // left\n if (c === 0 || grid[r][c - 1] !== 1) {\n len += 1;\n }\n // right\n if (grid[r][c + 1] !== 1) {\n len += 1;\n }\n // bottom\n if (grid[r + 1] == null || grid[r + 1][c] !== 1) {\n len += 1;\n }\n return len;\n}\n\nconsole.log(\n islandPerimeter([[0, 1, 0, 0], [1, 1, 1, 0], [0, 1, 0, 0], [1, 1, 0, 0]])\n);\n\n// another\n\n/**\n * @param {number[][]} grid\n * @return {number}\n */\nconst islandPerimeter = function(grid) {\n const m = grid.length\n const n = grid[0].length\n const dirs = [[0, 1], [0, -1], [1, 0], [-1, 0]]\n let r = 0\n for(let i = 0; i < m; i++) {\n for(let j = 0; j < n; j++) {\n if(grid[i][j] === 1) r += h(i, j)\n }\n }\n \n return r\n \n function h(i, j) {\n let res = 0\n for(let d of dirs) {\n const nr = i + d[0]\n const nc = j + d[1]\n if(nr < 0 || nc < 0 || nr >= m || nc >= n || grid[nr][nc] === 0) res++\n }\n return res\n }\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720bc3", + "questionid": 248, + "title": "Can I Win", + "slug": "can-i-win", + "description": "In the \"100 game\" two players take turns adding, to a running total, any integer from 1 to 10. The player who first causes the running total to reach or exceed 100 wins. What if we change the game so that players cannot re-use integers? For example, two players might take turns drawing from a common pool of numbers from 1 to 15 without replacement until they reach a total >= 100. Given two integers maxChoosableInteger and desiredTotal, return true if the first player to move can force a win, otherwise, return false. Assume both players play optimally. ", + "category": [ + "Math", + "Dynamic Programming", + "Bit Manipulation", + "Memoization", + "Game Theory", + "Bitmask" + ], + "complexity": "Medium", + "successrate": 29.8, + "totalsubmissions": 250138, + "totalaccepted": 74662, + "likes": 1824, + "dislikes": 294, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "maxChoosableInteger = 10, desiredTotal = 11", + "expected_output": "false", + "explanation": "No matter which integer the first player choose, the first player will lose.\nThe first player can choose an integer from 1 up to 10.\nIf the first player choose 1, the second player can only choose integers from 2 up to 10.\nThe second player will win by choosing 10 and get a total = 11, which is >= desiredTotal.\nSame with other integers chosen by the first player, the second player will always win." + }, + { + "example_num": 2, + "expected_input": "maxChoosableInteger = 10, desiredTotal = 0", + "expected_output": "true", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "maxChoosableInteger = 10, desiredTotal = 1", + "expected_output": "true", + "explanation": "" + } + ], + "solution": "/**\n * @param {number} maxChoosableInteger\n * @param {number} desiredTotal\n * @return {boolean}\n */\nconst canIWin = function(maxChoosableInteger, desiredTotal) {\n if (desiredTotal <= 0) return true\n if ((maxChoosableInteger * (1 + maxChoosableInteger)) / 2 < desiredTotal)\n return false\n const dp = new Array(1 << maxChoosableInteger).fill(0)\n return dfs(dp, 0, maxChoosableInteger, desiredTotal)\n\n function dfs(dp, chs, max, target) {\n if (target <= 0) return false\n if (dp[chs] != 0) return dp[chs] === 1\n let win = false\n for (let i = 0; i < max; i++) {\n if ((chs & (1 << i)) === 0) {\n //not used\n win = win || !dfs(dp, chs ^ (1 << i), max, target - i - 1)\n }\n }\n dp[chs] = win ? 1 : -1\n return win\n }\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720bc5", + "questionid": 250, + "title": "Concatenated Words", + "slug": "concatenated-words", + "description": "Given an array of strings words (without duplicates), return all the concatenated words in the given list of words. A concatenated word is defined as a string that is comprised entirely of at least two shorter words in the given array. ", + "category": [ + "Array", + "String", + "Dynamic Programming", + "Depth-First Search", + "Trie" + ], + "complexity": "Hard", + "successrate": 42.8, + "totalsubmissions": 300523, + "totalaccepted": 128601, + "likes": 1848, + "dislikes": 216, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "words = ["cat","cats","catsdogcats","dog","dogcatsdog","hippopotamuses","rat","ratcatdogcat"]", + "expected_output": "["catsdogcats","dogcatsdog","ratcatdogcat"]", + "explanation": ""catsdogcats" can be concatenated by "cats", "dog" and "cats"; \n"dogcatsdog" can be concatenated by "dog", "cats" and "dog"; \n"ratcatdogcat" can be concatenated by "rat", "cat", "dog" and "cat"." + }, + { + "example_num": 2, + "expected_input": "words = ["cat","dog","catdog"]", + "expected_output": "["catdog"]", + "explanation": "" + } + ], + "solution": "/**\n * @param {string[]} words\n * @return {string[]}\n */\n\nconst findAllConcatenatedWordsInADict = function (words) {\n const pre = new Set()\n words.sort((a, b) => a.length - b.length)\n const res = []\n for(let i = 0; i < words.length; i++) {\n if(valid(words[i], pre)) {\n res.push(words[i])\n }\n pre.add(words[i])\n }\n\n return res\n\n function valid(str, set) {\n if(set.size === 0) return false\n const dp = Array(str.length + 1).fill(false)\n dp[0] = true\n for(let i = 1; i <= str.length; i++) {\n for(let j = 0; j < i; j++) {\n if(!dp[j]) continue\n if(set.has(str.slice(j, i))) {\n dp[i] = true\n break\n }\n }\n }\n \n return dp[str.length]\n }\n}\n\n\n\n\n// another\n\n/**\n * @param {string[]} words\n * @return {string[]}\n */\n\nconst findAllConcatenatedWordsInADict = function (words) {\n const set = new Set(words)\n const res = []\n const map = new Map()\n for (let w of words) {\n if (w.length < 2) continue\n if (dfs(w, set, map, 0)) res.push(w)\n }\n return res\n\n function dfs(word, set, map, pos) {\n if (pos > 0 && map.get(word)) return map.get(word)\n if (pos > 0 && set.has(word)) {\n map.set(word, true)\n return map.get(word)\n }\n for (let i = 1; i < word.length; i++) {\n const left = word.slice(0, i)\n const right = word.slice(i)\n if (set.has(right) && dfs(left, set, map, pos + 1)) {\n map.set(word, true)\n return map.get(word)\n }\n }\n\n map.set(word, false)\n return false\n }\n}\n\n// another\n\n/**\n * @param {string[]} words\n * @return {string[]}\n */\n\nconst findAllConcatenatedWordsInADict = function (words) {\n const set = new Set(words)\n const res = []\n const map = new Map()\n\n for(let word of words) {\n if(dfs(word, 0)) res.push(word)\n }\n return res\n function dfs(word, idx) {\n if(map.has(word)) return map.get(word)\n if(idx > 0 && set.has(word)) return true\n let tmp = false\n for(let i = 1; i < word.length; i++) {\n const prefix = word.slice(0, i), suffix = word.slice(i)\n if(set.has(prefix) && set.has(suffix)) {\n tmp = true\n break\n }\n if(set.has(prefix) && dfs(suffix, idx + 1)) {\n tmp = true\n break\n }\n }\n \n map.set(word, tmp)\n return tmp\n }\n}\n\n\n// another\n\n/**\n * @param {string[]} words\n * @return {string[]}\n */\nconst findAllConcatenatedWordsInADict = function(words) {\n let res = []\n if (words === null || words.length == 0) return res\n let set = new Set(words)\n for (let word of words) {\n set.delete(word)\n if (dfs(word, set, '')) res.push(word)\n set.add(word)\n }\n return res\n}\n\nfunction dfs(word, set, prev) {\n if (prev != '') set.add(prev)\n if (set.has(word)) return true\n for (let i = 1; i <= word.length; i++) {\n const prefix = word.substring(0, i)\n if (set.has(prefix) && dfs(word.substring(i), set, prev + prefix)) {\n return true\n }\n }\n return false\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720bc7", + "questionid": 252, + "title": "Ones and Zeroes", + "slug": "ones-and-zeroes", + "description": "You are given an array of binary strings strs and two integers m and n. Return the size of the largest subset of strs such that there are at most m 0's and n 1's in the subset. A set x is a subset of a set y if all elements of x are also elements of y. ", + "category": [ + "Array", + "String", + "Dynamic Programming" + ], + "complexity": "Medium", + "successrate": 44.5, + "totalsubmissions": 237317, + "totalaccepted": 105672, + "likes": 2790, + "dislikes": 322, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "strs = ["10","0001","111001","1","0"], m = 5, n = 3", + "expected_output": "4", + "explanation": "The largest subset with at most 5 0's and 3 1's is {"10", "0001", "1", "0"}, so the answer is 4.\nOther valid but smaller subsets include {"0001", "1"} and {"10", "1", "0"}.\n{"111001"} is an invalid subset because it contains 4 1's, greater than the maximum of 3." + }, + { + "example_num": 2, + "expected_input": "strs = ["10","0","1"], m = 1, n = 1", + "expected_output": "2\nExplanation: The largest subset is {"0", "1"}, so the answer is 2.", + "explanation": "" + } + ], + "solution": "/**\n * @param {string[]} strs\n * @param {number} m\n * @param {number} n\n * @return {number}\n */\n\nconst findMaxForm = function(strs, m, n) {\n const memo = Array.from(new Array(m + 1), () => new Array(n + 1).fill(0))\n let numZeroes\n let numOnes\n\n for (let s of strs) {\n numZeroes = numOnes = 0\n // count number of zeroes and ones in current string\n for (let c of s) {\n if (c === '0') numZeroes++\n else if (c === '1') numOnes++\n }\n // memo[i][j] = the max number of strings that can be formed with i 0's and j 1's\n // from the first few strings up to the current string s\n // Catch: have to go from bottom right to top left\n // Why? If a cell in the memo is updated(because s is selected),\n // we should be adding 1 to memo[i][j] from the previous iteration (when we were not considering s)\n // If we go from top left to bottom right, we would be using results from this iteration => overcounting\n for (let i = m; i >= numZeroes; i--) {\n for (let j = n; j >= numOnes; j--) {\n memo[i][j] = Math.max(memo[i][j], memo[i - numZeroes][j - numOnes] + 1)\n }\n }\n }\n return memo[m][n]\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720bc8", + "questionid": 253, + "title": "Heaters", + "slug": "heaters", + "description": "Winter is coming! During the contest, your first job is to design a standard heater with a fixed warm radius to warm all the houses. Every house can be warmed, as long as the house is within the heater's warm radius range. Given the positions of houses and heaters on a horizontal line, return the minimum radius standard of heaters\u00a0so that those heaters could cover all houses. Notice that\u00a0all the heaters follow your radius standard, and the warm radius will the same. ", + "category": [ + "Array", + "Two Pointers", + "Binary Search", + "Sorting" + ], + "complexity": "Medium", + "successrate": 35.2, + "totalsubmissions": 247584, + "totalaccepted": 87206, + "likes": 1326, + "dislikes": 1026, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "houses = [1,2,3], heaters = [2]", + "expected_output": "1", + "explanation": "The only heater was placed in the position 2, and if we use the radius 1 standard, then all the houses can be warmed." + }, + { + "example_num": 2, + "expected_input": "houses = [1,2,3,4], heaters = [1,4]", + "expected_output": "1", + "explanation": "The two heaters were placed at positions 1 and 4. We need to use a radius 1 standard, then all the houses can be warmed." + }, + { + "example_num": 3, + "expected_input": "houses = [1,5], heaters = [2]", + "expected_output": "3", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} houses\n * @param {number[]} heaters\n * @return {number}\n */\nconst findRadius = function(houses, heaters) {\n heaters.sort((a, b) => a - b)\n return Math.max(...houses.map(h => findMinDistance(h, heaters)))\n}\n\nconst findMinDistance = (house, heaters) => {\n let left = 0\n let right = heaters.length - 1\n while (left <= right) {\n const mid = left + ((right - left) >> 1)\n if (heaters[mid] <= house && house <= heaters[mid + 1]) {\n return Math.min(house - heaters[mid], heaters[mid + 1] - house)\n } else if (heaters[mid] <= house) {\n left = mid + 1\n } else {\n right = mid - 1\n }\n }\n if (left === 0) return heaters[0] - house\n if (left === heaters.length) return house - heaters[heaters.length - 1]\n}\n\n// another\n\n/**\n * @param {number[]} houses\n * @param {number[]} heaters\n * @return {number}\n */\nconst findRadius = function(houses, heaters) {\n let res = 0\n let k = 0\n houses = houses.sort((a, b) => a - b)\n heaters = heaters.sort((a, b) => a - b)\n for (let i = 0; i < houses.length; i++) {\n const curr = houses[i]\n while (\n k < heaters.length &&\n Math.abs(heaters[k + 1] - curr) <= Math.abs(heaters[k] - curr)\n ) {\n k++\n }\n res = Math.max(res, Math.abs(heaters[k] - curr))\n }\n return res\n}\n\n// another\n\n/**\n * @param {number[]} houses\n * @param {number[]} heaters\n * @return {number}\n */\nconst findRadius = function(houses, heaters) {\n heaters.sort((a, b) => a - b)\n houses.sort((a, b) => a - b)\n let res = 0, i = 0\n for(let h of houses) {\n while(i < heaters.length - 1 && heaters[i] + heaters[i + 1] <= h * 2) i++\n res = Math.max(res, Math.abs(heaters[i] - h))\n }\n return res\n}\n\n" + }, + { + "_id": "66f925ddfdfb8e1665720bc9", + "questionid": 254, + "title": "Number Complement", + "slug": "number-complement", + "description": "The complement of an integer is the integer you get when you flip all the 0's to 1's and all the 1's to 0's in its binary representation. Given an integer num, return its complement. ", + "category": [ + "Bit Manipulation" + ], + "complexity": "Easy", + "successrate": 66.7, + "totalsubmissions": 392862, + "totalaccepted": 261892, + "likes": 1954, + "dislikes": 105, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "num = 5", + "expected_output": "2", + "explanation": "The binary representation of 5 is 101 (no leading zero bits), and its complement is 010. So you need to output 2." + }, + { + "example_num": 2, + "expected_input": "num = 1", + "expected_output": "0", + "explanation": "The binary representation of 1 is 1 (no leading zero bits), and its complement is 0. So you need to output 0." + } + ], + "solution": "/**\n * @param {number} num\n * @return {number}\n */\nconst findComplement = function(num) {\n const toBin = num => (num >>> 0).toString(2)\n const flip = str => {\n let res = ''\n for(let c of str) res += (c === '1' ? '0' : '1')\n return res\n }\n return parseInt(flip(toBin(num)), 2)\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720bcb", + "questionid": 256, + "title": "Largest Palindrome Product", + "slug": "largest-palindrome-product", + "description": "Given an integer n, return the largest palindromic integer that can be represented as the product of two n-digits integers. Since the answer can be very large, return it modulo 1337. ", + "category": [ + "Math" + ], + "complexity": "Hard", + "successrate": 31.1, + "totalsubmissions": 65149, + "totalaccepted": 20274, + "likes": 123, + "dislikes": 1448, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 2", + "expected_output": "987\nExplanation: 99 x 91 = 9009, 9009 % 1337 = 987", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "n = 1", + "expected_output": "9", + "explanation": "" + } + ], + "solution": "/**\n * @param {number} n\n * @return {number}\n */\nfunction largestPalindrome(n) {\n if(n === 1) return 9\n let max = BigInt(10 ** n - 1), min = max / 10n + 1n\n for(let h = max; h >= min; h--) {\n let left = h, right = 0n\n for(let i = h; i !== 0n; ) {\n right = right * 10n + i % 10n\n i = i / 10n\n left *= 10n\n }\n let pal = left + right\n for(let i = max; i >= min; i--) {\n let j = pal / i\n if(j > i) break\n if(pal % i === 0n) return pal % 1337n\n }\n }\n}\n\n// another\n\n/**\n * @param {number} n\n * @return {number}\n */\nconst largestPalindrome = function (n) {\n if (n === 1) return 9\n for (let i = 2, limit = 9 * 10 ** (n - 1); i < limit; i++) {\n let left = 10 ** n - i\n let right = +('' + left).split('').reverse().join('')\n if (i ** 2 - 4 * right < 0) continue\n const tmp = (i ** 2 - 4 * right) ** 0.5\n if (tmp === Math.floor(tmp)) {\n return (\n (BigInt(right) + 10n ** BigInt(n) * (10n ** BigInt(n) - BigInt(i))) %\n 1337n\n )\n }\n }\n}\n\n// another\n\n/**\n * @param {number} n\n * @return {number}\n */\nconst largestPalindrome = function(n) {\n if (n === 1) {\n return 9\n } else if (n === 8) {\n return 475\n }\n let max = Math.pow(10, n)\n let min = Math.pow(10, n - 1)\n let ret = 0\n\n for (let i = max - 1; i > 0; i--) {\n ret = i * max + getReverse(i)\n for (let factor = ~~Math.sqrt(ret); factor < max; factor++) {\n if (ret % factor == 0 && ret / factor < max) {\n return ret % 1337\n }\n }\n }\n return -1\n}\n\nfunction getReverse(n) {\n let result = 0\n let num = n\n while (num > 0) {\n result = result * 10 + (num % 10)\n num = ~~(num / 10)\n }\n return result\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720b8e", + "questionid": 195, + "title": "Find K Pairs with Smallest Sums", + "slug": "find-k-pairs-with-smallest-sums", + "description": "You are given two integer arrays nums1 and nums2 sorted in ascending order and an integer k. Define a pair (u, v) which consists of one element from the first array and one element from the second array. Return the k pairs (u1, v1), (u2, v2), ..., (uk, vk) with the smallest sums. ", + "category": [ + "Array", + "Heap (Priority Queue)" + ], + "complexity": "Medium", + "successrate": 38.8, + "totalsubmissions": 430871, + "totalaccepted": 167230, + "likes": 2979, + "dislikes": 185, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums1 = [1,7,11], nums2 = [2,4,6], k = 3", + "expected_output": "[[1,2],[1,4],[1,6]]", + "explanation": "The first 3 pairs are returned from the sequence: [1,2],[1,4],[1,6],[7,2],[7,4],[11,2],[7,6],[11,4],[11,6]" + }, + { + "example_num": 2, + "expected_input": "nums1 = [1,1,2], nums2 = [1,2,3], k = 2", + "expected_output": "[[1,1],[1,1]]", + "explanation": "The first 2 pairs are returned from the sequence: [1,1],[1,1],[1,2],[2,1],[1,2],[2,2],[1,3],[1,3],[2,3]" + } + ], + "solution": "/**\n * @param {number[]} nums1\n * @param {number[]} nums2\n * @param {number} k\n * @return {number[][]}\n */\nconst kSmallestPairs = function (nums1, nums2, k) {\n const pq = new PriorityQueue((a, b) => a[0] + a[1] < b[0] + b[1])\n for(let i = 0; i < nums1.length && i < k; i++) {\n pq.push([nums1[i], nums2[0], 0])\n }\n const res = []\n while(k > 0 && !pq.isEmpty()) {\n const [e1, e2, e2i] = pq.pop()\n res.push([e1, e2])\n if(e2i + 1 < nums2.length) pq.push([e1, nums2[e2i + 1], e2i + 1])\n k--\n }\n \n return res\n}\n\nclass PriorityQueue {\n constructor(comparator = (a, b) => a > b) {\n this.heap = []\n this.top = 0\n this.comparator = comparator\n }\n size() {\n return this.heap.length\n }\n isEmpty() {\n return this.size() === 0\n }\n peek() {\n return this.heap[this.top]\n }\n push(...values) {\n values.forEach((value) => {\n this.heap.push(value)\n this.siftUp()\n })\n return this.size()\n }\n pop() {\n const poppedValue = this.peek()\n const bottom = this.size() - 1\n if (bottom > this.top) {\n this.swap(this.top, bottom)\n }\n this.heap.pop()\n this.siftDown()\n return poppedValue\n }\n replace(value) {\n const replacedValue = this.peek()\n this.heap[this.top] = value\n this.siftDown()\n return replacedValue\n }\n\n parent = (i) => ((i + 1) >>> 1) - 1\n left = (i) => (i << 1) + 1\n right = (i) => (i + 1) << 1\n greater = (i, j) => this.comparator(this.heap[i], this.heap[j])\n swap = (i, j) => ([this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]])\n siftUp = () => {\n let node = this.size() - 1\n while (node > this.top && this.greater(node, this.parent(node))) {\n this.swap(node, this.parent(node))\n node = this.parent(node)\n }\n }\n siftDown = () => {\n let node = this.top\n while (\n (this.left(node) < this.size() && this.greater(this.left(node), node)) ||\n (this.right(node) < this.size() && this.greater(this.right(node), node))\n ) {\n let maxChild =\n this.right(node) < this.size() &&\n this.greater(this.right(node), this.left(node))\n ? this.right(node)\n : this.left(node)\n this.swap(node, maxChild)\n node = maxChild\n }\n }\n}\n\n\n// another\n\n/**\n * @param {number[]} nums1\n * @param {number[]} nums2\n * @param {number} k\n * @return {number[][]}\n */\nconst kSmallestPairs = function(nums1, nums2, k) {\n let len1 = nums1.length,\n len2 = nums2.length\n let arr = Array(len1).fill(0),\n resList = []\n while (k-- > 0) {\n let min = Infinity,\n index = -1,\n lastj = Infinity\n for (let i = 0; i < len1; i++) {\n const j = arr[i]\n if (j < lastj && j < len2) {\n const sum = nums1[i] + nums2[j]\n if (sum < min) {\n min = sum\n index = i\n }\n lastj = j\n }\n }\n if (index == -1) {\n break\n }\n resList.push([nums1[index], nums2[arr[index]]])\n arr[index]++\n }\n return resList\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720b97", + "questionid": 204, + "title": "Perfect Rectangle", + "slug": "perfect-rectangle", + "description": "Given an array rectangles where rectangles[i] = [xi, yi, ai, bi] represents an axis-aligned rectangle. The bottom-left point of the rectangle is (xi, yi) and the top-right point of it is (ai, bi). Return true if all the rectangles together form an exact cover of a rectangular region. ", + "category": [ + "Array", + "Line Sweep" + ], + "complexity": "Hard", + "successrate": 32.1, + "totalsubmissions": 106171, + "totalaccepted": 34050, + "likes": 592, + "dislikes": 97, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "rectangles = [[1,1,3,3],[3,1,4,2],[3,2,4,4],[1,3,2,4],[2,3,3,4]]", + "expected_output": "true", + "explanation": "All 5 rectangles together form an exact cover of a rectangular region." + }, + { + "example_num": 2, + "expected_input": "rectangles = [[1,1,2,3],[1,3,2,4],[3,1,4,2],[3,2,4,4]]", + "expected_output": "false", + "explanation": "Because there is a gap between the two rectangular regions." + }, + { + "example_num": 3, + "expected_input": "rectangles = [[1,1,3,3],[3,1,4,2],[1,3,2,4],[2,2,4,4]]", + "expected_output": "false", + "explanation": "Because two of the rectangles overlap with each other." + } + ], + "solution": "/**\n * @param {number[][]} rectangles\n * @return {boolean}\n */\nconst isRectangleCover = function(rectangles) {\n let tls = new Set()\n let trs = new Set()\n let bls = new Set()\n let brs = new Set()\n let corner = (x, y) => `${x} ${y}`\n for (let [l, b, r, t] of rectangles) {\n let tl = corner(t, l)\n let tr = corner(t, r)\n let bl = corner(b, l)\n let br = corner(b, r)\n if (tls.has(tl) || trs.has(tr) || bls.has(bl) || brs.has(br)) return false\n if (!bls.delete(tl) && !trs.delete(tl)) tls.add(tl)\n if (!brs.delete(tr) && !tls.delete(tr)) trs.add(tr)\n if (!brs.delete(bl) && !tls.delete(bl)) bls.add(bl)\n if (!bls.delete(br) && !trs.delete(br)) brs.add(br)\n }\n return tls.size === 1 && trs.size === 1 && bls.size === 1 && brs.size === 1\n}\n\n// another\n\n/**\n * @param {number[][]} rectangles\n * @return {boolean}\n */\nvar isRectangleCover = function(rectangles) {\n const n = rectangles.length\n const rects = rectangles, set = new Set()\n let area = 0\n const p = (x, y) => `${x},${y}`\n let xmin = Infinity, xmax = -Infinity, ymin = Infinity, ymax = -Infinity\n for(const [x,y,a,b] of rects) {\n xmin = Math.min(xmin, x)\n xmax = Math.max(xmax, a)\n ymin = Math.min(ymin, y)\n ymax = Math.max(ymax, b)\n area += (a - x) * (b - y)\n const p0 = p(x,y), p1 = p(a,b),p2=p(x,b),p3=p(a,y)\n if(set.has(p0)) set.delete(p0)\n else set.add(p0)\n if(set.has(p1)) set.delete(p1)\n else set.add(p1)\n if(set.has(p2)) set.delete(p2)\n else set.add(p2)\n if(set.has(p3)) set.delete(p3)\n else set.add(p3)\n }\n if(set.size !== 4 || !set.has(p(xmin, ymin)) || !set.has(p(xmax, ymax)) || !set.has(p(xmin, ymax)) || !set.has(p(xmax, ymin)) ) return false\n return area === (xmax - xmin) * (ymax - ymin)\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720b9c", + "questionid": 209, + "title": "Remove K Digits", + "slug": "remove-k-digits", + "description": "Given string num representing a non-negative integer num, and an integer k, return the smallest possible integer after removing k digits from num. ", + "category": [ + "String", + "Stack", + "Greedy", + "Monotonic Stack" + ], + "complexity": "Medium", + "successrate": 30.5, + "totalsubmissions": 849382, + "totalaccepted": 258935, + "likes": 5963, + "dislikes": 249, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "num = "1432219", k = 3", + "expected_output": ""1219"", + "explanation": "Remove the three digits 4, 3, and 2 to form the new number 1219 which is the smallest." + }, + { + "example_num": 2, + "expected_input": "num = "10200", k = 1", + "expected_output": ""200"", + "explanation": "Remove the leading 1 and the number is 200. Note that the output must not contain leading zeroes." + }, + { + "example_num": 3, + "expected_input": "num = "10", k = 2", + "expected_output": ""0"", + "explanation": "Remove all the digits from the number and it is left with nothing which is 0." + } + ], + "solution": "/**\n * @param {string} num\n * @param {number} k\n * @return {string}\n */\nconst removeKdigits = function(num, k) {\n const digits = num.length - k;\n const stk = new Array(num.length);\n let top = 0;\n // k keeps track of how many characters we can remove\n // if the previous character in stk is larger than the current one\n // then removing it will get a smaller number\n // but we can only do so when k is larger than 0\n for (let i = 0; i < num.length; i++) {\n let c = num.charAt(i);\n while (top > 0 && stk[top - 1] > c && k > 0) {\n top -= 1;\n k -= 1;\n }\n stk[top++] = c;\n }\n // find the index of first non-zero digit\n let idx = 0;\n while (idx < digits && stk[idx] === \"0\") idx++;\n return idx === digits ? \"0\" : stk.slice(idx, digits + idx).join(\"\");\n};\n\n\n// another\n\n/**\n * @param {string} num\n * @param {number} k\n * @return {string}\n */\nconst removeKdigits = function(num, k) {\n const n = num.length, stack = []\n if(n === k) return '0'\n let i = 0\n while(i < n) {\n while(k > 0 && stack.length && stack[stack.length - 1] > num[i]) {\n k--\n stack.pop()\n }\n stack.push(num[i++])\n }\n while(k-- > 0) stack.pop()\n while(stack[0] === '0') stack.shift()\n return stack.length ? stack.join('') : '0'\n};\n\n// another\n\n/**\n * @param {string} num\n * @param {number} k\n * @return {string}\n */\nconst removeKdigits = function(num, k) {\n const n = num.length, stack = []\n for(let i = 0; i < n; i++) {\n const ch = num[i]\n while(stack.length && k > 0 && ch < stack[stack.length - 1]) {\n stack.pop()\n k--\n }\n stack.push(ch)\n }\n while(k > 0) {\n stack.pop()\n k--\n }\n while(stack[0] === '0') stack.shift()\n return stack.length ? stack.join('') : '0'\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720ba7", + "questionid": 220, + "title": "Pacific Atlantic Water Flow", + "slug": "pacific-atlantic-water-flow", + "description": "There is an m x n rectangular island that borders both the Pacific Ocean and Atlantic Ocean. The Pacific Ocean touches the island's left and top edges, and the Atlantic Ocean touches the island's right and bottom edges. The island is partitioned into a grid of square cells. You are given an m x n integer matrix heights where heights[r][c] represents the height above sea level of the cell at coordinate (r, c). The island receives a lot of rain, and the rain water can flow to neighboring cells directly north, south, east, and west if the neighboring cell's height is less than or equal to the current cell's height. Water can flow from any cell adjacent to an ocean into the ocean. Return a 2D list of grid coordinates result where result[i] = [ri, ci] denotes that rain water can flow from cell (ri, ci) to both the Pacific and Atlantic oceans. ", + "category": [ + "Array", + "Depth-First Search", + "Breadth-First Search", + "Matrix" + ], + "complexity": "Medium", + "successrate": 48.9, + "totalsubmissions": 392980, + "totalaccepted": 192213, + "likes": 3494, + "dislikes": 799, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "heights = [[1,2,2,3,5],[3,2,3,4,4],[2,4,5,3,1],[6,7,1,4,5],[5,1,1,2,4]]", + "expected_output": "[[0,4],[1,3],[1,4],[2,2],[3,0],[3,1],[4,0]]", + "explanation": "The following cells can flow to the Pacific and Atlantic oceans, as shown below:\n[0,4]: [0,4] -> Pacific Ocean \n  [0,4] -> Atlantic Ocean\n[1,3]: [1,3] -> [0,3] -> Pacific Ocean \n  [1,3] -> [1,4] -> Atlantic Ocean\n[1,4]: [1,4] -> [1,3] -> [0,3] -> Pacific Ocean \n  [1,4] -> Atlantic Ocean\n[2,2]: [2,2] -> [1,2] -> [0,2] -> Pacific Ocean \n  [2,2] -> [2,3] -> [2,4] -> Atlantic Ocean\n[3,0]: [3,0] -> Pacific Ocean \n  [3,0] -> [4,0] -> Atlantic Ocean\n[3,1]: [3,1] -> [3,0] -> Pacific Ocean \n  [3,1] -> [4,1] -> Atlantic Ocean\n[4,0]: [4,0] -> Pacific Ocean \n [4,0] -> Atlantic Ocean\nNote that there are other possible paths for these cells to flow to the Pacific and Atlantic oceans." + }, + { + "example_num": 2, + "expected_input": "heights = [[1]]", + "expected_output": "[[0,0]]", + "explanation": "The water can flow from the only cell to the Pacific and Atlantic oceans." + } + ], + "solution": "/**\n * @param {number[][]} matrix\n * @return {number[][]}\n */\nconst pacificAtlantic = function(matrix) {\n const res = []\n if (!matrix || matrix.length === 0 || matrix[0].length === 0) return res\n const rows = matrix.length\n const cols = matrix[0].length\n const dirs = [[-1, 0], [1, 0], [0, 1], [0, -1]]\n const pacific = Array.from({ length: rows }, () => new Array(cols).fill(false))\n const atlantic = Array.from({ length: rows }, () => new Array(cols).fill(false))\n for (let y = 0; y < rows; y++) {\n helper(0, y, pacific, -1, matrix, cols, rows, dirs)\n helper(cols - 1, y, atlantic, -1, matrix, cols, rows, dirs)\n }\n for (let x = 0; x < cols; x++) {\n helper(x, 0, pacific, -1, matrix, cols, rows, dirs)\n helper(x, rows - 1, atlantic, -1, matrix, cols, rows, dirs)\n }\n\n for (let y = 0; y < rows; y++) {\n for (let x = 0; x < cols; x++) {\n if (pacific[y][x] && atlantic[y][x]) {\n res.push([y, x])\n }\n }\n }\n return res\n}\n\nfunction helper(x, y, visited, height, matrix, cols, rows, dirs) {\n if (x < 0 || x >= cols || y < 0 || y >= rows || visited[y][x] || matrix[y][x] < height) return\n visited[y][x] = true\n for (let dir of dirs)\n helper(x + dir[0], y + dir[1], visited, matrix[y][x], matrix, cols, rows, dirs)\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720ba8", + "questionid": 221, + "title": "Battleships in a Board", + "slug": "battleships-in-a-board", + "description": "Given an m x n matrix board where each cell is a battleship 'X' or empty '.', return the number of the battleships on board. Battleships can only be placed horizontally or vertically on board. In other words, they can only be made of the shape 1 x k (1 row, k columns) or k x 1 (k rows, 1 column), where k can be of any size. At least one horizontal or vertical cell separates between two battleships (i.e., there are no adjacent battleships). ", + "category": [ + "Array", + "Depth-First Search", + "Matrix" + ], + "complexity": "Medium", + "successrate": 73.4, + "totalsubmissions": 195795, + "totalaccepted": 143656, + "likes": 1452, + "dislikes": 733, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "board = [["X",".",".","X"],[".",".",".","X"],[".",".",".","X"]]", + "expected_output": "2", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "board = [["."]]", + "expected_output": "0", + "explanation": "" + } + ], + "solution": null + }, + { + "_id": "66f925ddfdfb8e1665720bab", + "questionid": 224, + "title": "Longest Repeating Character Replacement", + "slug": "longest-repeating-character-replacement", + "description": "You are given a string s and an integer k. You can choose any character of the string and change it to any other uppercase English character. You can perform this operation at most k times. Return the length of the longest substring containing the same letter you can get after performing the above operations. ", + "category": [ + "Hash Table", + "String", + "Sliding Window" + ], + "complexity": "Medium", + "successrate": 50.7, + "totalsubmissions": 406149, + "totalaccepted": 206085, + "likes": 4188, + "dislikes": 170, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "ABAB", k = 2", + "expected_output": "4", + "explanation": "Replace the two 'A's with two 'B's or vice versa." + }, + { + "example_num": 2, + "expected_input": "s = "AABABBA", k = 1", + "expected_output": "4", + "explanation": "Replace the one 'A' in the middle with 'B' and form "AABBBBA".\nThe substring "BBBB" has the longest repeating letters, which is 4.\nThere may exists other ways to achieve this answer too." + } + ], + "solution": "/**\n * @param {string} s\n * @param {number} k\n * @return {number}\n */\nconst characterReplacement = function(s, k) {\n const len = s.length;\n const count = Array(26).fill(0);\n let start = 0,\n maxCount = 0,\n maxLength = 0;\n const ca = \"A\".charCodeAt(0);\n for (let end = 0; end < len; end++) {\n maxCount = Math.max(maxCount, ++count[s.charCodeAt(end) - ca]);\n if (end - start + 1 - maxCount > k) {\n count[s.charCodeAt(start) - ca]--;\n start++;\n }\n maxLength = Math.max(maxLength, end - start + 1);\n }\n return maxLength;\n};\n\nconsole.log(characterReplacement(\"ABAB\", 2));\nconsole.log(characterReplacement(\"AABABBA\", 1));\n\n\n// another\n\n/**\n * @param {string} s\n * @param {number} k\n * @return {number}\n */\nconst characterReplacement = function (s, k) {\n const freq = Array(26).fill(0),\n n = s.length,\n { max } = Math,\n A = 'A'.charCodeAt(0)\n let res = 0,\n l = 0,\n r = 0,\n maxFreq = 0\n while (r < n) {\n maxFreq = max(maxFreq, ++freq[s.charCodeAt(r) - A])\n if (r - l + 1 - maxFreq > k) {\n freq[s.charCodeAt(l) - A]--\n l++\n }\n res = max(res, r - l + 1)\n r++\n }\n\n return res\n}\n\n" + }, + { + "_id": "66f925ddfdfb8e1665720bae", + "questionid": 227, + "title": "Non-overlapping Intervals", + "slug": "non-overlapping-intervals", + "description": "Given an array of intervals intervals where intervals[i] = [starti, endi], return the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping. ", + "category": [ + "Array", + "Dynamic Programming", + "Greedy", + "Sorting" + ], + "complexity": "Medium", + "successrate": 48.1, + "totalsubmissions": 494769, + "totalaccepted": 238037, + "likes": 3819, + "dislikes": 111, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "intervals = [[1,2],[2,3],[3,4],[1,3]]", + "expected_output": "1", + "explanation": "[1,3] can be removed and the rest of the intervals are non-overlapping." + }, + { + "example_num": 2, + "expected_input": "intervals = [[1,2],[1,2],[1,2]]", + "expected_output": "2", + "explanation": "You need to remove two [1,2] to make the rest of the intervals non-overlapping." + }, + { + "example_num": 3, + "expected_input": "intervals = [[1,2],[2,3]]", + "expected_output": "0", + "explanation": "You don't need to remove any of the intervals since they're already non-overlapping." + } + ], + "solution": "/**\n * @param {number[][]} intervals\n * @return {number}\n */\nconst eraseOverlapIntervals = function(intervals) {\n if(intervals == null || intervals.length === 0) return 0\n intervals.sort((a, b) => a[1] - b[1])\n let res = 1, end = intervals[0][1]\n const len = intervals.length\n for(let i = 1; i < len; i++) {\n if(intervals[i][0] >= end) {\n end = intervals[i][1]\n res++\n }\n }\n \n return len - res\n};\n\n// another\n\n/**\n * Definition for an interval.\n * function Interval(start, end) {\n * this.start = start;\n * this.end = end;\n * }\n */\n/**\n * @param {Interval[]} intervals\n * @return {number}\n */\nconst eraseOverlapIntervals = function(intervals) {\n intervals.sort((a, b) => a.end - b.end)\n let count = 0\n let end = Number.MIN_SAFE_INTEGER\n const len = intervals.length\n for(let el of intervals) {\n if(el.start >= end) {\n end = el.end\n count++\n }\n }\n return len - count\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720bb2", + "questionid": 231, + "title": "K-th Smallest in Lexicographical Order", + "slug": "k-th-smallest-in-lexicographical-order", + "description": "Given two integers n and k, return the kth lexicographically smallest integer in the range [1, n]. ", + "category": [ + "Trie" + ], + "complexity": "Hard", + "successrate": 30.5, + "totalsubmissions": 57068, + "totalaccepted": 17419, + "likes": 552, + "dislikes": 73, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 13, k = 2", + "expected_output": "10", + "explanation": "The lexicographical order is [1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9], so the second smallest number is 10." + }, + { + "example_num": 2, + "expected_input": "n = 1, k = 1", + "expected_output": "1", + "explanation": "" + } + ], + "solution": "/**\n * @param {number} n\n * @param {number} k\n * @return {number}\n */\nconst findKthNumber = function (n, k) {\n let cur = 1\n k = k - 1\n while(k > 0) {\n const num = calc(cur)\n if(num <= k) {\n cur++\n k -= num\n } else {\n k--\n cur *= 10\n }\n }\n return cur\n \n function calc(cur) {\n let total = 0\n let nxt = cur + 1\n while(cur <= n) {\n total += Math.min(n - cur + 1, nxt - cur)\n nxt *= 10\n cur *= 10\n }\n \n return total\n }\n}\n\n// another\n\n/**\n * @param {number} n\n * @param {number} k\n * @return {number}\n */\nconst findKthNumber = function (n, k) {\n let curr = 1\n k = k - 1\n while (k > 0) {\n let steps = calSteps(n, curr, curr + 1)\n if (steps <= k) {\n curr += 1\n k -= steps\n } else {\n curr *= 10\n k -= 1\n }\n }\n return curr\n\n function calSteps(n, n1, n2) {\n let steps = 0\n while (n1 <= n) {\n steps += Math.min(n + 1, n2) - n1\n n1 *= 10\n n2 *= 10\n }\n return steps\n }\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720bb4", + "questionid": 233, + "title": "Find All Duplicates in an Array", + "slug": "find-all-duplicates-in-an-array", + "description": "Given an integer array nums of length n where all the integers of nums are in the range [1, n] and each integer appears once or twice, return an array of all the integers that appears twice. You must write an algorithm that runs in\u00a0O(n)\u00a0time and uses only constant extra space. ", + "category": [ + "Array", + "Hash Table" + ], + "complexity": "Medium", + "successrate": 72.3, + "totalsubmissions": 540996, + "totalaccepted": 391236, + "likes": 5995, + "dislikes": 247, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [4,3,2,7,8,2,3,1]", + "expected_output": "[2,3]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "nums = [1,1,2]", + "expected_output": "[1]", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "nums = [1]", + "expected_output": "[]", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} nums\n * @return {number[]}\n */\n\nconst findDuplicates = function(nums) {\n if (nums === null || nums.length <= 1) {\n return [];\n }\n\n let dup = [];\n for (let i = 0, n = nums.length; i < n; i++) {\n let next = Math.abs(nums[i]);\n nums[next - 1] < 0 ? dup.push(next) : (nums[next - 1] = -nums[next - 1]);\n }\n\n return dup;\n};\n\nconsole.log(findDuplicates([4, 3, 2, 7, 8, 2, 3, 1]));\nconsole.log(findDuplicates([10, 2, 5, 10, 9, 1, 1, 4, 3, 7]));\n\n// another\n\n/**\n * @param {number[]} nums\n * @return {number[]}\n */\nconst findDuplicates = function(nums) {\n const res = []\n for(let i = 0, len = nums.length; i < len; i++) {\n const idx = Math.abs(nums[i]) - 1\n if(nums[idx] < 0) res.push(idx + 1)\n nums[idx] = -nums[idx]\n }\n return res;\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720bb7", + "questionid": 236, + "title": "Number of Boomerangs", + "slug": "number-of-boomerangs", + "description": "You are given n points in the plane that are all distinct, where points[i] = [xi, yi]. A boomerang is a tuple of points (i, j, k) such that the distance between i and j equals the distance between i and k (the order of the tuple matters). Return the number of boomerangs. ", + "category": [ + "Array", + "Hash Table", + "Math" + ], + "complexity": "Medium", + "successrate": 54.1, + "totalsubmissions": 156588, + "totalaccepted": 84744, + "likes": 611, + "dislikes": 881, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "points = [[0,0],[1,0],[2,0]]", + "expected_output": "2", + "explanation": "The two boomerangs are [[1,0],[0,0],[2,0]] and [[1,0],[2,0],[0,0]]." + }, + { + "example_num": 2, + "expected_input": "points = [[1,1],[2,2],[3,3]]", + "expected_output": "2", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "points = [[1,1]]", + "expected_output": "0", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[][]} points\n * @return {number}\n */\nconst numberOfBoomerangs = function(points) {\n const m = new Map()\n const len = points.length\n let res = 0\n for(let i = 0; i < len; i++) {\n for(let j = 0; j < len; j++) {\n if(i === j) continue\n const d = dis(points[i], points[j])\n if(!m.has(d)) m.set(d, 0)\n m.set(d, m.get(d) + 1)\n }\n for(let v of m.values()) {\n res += v * (v - 1)\n }\n m.clear()\n }\n return res\n};\n\nfunction dis(a, b) {\n return (a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720bc6", + "questionid": 251, + "title": "Matchsticks to Square", + "slug": "matchsticks-to-square", + "description": "You are given an integer array matchsticks where matchsticks[i] is the length of the ith matchstick. You want to use all the matchsticks to make one square. You should not break any stick, but you can link them up, and each matchstick must be used exactly one time. Return true if you can make this square and false otherwise. ", + "category": [ + "Array", + "Dynamic Programming", + "Backtracking", + "Bit Manipulation", + "Bitmask" + ], + "complexity": "Medium", + "successrate": 40.3, + "totalsubmissions": 188482, + "totalaccepted": 76024, + "likes": 1571, + "dislikes": 121, + "hints": "Treat the matchsticks as an array. Can we split the array into 4 equal halves? Every matchstick can belong to either of the 4 sides. We don't know which one. Maybe try out all options! For every matchstick, we have to try out each of the 4 options i.e. which side it can belong to. We can make use of recursion for this. We don't really need to keep track of which matchsticks belong to a particular side during recursion. We just need to keep track of the length of each of the 4 sides. When all matchsticks have been used we simply need to see the length of all 4 sides. If they're equal, we have a square on our hands!", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "matchsticks = [1,1,2,2,2]", + "expected_output": "true", + "explanation": "You can form a square with length 2, one side of the square came two sticks with length 1." + }, + { + "example_num": 2, + "expected_input": "matchsticks = [3,3,3,3,4]", + "expected_output": "false", + "explanation": "You cannot find a way to form a square with all the matchsticks." + } + ], + "solution": "/**\n * @param {number[]} nums\n * @return {boolean}\n */\nconst makesquare = function(nums) {\n if (nums == null || nums.length < 4) return false\n const sum = nums.reduce((ac, el) => ac + el, 0)\n if (sum % 4 !== 0) return false\n nums.sort((a, b) => b - a)\n return dfs(nums, new Array(4).fill(0), 0, sum / 4)\n}\n\nfunction dfs(nums, arr, idx, target) {\n if (idx === nums.length) {\n return true\n }\n for (let i = 0; i < 4; i++) {\n if (arr[i] + nums[idx] > target || (i > 0 && arr[i] === arr[i - 1]))\n continue\n arr[i] += nums[idx]\n if (dfs(nums, arr, idx + 1, target)) return true\n arr[i] -= nums[idx]\n }\n return false\n}\n\n\n\n// another\n\n/**\n * @param {number[]} nums\n * @return {boolean}\n */\nconst makesquare = function(nums) {\n if (nums.length == 0) return false\n const edge = nums.reduce((accum, val) => accum + val) / 4\n nums.sort((val1, val2) => val2 - val1)\n if (edge !== Math.floor(edge)) return false\n const findEdge = function(target) {\n if (target <= 0) return target === 0\n let newNums = []\n while (nums.length) {\n let item = nums.shift()\n if (findEdge(target - item)) {\n nums = newNums.concat(nums)\n return true\n }\n newNums.push(item)\n }\n nums = newNums\n return false\n }\n let count = 4\n while (count) {\n if (!findEdge(edge)) return false\n count--\n }\n return true\n}\n\n" + }, + { + "_id": "66f925ddfdfb8e1665720b90", + "questionid": 197, + "title": "Combination Sum IV", + "slug": "combination-sum-iv", + "description": "Given an array of distinct integers nums and a target integer target, return the number of possible combinations that add up to\u00a0target. The test cases are generated so that the answer can fit in a 32-bit integer. ", + "category": [ + "Array", + "Dynamic Programming" + ], + "complexity": "Medium", + "successrate": 49.3, + "totalsubmissions": 482241, + "totalaccepted": 237874, + "likes": 3333, + "dislikes": 383, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,2,3], target = 4", + "expected_output": "7", + "explanation": "The possible combination ways are:\n(1, 1, 1, 1)\n(1, 1, 2)\n(1, 2, 1)\n(1, 3)\n(2, 1, 1)\n(2, 2)\n(3, 1)\nNote that different sequences are counted as different combinations." + }, + { + "example_num": 2, + "expected_input": "nums = [9], target = 3", + "expected_output": "0", + "explanation": "" + } + ], + "solution": null + }, + { + "_id": "66f925ddfdfb8e1665720b91", + "questionid": 198, + "title": "Kth Smallest Element in a Sorted Matrix", + "slug": "kth-smallest-element-in-a-sorted-matrix", + "description": "Given an n x n matrix where each of the rows and columns is sorted in ascending order, return the kth smallest element in the matrix. Note that it is the kth smallest element in the sorted order, not the kth distinct element. You must find a solution with a memory complexity better than O(n2). ", + "category": [ + "Array", + "Binary Search", + "Sorting", + "Heap (Priority Queue)", + "Matrix" + ], + "complexity": "Medium", + "successrate": 59.6, + "totalsubmissions": 632411, + "totalaccepted": 376832, + "likes": 5707, + "dislikes": 236, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "matrix = [[1,5,9],[10,11,13],[12,13,15]], k = 8", + "expected_output": "13", + "explanation": "The elements in the matrix are [1,5,9,10,11,12,13,13,15], and the 8th smallest number is 13" + }, + { + "example_num": 2, + "expected_input": "matrix = [[-5]], k = 1", + "expected_output": "-5", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[][]} matrix\n * @param {number} k\n * @return {number}\n */\nconst kthSmallest = function(matrix, k) {\n let lo = matrix[0][0],\n hi = matrix[matrix.length - 1][matrix[0].length - 1] + 1; //[lo, hi)\n while (lo < hi) {\n let mid = Math.floor(lo + (hi - lo) / 2);\n let count = 0,\n j = matrix[0].length - 1;\n for (let i = 0; i < matrix.length; i++) {\n while (j >= 0 && matrix[i][j] > mid) j--;\n count += j + 1;\n }\n if (count < k) lo = mid + 1;\n else hi = mid;\n }\n return lo;\n};\n\nconsole.log(kthSmallest([[-5]], 1));\nconsole.log(kthSmallest([[1, 2], [1, 3]], 4));\nconsole.log(kthSmallest([[1, 5, 9], [10, 11, 13], [12, 13, 15]], 8));\nconsole.log(kthSmallest([[1, 2], [1, 3]], 2));\n" + }, + { + "_id": "66f925ddfdfb8e1665720b94", + "questionid": 201, + "title": "Lexicographical Numbers", + "slug": "lexicographical-numbers", + "description": "Given an integer n, return all the numbers in the range [1, n] sorted in lexicographical order. You must write an algorithm that runs in\u00a0O(n)\u00a0time and uses O(1) extra space. ", + "category": [ + "Depth-First Search", + "Trie" + ], + "complexity": "Medium", + "successrate": 58.7, + "totalsubmissions": 140350, + "totalaccepted": 82427, + "likes": 1197, + "dislikes": 113, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 13", + "expected_output": "[1,10,11,12,13,2,3,4,5,6,7,8,9]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "n = 2", + "expected_output": "[1,2]", + "explanation": "" + } + ], + "solution": "/**\n * @param {number} n\n * @return {number[]}\n */\nconst lexicalOrder = function(n) {\n const res = []\n for(let i = 1; i < 10; i++) {\n dfs(i)\n }\n \n return res\n \n function dfs(num) {\n if(num > n) return\n res.push(num)\n for(let i = 0; i < 10; i++) {\n const tmp = num * 10 + i\n if(tmp > n) return\n dfs(tmp)\n }\n }\n};\n\n// another\n\n/**\n * @param {number} n\n * @return {number[]}\n */\nconst lexicalOrder = function(n) {\n const result = []\n for (let i = 1; i < 10; i++) {\n dfs(i)\n }\n function dfs(n) {\n if (n <= num) result.push(n)\n if (10 * n <= num) {\n for (let j = 0; j < 10; j++) {\n dfs(10 * n + j)\n }\n }\n }\n return result\n}\n\n// another\n\nconst lexicalOrder = function(n) {\n function getNumberByOrder(start, end) {\n for (let i = start; i <= end; i++) {\n if (i > n) {\n break\n }\n res.push(i)\n getNumberByOrder(i * 10, i * 10 + 9)\n }\n }\n const res = []\n getNumberByOrder(1, 9)\n return res\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720b99", + "questionid": 206, + "title": "Longest Substring with At Least K Repeating Characters", + "slug": "longest-substring-with-at-least-k-repeating-characters", + "description": "Given a string s and an integer k, return the length of the longest substring of s such that the frequency of each character in this substring is greater than or equal to k. ", + "category": [ + "Hash Table", + "String", + "Divide and Conquer", + "Sliding Window" + ], + "complexity": "Medium", + "successrate": 44.5, + "totalsubmissions": 345377, + "totalaccepted": 153849, + "likes": 3853, + "dislikes": 321, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "aaabb", k = 3", + "expected_output": "3", + "explanation": "The longest substring is "aaa", as 'a' is repeated 3 times." + }, + { + "example_num": 2, + "expected_input": "s = "ababbc", k = 2", + "expected_output": "5", + "explanation": "The longest substring is "ababb", as 'a' is repeated 2 times and 'b' is repeated 3 times." + } + ], + "solution": "/**\n * @param {string} s\n * @param {number} k\n * @return {number}\n */\nconst longestSubstring = function (s, k) {\n if (s == null || s.length === 0) return 0\n const chars = new Array(26).fill(0)\n const aCode = 'a'.charCodeAt(0)\n for (let i = 0; i < s.length; i++) chars[s.charCodeAt(i) - aCode] += 1\n let flag = true\n for (let i = 0; i < chars.length; i++) {\n if (chars[i] < k && chars[i] > 0) flag = false\n }\n if (flag === true) {\n return s.length\n }\n let result = 0\n let start = 0\n let cur = 0\n while (cur < s.length) {\n if (chars[s.charCodeAt(cur) - aCode] < k) {\n result = Math.max(result, longestSubstring(s.slice(start, cur), k))\n start = cur + 1\n }\n cur++\n }\n result = Math.max(result, longestSubstring(s.slice(start), k))\n return result\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720b9d", + "questionid": 210, + "title": "Frog Jump", + "slug": "frog-jump", + "description": "A frog is crossing a river. The river is divided into some number of units, and at each unit, there may or may not exist a stone. The frog can jump on a stone, but it must not jump into the water. Given a list of stones' positions (in units) in sorted ascending order, determine if the frog can cross the river by landing on the last stone. Initially, the frog is on the first stone and assumes the first jump must be 1 unit. If the frog's last jump was k units, its next jump must be either k - 1, k, or k + 1 units. The frog can only jump in the forward direction. ", + "category": [ + "Array", + "Dynamic Programming" + ], + "complexity": "Hard", + "successrate": 42.9, + "totalsubmissions": 353218, + "totalaccepted": 151515, + "likes": 2448, + "dislikes": 160, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "stones = [0,1,3,5,6,8,12,17]", + "expected_output": "true", + "explanation": "The frog can jump to the last stone by jumping 1 unit to the 2nd stone, then 2 units to the 3rd stone, then 2 units to the 4th stone, then 3 units to the 6th stone, 4 units to the 7th stone, and 5 units to the 8th stone." + }, + { + "example_num": 2, + "expected_input": "stones = [0,1,2,3,4,8,9,11]", + "expected_output": "false", + "explanation": "There is no way to jump to the last stone as the gap between the 5th and 6th stone is too large." + } + ], + "solution": "/**\n * @param {number[]} stones\n * @return {boolean}\n */\nconst canCross = function(stones) {\n for (let i = 3; i < stones.length; i++) {\n if (stones[i] > stones[i - 1] * 2) {\n return false\n }\n }\n const count = new Set(stones)\n const lastStone = stones[stones.length - 1]\n const position = [0]\n const jump = [0]\n while (position.length > 0) {\n const nextPosition = position.pop()\n const nextDistance = jump.pop()\n for (let i = nextDistance - 1; i <= nextDistance + 1; i++) {\n if (i <= 0) {\n continue\n }\n const nextStone = nextPosition + i\n if (nextStone == lastStone) {\n return true\n } else if (count.has(nextStone)) {\n position.push(nextStone)\n jump.push(i)\n }\n }\n }\n return false\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720b9e", + "questionid": 211, + "title": "Sum of Left Leaves", + "slug": "sum-of-left-leaves", + "description": "Given the root of a binary tree, return the sum of all left leaves. A leaf is a node with no children. A left leaf is a leaf that is the left child of another node. ", + "category": [ + "Tree", + "Depth-First Search", + "Breadth-First Search", + "Binary Tree" + ], + "complexity": "Easy", + "successrate": 55, + "totalsubmissions": 621755, + "totalaccepted": 341893, + "likes": 3236, + "dislikes": 244, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [3,9,20,null,null,15,7]", + "expected_output": "24", + "explanation": "There are two left leaves in the binary tree, with values 9 and 15 respectively." + }, + { + "example_num": 2, + "expected_input": "root = [1]", + "expected_output": "0", + "explanation": "" + } + ], + "solution": "/**\n * Definition for a binary tree node.\n * function TreeNode(val) {\n * this.val = val;\n * this.left = this.right = null;\n * }\n */\n/**\n * @param {TreeNode} root\n * @return {number}\n */\nconst sumOfLeftLeaves = function(root) {\n if(root == null) return 0\n let res = 0\n function dfs(node, side) {\n if(node === null) return\n if(node.left === null && node.right === null) {\n if(side === 'left') res += node.val\n return\n }\n dfs(node.left, 'left')\n dfs(node.right, 'right')\n }\n dfs(root.left, 'left')\n dfs(root.right, 'right')\n\n return res\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720b9f", + "questionid": 212, + "title": "Queue Reconstruction by Height", + "slug": "queue-reconstruction-by-height", + "description": "You are given an array of people, people, which are the attributes of some people in a queue (not necessarily in order). Each people[i] = [hi, ki] represents the ith person of height hi with exactly ki other people in front who have a height greater than or equal to hi. Reconstruct and return the queue that is represented by the input array people. The returned queue should be formatted as an array queue, where queue[j] = [hj, kj] is the attributes of the jth person in the queue (queue[0] is the person at the front of the queue). ", + "category": [ + "Array", + "Greedy", + "Binary Indexed Tree", + "Segment Tree", + "Sorting" + ], + "complexity": "Medium", + "successrate": 70.1, + "totalsubmissions": 314990, + "totalaccepted": 220723, + "likes": 4787, + "dislikes": 511, + "hints": "What can you say about the position of the shortest person? \r\nIf the position of the shortest person is i, how many people would be in front of the shortest person? Once you fix the position of the shortest person, what can you say about the position of the second shortest person?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "people = [[7,0],[4,4],[7,1],[5,0],[6,1],[5,2]]", + "expected_output": "[[5,0],[7,0],[5,2],[6,1],[4,4],[7,1]]", + "explanation": "Person 0 has height 5 with no other people taller or the same height in front.\nPerson 1 has height 7 with no other people taller or the same height in front.\nPerson 2 has height 5 with two persons taller or the same height in front, which is person 0 and 1.\nPerson 3 has height 6 with one person taller or the same height in front, which is person 1.\nPerson 4 has height 4 with four people taller or the same height in front, which are people 0, 1, 2, and 3.\nPerson 5 has height 7 with one person taller or the same height in front, which is person 1.\nHence [[5,0],[7,0],[5,2],[6,1],[4,4],[7,1]] is the reconstructed queue." + }, + { + "example_num": 2, + "expected_input": "people = [[6,0],[5,0],[4,0],[3,2],[2,2],[1,4]]", + "expected_output": "[[4,0],[5,0],[2,2],[3,2],[1,4],[6,0]]", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[][]} people\n * @return {number[][]}\n */\nconst reconstructQueue = function (people) {\n const h = 0\n const k = 1\n people.sort((a, b) => (a[h] == b[h] ? a[k] - b[k] : b[h] - a[h]))\n let queue = []\n for (let person of people) {\n queue.splice(person[k], 0, person)\n }\n return queue\n}\n\n// another\n\n/**\n * @param {number[][]} people\n * @return {number[][]}\n */\nconst reconstructQueue = function(people) {\n if (!people) return [];\n const peopledct = {};\n let height = [];\n const res = [];\n people.forEach((el, idx) => {\n if (peopledct.hasOwnProperty(el[0])) {\n peopledct[el[0]].push([el[1], idx]);\n } else {\n peopledct[el[0]] = [[el[1], idx]];\n height.push(el[0]);\n }\n });\n height = height.sort((a, b) => b - a);\n\n for (let i = 0; i < height.length; i++) {\n peopledct[height[i]] = peopledct[height[i]].sort((a, b) => a[0] - b[0]);\n for (el of peopledct[height[i]]) {\n res.splice(el[0], 0, people[el[1]]);\n }\n }\n return res;\n};\n\nconsole.log(reconstructQueue([[7, 0], [4, 4], [7, 1], [5, 0], [6, 1], [5, 2]]));\n" + }, + { + "_id": "66f925ddfdfb8e1665720ba0", + "questionid": 213, + "title": "Trapping Rain Water II", + "slug": "trapping-rain-water-ii", + "description": "Given an m x n integer matrix heightMap representing the height of each unit cell in a 2D elevation map, return the volume of water it can trap after raining. ", + "category": [ + "Array", + "Breadth-First Search", + "Heap (Priority Queue)", + "Matrix" + ], + "complexity": "Hard", + "successrate": 46.9, + "totalsubmissions": 145379, + "totalaccepted": 68250, + "likes": 2670, + "dislikes": 60, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "heightMap = [[1,4,3,1,3,2],[3,2,1,3,2,4],[2,3,3,2,3,1]]", + "expected_output": "4", + "explanation": "After the rain, water is trapped between the blocks.\nWe have two small ponds 1 and 3 units trapped.\nThe total volume of water trapped is 4." + }, + { + "example_num": 2, + "expected_input": "heightMap = [[3,3,3,3,3],[3,2,2,2,3],[3,2,1,2,3],[3,2,2,2,3],[3,3,3,3,3]]", + "expected_output": "10", + "explanation": "" + } + ], + "solution": "class PQ {\n constructor(comparator = (a, b) => a > b) {\n this.heap = []\n this.top = 0\n this.comparator = comparator\n }\n size() {\n return this.heap.length\n }\n isEmpty() {\n return this.size() === 0\n }\n peek() {\n return this.heap[this.top]\n }\n push(...values) {\n values.forEach((value) => {\n this.heap.push(value)\n this.siftUp()\n })\n return this.size()\n }\n pop() {\n const poppedValue = this.peek()\n const bottom = this.size() - 1\n if (bottom > this.top) {\n this.swap(this.top, bottom)\n }\n this.heap.pop()\n this.siftDown()\n return poppedValue\n }\n replace(value) {\n const replacedValue = this.peek()\n this.heap[this.top] = value\n this.siftDown()\n return replacedValue\n }\n\n parent = (i) => ((i + 1) >>> 1) - 1\n left = (i) => (i << 1) + 1\n right = (i) => (i + 1) << 1\n greater = (i, j) => this.comparator(this.heap[i], this.heap[j])\n swap = (i, j) => ([this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]])\n siftUp = () => {\n let node = this.size() - 1\n while (node > this.top && this.greater(node, this.parent(node))) {\n this.swap(node, this.parent(node))\n node = this.parent(node)\n }\n }\n siftDown = () => {\n let node = this.top\n while (\n (this.left(node) < this.size() && this.greater(this.left(node), node)) ||\n (this.right(node) < this.size() && this.greater(this.right(node), node))\n ) {\n let maxChild =\n this.right(node) < this.size() &&\n this.greater(this.right(node), this.left(node))\n ? this.right(node)\n : this.left(node)\n this.swap(node, maxChild)\n node = maxChild\n }\n }\n}\n/**\n * @param {number[][]} heightMap\n * @return {number}\n */\nconst trapRainWater = function(heightMap) {\n const pq = new PQ((a, b) => a[1] < b[1])\n const m = heightMap.length, n = heightMap[0].length\n const visited = Array.from({ length: m }, () => Array(n).fill(false))\n for(let i = 0; i < m; i++) {\n visited[i][0] = visited[i][n - 1] = true\n pq.push([[i, 0], heightMap[i][0]])\n pq.push([[i, n - 1], heightMap[i][n - 1]])\n }\n for(let j = 0; j < n; j++) {\n visited[0][j] = visited[m - 1][j] = true\n pq.push([[0, j], heightMap[0][j]])\n pq.push([[m - 1, j], heightMap[m - 1][j]])\n }\n const dirs = [[1,0],[-1,0],[0,1],[0,-1]]\n let res = 0\n while(!pq.isEmpty()) {\n const [coord, h] = pq.pop()\n const [r, c] = coord\n for(const [dr, dc] of dirs) {\n const nr = r + dr, nc = c + dc\n if(nr >= 0 && nr < m && nc >= 0 && nc < n && !visited[nr][nc]) {\n visited[nr][nc] = true\n if (h > heightMap[nr][nc]) res += h - heightMap[nr][nc]\n pq.push([[nr, nc], Math.max(heightMap[nr][nc], h)])\n }\n }\n }/* */\n return res\n};\n\n// another\n\n/**\n * @param {number[][]} heightMap\n * @return {number}\n */\n\nconst trapRainWater = function (heightMap) {\n const pq = new PriorityQueue((a, b) => a[2] < b[2])\n const m = heightMap.length, n = heightMap[0].length\n \n const visited = Array.from({ length: m }, () => Array(n).fill(false))\n \n for(let i = 0; i < m; i++) {\n visited[i][0] = visited[i][n - 1] = true\n pq.push([i, 0, heightMap[i][0]])\n pq.push([i, n - 1, heightMap[i][n - 1]])\n }\n for(let j = 1; j < n - 1; j++) {\n visited[0][j] = visited[m - 1][j] = true\n pq.push([0, j, heightMap[0][j]], [m - 1, j, heightMap[m - 1][j]])\n }\n \n let res = 0\n const dirs = [[-1, 0], [1, 0], [0, 1], [0, -1]]\n while(!pq.isEmpty()) {\n const cur = pq.pop()\n const [r, c, h] = cur\n for(let dir of dirs) {\n const newR = r + dir[0], newC = c + dir[1]\n if(newR < 0 || newR >= m || newC < 0 || newC >= n || visited[newR][newC]) continue\n visited[newR][newC] = true\n res += Math.max(0, h - heightMap[newR][newC])\n pq.push([newR, newC, Math.max(h, heightMap[newR][newC])])\n }\n }\n \n return res\n\n}\nclass PriorityQueue {\n constructor(comparator = (a, b) => a > b) {\n this.heap = []\n this.top = 0\n this.comparator = comparator\n }\n size() {\n return this.heap.length\n }\n isEmpty() {\n return this.size() === 0\n }\n peek() {\n return this.heap[this.top]\n }\n push(...values) {\n values.forEach((value) => {\n this.heap.push(value)\n this.siftUp()\n })\n return this.size()\n }\n pop() {\n const poppedValue = this.peek()\n const bottom = this.size() - 1\n if (bottom > this.top) {\n this.swap(this.top, bottom)\n }\n this.heap.pop()\n this.siftDown()\n return poppedValue\n }\n replace(value) {\n const replacedValue = this.peek()\n this.heap[this.top] = value\n this.siftDown()\n return replacedValue\n }\n\n parent = (i) => ((i + 1) >>> 1) - 1\n left = (i) => (i << 1) + 1\n right = (i) => (i + 1) << 1\n greater = (i, j) => this.comparator(this.heap[i], this.heap[j])\n swap = (i, j) => ([this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]])\n siftUp = () => {\n let node = this.size() - 1\n while (node > this.top && this.greater(node, this.parent(node))) {\n this.swap(node, this.parent(node))\n node = this.parent(node)\n }\n }\n siftDown = () => {\n let node = this.top\n while (\n (this.left(node) < this.size() && this.greater(this.left(node), node)) ||\n (this.right(node) < this.size() && this.greater(this.right(node), node))\n ) {\n let maxChild =\n this.right(node) < this.size() &&\n this.greater(this.right(node), this.left(node))\n ? this.right(node)\n : this.left(node)\n this.swap(node, maxChild)\n node = maxChild\n }\n }\n}\n\n\n\n// another\n\n/**\n * @param {number[][]} heightMap\n * @return {number}\n */\n\nconst trapRainWater = function (heightMap) {\n const pq = new PriorityQueue((a, b) => a[2] < b[2])\n const visited = []\n for (let i = 0; i < heightMap.length; i++) {\n visited[i] = []\n for (let j = 0; j < heightMap[0].length; j++) {\n if (\n i > 0 &&\n i < heightMap.length - 1 &&\n j > 0 &&\n j < heightMap[0].length - 1\n )\n continue\n pq.push([i, j, heightMap[i][j]])\n visited[i][j] = true\n }\n }\n\n let max = -Infinity,\n count = 0\n while (!pq.isEmpty()) {\n const cur = pq.pop()\n if (cur[2] > max) max = cur[2]\n check(cur[0], cur[1])\n }\n function check(row, col) {\n const step = [\n [-1, 0],\n [1, 0],\n [0, -1],\n [0, 1],\n ]\n for (let i = 0; i < step.length; i++) {\n let newR = row + step[i][0],\n newC = col + step[i][1]\n if (\n newR < 0 ||\n newR >= heightMap.length ||\n newC < 0 ||\n newC >= heightMap[0].length\n )\n continue\n if (visited[newR][newC]) continue\n visited[newR][newC] = true\n const newVal = heightMap[newR][newC]\n if (newVal < max) {\n count += max - newVal\n check(newR, newC)\n } else {\n pq.push([newR, newC, newVal])\n }\n }\n }\n\n return count\n}\nclass PriorityQueue {\n constructor(comparator = (a, b) => a > b) {\n this.heap = []\n this.top = 0\n this.comparator = comparator\n }\n size() {\n return this.heap.length\n }\n isEmpty() {\n return this.size() === 0\n }\n peek() {\n return this.heap[this.top]\n }\n push(...values) {\n values.forEach((value) => {\n this.heap.push(value)\n this.siftUp()\n })\n return this.size()\n }\n pop() {\n const poppedValue = this.peek()\n const bottom = this.size() - 1\n if (bottom > this.top) {\n this.swap(this.top, bottom)\n }\n this.heap.pop()\n this.siftDown()\n return poppedValue\n }\n replace(value) {\n const replacedValue = this.peek()\n this.heap[this.top] = value\n this.siftDown()\n return replacedValue\n }\n\n parent = (i) => ((i + 1) >>> 1) - 1\n left = (i) => (i << 1) + 1\n right = (i) => (i + 1) << 1\n greater = (i, j) => this.comparator(this.heap[i], this.heap[j])\n swap = (i, j) => ([this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]])\n siftUp = () => {\n let node = this.size() - 1\n while (node > this.top && this.greater(node, this.parent(node))) {\n this.swap(node, this.parent(node))\n node = this.parent(node)\n }\n }\n siftDown = () => {\n let node = this.top\n while (\n (this.left(node) < this.size() && this.greater(this.left(node), node)) ||\n (this.right(node) < this.size() && this.greater(this.right(node), node))\n ) {\n let maxChild =\n this.right(node) < this.size() &&\n this.greater(this.right(node), this.left(node))\n ? this.right(node)\n : this.left(node)\n this.swap(node, maxChild)\n node = maxChild\n }\n }\n}\n\n\n// another\n\n/**\n * @param {number[][]} heightMap\n * @return {number}\n */\nconst trapRainWater = function(heightMap) {\n\n function PriorityQueueMin(){\n let heap=[null]\n function swim(idx){\n if(idx<2)return\n let k=Math.floor(idx/2)\n if(heap[idx][2]-heap[k][2]<0){\n swap(heap,idx,k)\n idx=k\n swim(idx)\n }\n }\n function sink(idx){\n let k=Math.floor(idx*2)\n if(k>=heap.length)return\n if(k0) k++\n if(heap[idx][2]-heap[k][2]>0){\n swap(heap,idx,k)\n idx=k\n sink(idx)\n }\n }\n function swap(arr,i,j){\n let temp=arr[i]\n arr[i]=arr[j]\n arr[j]=temp\n }\n this.insert=function (v) {\n heap.push(v)\n swim(heap.length-1)\n }\n this.delMin=function () {\n swap(heap,1,heap.length-1)\n let min=heap.pop()\n sink(1)\n return min\n }\n this.isEmpty=function () {\n return heap.length===1\n }\n }\n \n let pq=new PriorityQueueMin()\n let visited=[]\n for(let i=0;i0 && i0 && jmax)max=cur[2]\n check(cur[0],cur[1])\n }\n function check(row,col){\n let step=[[-1,0],[1,0],[0,-1],[0,1]]\n for(let i=0;i=heightMap.length) || (newC<0 || newC>=heightMap[0].length))continue\n if(visited[newR][newC])continue\n visited[newR][newC]=true\n let newVal=heightMap[newR][newC]\n if(newVal 0 && nums[i] === max || count > 1 && nums[i] === mid) continue;\n count++;\n if (nums[i] > max) {\n small = mid;\n mid = max;\n max = nums[i];\n } else if (nums[i] > mid) {\n small = mid;\n mid = nums[i];\n } else if (nums[i] > small) {\n small = nums[i];\n }\n }\n return count < 3 ? max : small;\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720baa", + "questionid": 223, + "title": "Reconstruct Original Digits from English", + "slug": "reconstruct-original-digits-from-english", + "description": "Given a string s containing an out-of-order English representation of digits 0-9, return the digits in ascending order. ", + "category": [ + "Hash Table", + "Math", + "String" + ], + "complexity": "Medium", + "successrate": 51.2, + "totalsubmissions": 120508, + "totalaccepted": 61662, + "likes": 601, + "dislikes": 2013, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = \"owoztneoer\"", + "expected_output": "\"012\"", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "s = \"fviefuro\"", + "expected_output": "\"45\"", + "explanation": "" + } + ], + "solution": "/**\n * @param {string} s\n * @return {string}\n */\nconst originalDigits = function(s) {\n const count = new Array(10).fill(0);\n for (let i = 0; i < s.length; i++) {\n let c = s.charAt(i);\n if (c === \"z\") count[0]++;\n if (c === \"w\") count[2]++;\n if (c === \"x\") count[6]++;\n if (c === \"s\") count[7]++; //7-6\n if (c === \"g\") count[8]++;\n if (c === \"u\") count[4]++;\n if (c === \"f\") count[5]++; //5-4\n if (c === \"h\") count[3]++; //3-8\n if (c === \"i\") count[9]++; //9-8-5-6\n if (c === \"o\") count[1]++; //1-0-2-4\n }\n count[7] -= count[6];\n count[5] -= count[4];\n count[3] -= count[8];\n count[9] = count[9] - count[8] - count[5] - count[6];\n count[1] = count[1] - count[0] - count[2] - count[4];\n let ans = \"\";\n for (let i = 0; i <= 9; i++) {\n ans += `${i}`.repeat(count[i]);\n }\n return ans;\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720bac", + "questionid": 225, + "title": "Minimum Genetic Mutation", + "slug": "minimum-genetic-mutation", + "description": "A gene string can be represented by an 8-character long string, with choices from 'A', 'C', 'G', and 'T'. Suppose we need to investigate a mutation from a gene string start to a gene string end where one mutation is defined as one single character changed in the gene string. There is also a gene bank bank that records all the valid gene mutations. A gene must be in bank to make it a valid gene string. Given the two gene strings start and end and the gene bank bank, return the minimum number of mutations needed to mutate from start to end. If there is no such a mutation, return -1. Note that the starting point is assumed to be valid, so it might not be included in the bank. ", + "category": [ + "Hash Table", + "String", + "Breadth-First Search" + ], + "complexity": "Medium", + "successrate": 46.6, + "totalsubmissions": 113064, + "totalaccepted": 52704, + "likes": 868, + "dislikes": 102, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "startGene = "AACCGGTT", endGene = "AACCGGTA", bank = ["AACCGGTA"]", + "expected_output": "1", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "startGene = "AACCGGTT", endGene = "AAACGGTA", bank = ["AACCGGTA","AACCGCTA","AAACGGTA"]", + "expected_output": "2", + "explanation": "" + } + ], + "solution": "/**\n * @param {string} start\n * @param {string} end\n * @param {string[]} bank\n * @return {number}\n */\nconst minMutation = function(start, end, bank) {\n const obj = { res: Number.MAX_VALUE }\n dfs(start, end, bank, 0, obj, new Set())\n return obj.res === Number.MAX_VALUE ? -1 : obj.res\n}\n\nfunction dfs(s, e, bank, num, obj, visited) {\n if(s === e) {\n obj.res = Math.min(obj.res, num)\n return\n }\n for(let el of bank) {\n let diff = 0\n for(let i = 0, len = s.length; i < len; i++) {\n if(s[i] !== el[i]) {\n diff++\n if(diff > 1) break\n }\n }\n if(diff === 1 && !visited.has(el)) {\n visited.add(el)\n dfs(el, e, bank, num + 1, obj, visited)\n visited.delete(el)\n }\n }\n} \n\n// another\n\n/**\n * @param {string} start\n * @param {string} end\n * @param {string[]} bank\n * @return {number}\n */\nconst minMutation = function(start, end, bank) {\n const bankSet = new Set(bank)\n if (!bankSet.has(end)) return -1\n const queue = [[start, 0]]\n const dna = ['A', 'C', 'G', 'T']\n while (queue.length) {\n let [node, count] = queue.shift()\n if (node === end) return count\n for (let i = 0; i < node.length; i++) {\n for (let j = 0; j < dna.length; j++) {\n const d = node.slice(0, i) + dna[j] + node.slice(i + 1)\n if (bankSet.has(d)) {\n queue.push([d, count + 1])\n bankSet.delete(d)\n }\n }\n }\n }\n return -1\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720bad", + "questionid": 226, + "title": "Number of Segments in a String", + "slug": "number-of-segments-in-a-string", + "description": "Given a string s, return the number of segments in the string. A segment is defined to be a contiguous sequence of non-space characters. ", + "category": [ + "String" + ], + "complexity": "Easy", + "successrate": 37.9, + "totalsubmissions": 301227, + "totalaccepted": 114139, + "likes": 433, + "dislikes": 1006, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "Hello, my name is John"", + "expected_output": "5", + "explanation": "The five segments are ["Hello,", "my", "name", "is", "John"]" + }, + { + "example_num": 2, + "expected_input": "s = "Hello"", + "expected_output": "1", + "explanation": "" + } + ], + "solution": "/**\n * @param {string} s\n * @return {number}\n */\nconst countSegments = function(s) {\n if(s.trim() === '') return 0\n return s.trim().split(' ').filter(el => el !== '').length\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720bb0", + "questionid": 229, + "title": "Path Sum III", + "slug": "path-sum-iii", + "description": "Given the root of a binary tree and an integer targetSum, return the number of paths where the sum of the values\u00a0along the path equals\u00a0targetSum. The path does not need to start or end at the root or a leaf, but it must go downwards (i.e., traveling only from parent nodes to child nodes). ", + "category": [ + "Tree", + "Depth-First Search", + "Binary Tree" + ], + "complexity": "Medium", + "successrate": 50.2, + "totalsubmissions": 713399, + "totalaccepted": 357889, + "likes": 7352, + "dislikes": 359, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [10,5,-3,3,2,null,11,3,-2,null,1], targetSum = 8", + "expected_output": "3", + "explanation": "The paths that sum to 8 are shown." + }, + { + "example_num": 2, + "expected_input": "root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22", + "expected_output": "3", + "explanation": "" + } + ], + "solution": "/**\n * Definition for a binary tree node.\n * function TreeNode(val) {\n * this.val = val;\n * this.left = this.right = null;\n * }\n */\n/**\n * @param {TreeNode} root\n * @param {number} sum\n * @return {number}\n */\nfunction pathSum(root, sum) {\n const preSums = new Map([[0, 1]]);\n let count = 0;\n visit(root, 0);\n return count;\n \n function visit(node, preSum) {\n if (!node) return;\n preSum += node.val;\n count += preSums.get(preSum - sum) || 0;\n preSums.set(preSum, (preSums.get(preSum) || 0) + 1);\n visit(node.left, preSum);\n visit(node.right, preSum);\n preSums.set(preSum, preSums.get(preSum) - 1);\n }\n}\n\n" + }, + { + "_id": "66f925ddfdfb8e1665720bb3", + "questionid": 232, + "title": "Arranging Coins", + "slug": "arranging-coins", + "description": "You have n coins and you want to build a staircase with these coins. The staircase consists of k rows where the ith row has exactly i coins. The last row of the staircase may be incomplete. Given the integer n, return the number of complete rows of the staircase you will build. ", + "category": [ + "Math", + "Binary Search" + ], + "complexity": "Easy", + "successrate": 45.3, + "totalsubmissions": 602006, + "totalaccepted": 272594, + "likes": 2139, + "dislikes": 1012, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 5", + "expected_output": "2", + "explanation": "Because the 3rd row is incomplete, we return 2." + }, + { + "example_num": 2, + "expected_input": "n = 8", + "expected_output": "3", + "explanation": "Because the 4th row is incomplete, we return 3." + } + ], + "solution": "/**\n * @param {number} n\n * @return {number}\n */\nconst arrangeCoins = function(n) {\n if (n === 0) {\n return 0\n }\n let num = 1\n let sum = 1\n while(n >= sum + num + 1) {\n num += 1\n sum += num\n }\n\n return num\n};\n\n// another\n\n/**\n * @param {number} n\n * @return {number}\n */\nconst arrangeCoins = function(n) {\n return (-1 + Math.sqrt(1+4*2*n)) >> 1\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720bb8", + "questionid": 237, + "title": "Find All Numbers Disappeared in an Array", + "slug": "find-all-numbers-disappeared-in-an-array", + "description": "Given an array nums of n integers where nums[i] is in the range [1, n], return an array of all the integers in the range [1, n] that do not appear in nums. ", + "category": [ + "Array", + "Hash Table" + ], + "complexity": "Easy", + "successrate": 59, + "totalsubmissions": 952265, + "totalaccepted": 561997, + "likes": 6409, + "dislikes": 376, + "hints": "This is a really easy problem if you decide to use additional memory. For those trying to write an initial solution using additional memory, think counters! However, the trick really is to not use any additional space than what is already available to use. Sometimes, multiple passes over the input array help find the solution. However, there's an interesting piece of information in this problem that makes it easy to re-use the input array itself for the solution. The problem specifies that the numbers in the array will be in the range [1, n] where n is the number of elements in the array. Can we use this information and modify the array in-place somehow to find what we need?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [4,3,2,7,8,2,3,1]", + "expected_output": "[5,6]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "nums = [1,1]", + "expected_output": "[2]", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} nums\n * @return {number[]}\n */\nconst findDisappearedNumbers = function(nums) {\n const res = [];\n nums.forEach((el, idx) => {\n res[el - 1] = 1;\n });\n const arr = [];\n for (let i = 0; i < nums.length; i++) {\n if (res[i] == null) {\n arr.push(i + 1);\n }\n }\n return arr;\n};\n\n// another\n\n/**\n * @param {number[]} nums\n * @return {number[]}\n */\nconst findDisappearedNumbers = function(nums) {\n for(let i = 0, len = nums.length; i < len; i++) {\n const idx = Math.abs(nums[i]) - 1\n nums[idx] = - Math.abs(nums[idx])\n }\n const res = []\n nums.forEach((e, i) => {\n if(e > 0) res.push(i + 1)\n })\n return res\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720bb9", + "questionid": 238, + "title": "Serialize and Deserialize BST", + "slug": "serialize-and-deserialize-bst", + "description": "Serialization is converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment. Design an algorithm to serialize and deserialize a binary search tree. There is no restriction on how your serialization/deserialization algorithm should work. You need to ensure that a binary search tree can be serialized to a string, and this string can be deserialized to the original tree structure. The encoded string should be as compact as possible. ", + "category": [ + "String", + "Tree", + "Depth-First Search", + "Breadth-First Search", + "Design", + "Binary Search Tree", + "Binary Tree" + ], + "complexity": "Medium", + "successrate": 56.1, + "totalsubmissions": 339893, + "totalaccepted": 190840, + "likes": 2633, + "dislikes": 129, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [2,1,3]", + "expected_output": "[2,1,3]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "root = []", + "expected_output": "[]", + "explanation": "" + } + ], + "solution": null + }, + { + "_id": "66f925ddfdfb8e1665720bba", + "questionid": 239, + "title": "Sort Characters By Frequency", + "slug": "sort-characters-by-frequency", + "description": "Given a string s, sort it in decreasing order based on the frequency of the characters. The frequency of a character is the number of times it appears in the string. Return the sorted string. If there are multiple answers, return any of them. ", + "category": [ + "Hash Table", + "String", + "Sorting", + "Heap (Priority Queue)", + "Bucket Sort", + "Counting" + ], + "complexity": "Medium", + "successrate": 67.7, + "totalsubmissions": 524140, + "totalaccepted": 354883, + "likes": 4008, + "dislikes": 178, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "tree"", + "expected_output": ""eert"", + "explanation": "'e' appears twice while 'r' and 't' both appear once.\nSo 'e' must appear before both 'r' and 't'. Therefore "eetr" is also a valid answer." + }, + { + "example_num": 2, + "expected_input": "s = "cccaaa"", + "expected_output": ""aaaccc"", + "explanation": "Both 'c' and 'a' appear three times, so both "cccaaa" and "aaaccc" are valid answers.\nNote that "cacaca" is incorrect, as the same characters must be together." + }, + { + "example_num": 3, + "expected_input": "s = "Aabb"", + "expected_output": ""bbAa"", + "explanation": ""bbaA" is also a valid answer, but "Aabb" is incorrect.\nNote that 'A' and 'a' are treated as two different characters." + } + ], + "solution": "/**\n * @param {string} s\n * @return {string}\n */\nconst frequencySort = function(s) {\n const charMap = {};\n for (let i = 0; i < s.length; i++) {\n const index = s.charAt(i);\n charMap[index] = (charMap[index] || 0) + 1;\n }\n return Object.entries(charMap)\n .sort((a, b) => {\n return b[1] - a[1];\n })\n .map(x => {\n return x[0].repeat(x[1]);\n })\n .join(\"\");\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720bbc", + "questionid": 241, + "title": "Minimum Moves to Equal Array Elements", + "slug": "minimum-moves-to-equal-array-elements", + "description": "Given an integer array nums of size n, return the minimum number of moves required to make all array elements equal. In one move, you can increment n - 1 elements of the array by 1. ", + "category": [ + "Array", + "Math" + ], + "complexity": "Medium", + "successrate": 54, + "totalsubmissions": 224354, + "totalaccepted": 121115, + "likes": 1419, + "dislikes": 1548, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,2,3]", + "expected_output": "3", + "explanation": "Only three moves are needed (remember each move increments two elements):\n[1,2,3] => [2,3,3] => [3,4,3] => [4,4,4]" + }, + { + "example_num": 2, + "expected_input": "nums = [1,1,1]", + "expected_output": "0", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} nums\n * @return {number}\n */\nconst minMoves = function(nums) {\n let min = Number.MAX_SAFE_INTEGER;\n let sum = 0;\n for (let i = 0; i < nums.length; i++) {\n min = Math.min(min, nums[i]);\n sum += nums[i];\n }\n return sum - min * nums.length;\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720bc1", + "questionid": 246, + "title": "Minimum Moves to Equal Array Elements II", + "slug": "minimum-moves-to-equal-array-elements-ii", + "description": "Given an integer array nums of size n, return the minimum number of moves required to make all array elements equal. In one move, you can increment or decrement an element of the array by 1. Test cases are designed so that the answer will fit in a 32-bit integer. ", + "category": [ + "Array", + "Math", + "Sorting" + ], + "complexity": "Medium", + "successrate": 56.9, + "totalsubmissions": 154692, + "totalaccepted": 88030, + "likes": 1373, + "dislikes": 73, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,2,3]", + "expected_output": "2", + "explanation": "Only two moves are needed (remember each move increments or decrements one element):\n[1,2,3] => [2,2,3] => [2,2,2]" + }, + { + "example_num": 2, + "expected_input": "nums = [1,10,2,9]", + "expected_output": "16", + "explanation": "" + } + ], + "solution": null + }, + { + "_id": "66f925ddfdfb8e1665720bc4", + "questionid": 249, + "title": "Count The Repetitions", + "slug": "count-the-repetitions", + "description": "We define str = [s, n] as the string str which consists of the string s concatenated n times. We define that string s1 can be obtained from string s2 if we can remove some characters from s2 such that it becomes s1. You are given two strings s1 and s2 and two integers n1 and n2. You have the two strings str1 = [s1, n1] and str2 = [s2, n2]. Return the maximum integer m such that str = [str2, m] can be obtained from str1. ", + "category": [ + "String", + "Dynamic Programming" + ], + "complexity": "Hard", + "successrate": 29, + "totalsubmissions": 48557, + "totalaccepted": 14067, + "likes": 292, + "dislikes": 260, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s1 = \"acb\", n1 = 4, s2 = \"ab\", n2 = 2", + "expected_output": "2", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "s1 = \"acb\", n1 = 1, s2 = \"acb\", n2 = 1", + "expected_output": "1", + "explanation": "" + } + ], + "solution": "/**\n * @param {string} s1\n * @param {number} n1\n * @param {string} s2\n * @param {number} n2\n * @return {number}\n */\nconst getMaxRepetitions = function(s1, n1, s2, n2) {\n let j = 0,\n i,\n count = 0,\n perCycle = 0,\n firstEnd = -1,\n lastEnd = -1,\n nonMatch = 0\n for (i = 0; i < s1.length * n1; i++) {\n if (s2[j] === s1[i % s1.length]) {\n j++\n nonMatch = 0\n } else if (++nonMatch >= s1.length) break\n if (j === s2.length) {\n count++\n perCycle++\n j = 0\n if (lastEnd !== -1) continue\n else if (firstEnd === -1) {\n firstEnd = i\n perCycle = 0\n } else if ((i - firstEnd) % s1.length === 0) {\n let cycleLen = i - firstEnd\n let remainLen = s1.length * n1 - i - 1\n let cycles = Math.floor(remainLen / cycleLen)\n count += cycles * perCycle\n i += cycles * cycleLen\n }\n }\n }\n return Math.floor(count / n2)\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720bca", + "questionid": 255, + "title": "Total Hamming Distance", + "slug": "total-hamming-distance", + "description": "The Hamming distance between two integers is the number of positions at which the corresponding bits are different. Given an integer array nums, return the sum of Hamming distances between all the pairs of the integers in nums. ", + "category": [ + "Array", + "Math", + "Bit Manipulation" + ], + "complexity": "Medium", + "successrate": 52, + "totalsubmissions": 167545, + "totalaccepted": 87042, + "likes": 1614, + "dislikes": 80, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [4,14,2]", + "expected_output": "6", + "explanation": "In binary representation, the 4 is 0100, 14 is 1110, and 2 is 0010 (just\nshowing the four bits relevant in this case).\nThe answer will be:\nHammingDistance(4, 14) + HammingDistance(4, 2) + HammingDistance(14, 2) = 2 + 2 + 2 = 6." + }, + { + "example_num": 2, + "expected_input": "nums = [4,14,4]", + "expected_output": "4", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} nums\n * @return {number}\n */\nconst totalHammingDistance = function(nums) {\n let total = 0,\n n = nums.length;\n for (let j = 0; j < 32; j++) {\n let bitCount = 0;\n for (let i = 0; i < n; i++) bitCount += (nums[i] >> j) & 1;\n total += bitCount * (n - bitCount);\n }\n return total;\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720bd1", + "questionid": 262, + "title": "Reverse Pairs", + "slug": "reverse-pairs", + "description": "Given an integer array nums, return the number of reverse pairs in the array. A reverse pair is a pair (i, j) where 0 <= i < j < nums.length and nums[i] > 2 * nums[j]. ", + "category": [ + "Array", + "Binary Search", + "Divide and Conquer", + "Binary Indexed Tree", + "Segment Tree", + "Merge Sort", + "Ordered Set" + ], + "complexity": "Hard", + "successrate": 29.8, + "totalsubmissions": 270169, + "totalaccepted": 80624, + "likes": 2706, + "dislikes": 178, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,3,2,3,1]", + "expected_output": "2", + "explanation": "The reverse pairs are:\n(1, 4) --> nums[1] = 3, nums[4] = 1, 3 > 2 * 1\n(3, 4) --> nums[3] = 3, nums[4] = 1, 3 > 2 * 1" + }, + { + "example_num": 2, + "expected_input": "nums = [2,4,3,5,1]", + "expected_output": "3", + "explanation": "The reverse pairs are:\n(1, 4) --> nums[1] = 4, nums[4] = 1, 4 > 2 * 1\n(2, 4) --> nums[2] = 3, nums[4] = 1, 3 > 2 * 1\n(3, 4) --> nums[3] = 5, nums[4] = 1, 5 > 2 * 1" + } + ], + "solution": "/**\n * @param {number[]} nums\n * @return {number}\n */\nconst reversePairs = function(nums) {\n return mergeSort(nums, [], 0, nums.length-1);\n};\n\nfunction mergeSort(arr, temp, left, right){\n let mid = Math.floor((left+right)/2), count = 0;\n if(left2*a[j])){\n j++;\n }\n count+= (j-(mid));\n }\n i=left;\n j=mid;\n while(i<=(mid-1) && j<=right){\n if (a[i]>(a[j])) {\n temp[k++] = a[j++];\n } else {\n temp[k++] = a[i++];\n }\n }\n while(i<=(mid-1)){\n temp[k++] = a[i++];\n }\n while(j<=right){\n temp[k++] = a[j++];\n }\n for(let x=left; x<=right; x++){\n a[x] = temp[x];\n }\n return count;\n}\n\n// another\n\n/**\n * @param {number[]} nums\n * @return {number}\n */\nconst reversePairs = function(nums) {\n return mergeSort(nums, 0, nums.length - 1);\n};\n\nfunction mergeSort(nums, s, e) {\n if (s >= e) return 0;\n let mid = s + Math.floor((e - s) / 2);\n let cnt = mergeSort(nums, s, mid) + mergeSort(nums, mid + 1, e);\n for (let i = s, j = mid + 1; i <= mid; i++) {\n while (j <= e && nums[i] / 2.0 > nums[j]) j++;\n cnt += j - (mid + 1);\n }\n sortSubArr(nums, s, e + 1);\n return cnt;\n}\n\nfunction sortSubArr(arr, s, e) {\n const tmp = arr.slice(s, e);\n tmp.sort((a, b) => a - b);\n arr.splice(s, e - s, ...tmp);\n}\n\n// another\n\n/**\n * @param {number[]} nums\n * @return {number}\n */\nfunction merge(A, start, mid, end) {\n let n1 = mid - start + 1\n let n2 = end - mid\n const L = new Array(n1).fill(0)\n const R = new Array(n2).fill(0)\n\n for (let i = 0; i < n1; i++) L[i] = A[start + i]\n for (let j = 0; j < n2; j++) R[j] = A[mid + 1 + j]\n let i = 0,\n j = 0\n for (let k = start; k <= end; k++) {\n if (j >= n2 || (i < n1 && L[i] <= R[j])) A[k] = L[i++]\n else A[k] = R[j++]\n }\n}\n\nfunction mergesort_and_count(A, start, end) {\n if (start < end) {\n let mid = start + ((end - start) >> 1)\n let count =\n mergesort_and_count(A, start, mid) + mergesort_and_count(A, mid + 1, end)\n let j = mid + 1\n for (let i = start; i <= mid; i++) {\n while (j <= end && A[i] > A[j] * 2) j++\n count += j - (mid + 1)\n }\n merge(A, start, mid, end)\n return count\n } else return 0\n}\n\nfunction reversePairs(nums) {\n return mergesort_and_count(nums, 0, nums.length - 1)\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720bd2", + "questionid": 263, + "title": "Target Sum", + "slug": "target-sum", + "description": "You are given an integer array nums and an integer target. You want to build an expression out of nums by adding one of the symbols '+' and '-' before each integer in nums and then concatenate all the integers. Return the number of different expressions that you can build, which evaluates to target. ", + "category": [ + "Array", + "Dynamic Programming", + "Backtracking" + ], + "complexity": "Medium", + "successrate": 45.4, + "totalsubmissions": 750493, + "totalaccepted": 340614, + "likes": 6621, + "dislikes": 253, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,1,1,1,1], target = 3", + "expected_output": "5", + "explanation": "There are 5 ways to assign symbols to make the sum of nums be target 3.\n-1 + 1 + 1 + 1 + 1 = 3\n+1 - 1 + 1 + 1 + 1 = 3\n+1 + 1 - 1 + 1 + 1 = 3\n+1 + 1 + 1 - 1 + 1 = 3\n+1 + 1 + 1 + 1 - 1 = 3" + }, + { + "example_num": 2, + "expected_input": "nums = [1], target = 1", + "expected_output": "1", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} nums\n * @param {number} target\n * @return {number}\n */\nconst findTargetSumWays = function(nums, target) {\n const n = nums.length\n let res = 0\n for(let i = 0, limit = Math.pow(2, n); i < limit; i++) {\n if(helper(i)) res++\n }\n \n return res\n \n function helper(mask) {\n let sum = 0\n for(let i = 0; i < nums.length; i++) {\n if(mask & (1 << i)) {\n sum += nums[i]\n } else sum -= nums[i]\n }\n \n return sum === target\n }\n};\n\n// another\n\n/**\n * @param {number[]} nums\n * @param {number} target\n * @return {number}\n */\nconst findTargetSumWays = function(nums, target) {\n const sum = nums.reduce((a, b) => a+b);\n if(Math.abs(target) > sum) {\n return 0;\n }\n if((target + sum) % 2) {\n return 0;\n }\n const newTarget = (target + sum) / 2;\n let dp = new Array(newTarget+1).fill(0);\n dp[0] = 1;\n for(let i = 0; i < nums.length; i++) {\n for(let j = newTarget; j >= nums[i]; j--) {\n dp[j] += dp[j - nums[i]];\n }\n }\n return dp[newTarget];\n};\n\n\n\n// another\n\n/**\n * @param {number[]} nums\n * @param {number} S\n * @return {number}\n */\nconst findTargetSumWays = function(nums, s) {\n const sum = nums.reduce((p, n) => p + n, 0);\n return sum < s || (s + sum) % 2 > 0 ? 0 : subsetSum(nums, (s + sum) >>> 1);\n};\n\nfunction subsetSum(nums, s) {\n const dp = Array(s + 1).fill(0);\n dp[0] = 1;\n for (let n of nums) {\n for (let i = s; i >= n; i--) dp[i] += dp[i - n];\n }\n return dp[s];\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720bd7", + "questionid": 268, + "title": "Next Greater Element II", + "slug": "next-greater-element-ii", + "description": "Given a circular integer array nums (i.e., the next element of nums[nums.length - 1] is nums[0]), return the next greater number for every element in nums. The next greater number of a number x is the first greater number to its traversing-order next in the array, which means you could search circularly to find its next greater number. If it doesn't exist, return -1 for this number. ", + "category": [ + "Array", + "Stack", + "Monotonic Stack" + ], + "complexity": "Medium", + "successrate": 61.9, + "totalsubmissions": 341428, + "totalaccepted": 211511, + "likes": 4409, + "dislikes": 130, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,2,1]", + "expected_output": "[2,-1,2]\nExplanation: The first 1's next greater number is 2; \nThe number 2 can't find next greater number. \nThe second 1's next greater number needs to search circularly, which is also 2.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "nums = [1,2,3,4,3]", + "expected_output": "[2,3,4,-1,4]", + "explanation": "" + } + ], + "solution": null + }, + { + "_id": "66f925ddfdfb8e1665720bd9", + "questionid": 270, + "title": "Perfect Number", + "slug": "perfect-number", + "description": "A perfect number is a positive integer that is equal to the sum of its positive divisors, excluding the number itself. A divisor of an integer x is an integer that can divide x evenly. Given an integer n, return true if n is a perfect number, otherwise return false. ", + "category": [ + "Math" + ], + "complexity": "Easy", + "successrate": 37.6, + "totalsubmissions": 269423, + "totalaccepted": 101225, + "likes": 543, + "dislikes": 836, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "num = 28", + "expected_output": "true", + "explanation": "28 = 1 + 2 + 4 + 7 + 14\n1, 2, 4, 7, and 14 are all divisors of 28." + }, + { + "example_num": 2, + "expected_input": "num = 7", + "expected_output": "false", + "explanation": "" + } + ], + "solution": "/**\n * @param {number} num\n * @return {boolean}\n */\nconst checkPerfectNumber = function(num) {\n if (num === 1) return false;\n return chk(num);\n};\n\nfunction chk(num) {\n let min = 2;\n let max = Math.ceil(Math.sqrt(num));\n const res = [1];\n for (let i = min; i <= max; i++) {\n if (Number.isInteger(num / i) && res.indexOf(i) === -1) {\n res.push(i, num / i);\n }\n }\n if (res.reduce((ac, el) => ac + el, 0) === num) {\n return true;\n } else {\n return false;\n }\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720bdc", + "questionid": 273, + "title": "Find Largest Value in Each Tree Row", + "slug": "find-largest-value-in-each-tree-row", + "description": "Given the root of a binary tree, return an array of the largest value in each row of the tree (0-indexed). ", + "category": [ + "Tree", + "Depth-First Search", + "Breadth-First Search", + "Binary Tree" + ], + "complexity": "Medium", + "successrate": 64.4, + "totalsubmissions": 291567, + "totalaccepted": 187850, + "likes": 1980, + "dislikes": 82, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [1,3,2,5,3,null,9]", + "expected_output": "[1,3,9]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "root = [1,2,3]", + "expected_output": "[1,3]", + "explanation": "" + } + ], + "solution": "/**\n * Definition for a binary tree node.\n * function TreeNode(val) {\n * this.val = val;\n * this.left = this.right = null;\n * }\n */\n/**\n * @param {TreeNode} root\n * @return {number[]}\n */\nconst largestValues = function(root) {\n const res = [];\n single(root, 0, res);\n return res;\n};\n\nfunction single(node, row, arr) {\n if (node == null) {\n return null;\n }\n if (row < arr.length) {\n if (node.val > arr[row]) {\n arr[row] = node.val;\n }\n } else {\n arr[row] = node.val;\n }\n single(node.left, row + 1, arr);\n single(node.right, row + 1, arr);\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720bdd", + "questionid": 274, + "title": "Longest Palindromic Subsequence", + "slug": "longest-palindromic-subsequence", + "description": "Given a string s, find the longest palindromic subsequence's length in s. A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements. ", + "category": [ + "String", + "Dynamic Programming" + ], + "complexity": "Medium", + "successrate": 59.3, + "totalsubmissions": 418537, + "totalaccepted": 248026, + "likes": 5039, + "dislikes": 246, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "bbbab"", + "expected_output": "4", + "explanation": "One possible longest palindromic subsequence is "bbbb"." + }, + { + "example_num": 2, + "expected_input": "s = "cbbd"", + "expected_output": "2", + "explanation": "One possible longest palindromic subsequence is "bb"." + } + ], + "solution": "// \u533a\u95f4DP\n\n/**\n * @param {string} s\n * @return {number}\n */\nconst longestPalindromeSubseq = function(s) {\n const n = s.length\n const dp = Array.from({ length: n }, () => Array(n).fill(0))\n for(let i = 0; i < n; i++) dp[i][i] = 1\n for(let len = 2; len <= n; len++) {\n for(let i = 0; i + len - 1 < n; i++) {\n const j = i + len - 1\n if(s[i] === s[j]) dp[i][j] = 2 + dp[i + 1][j - 1]\n else dp[i][j] = Math.max(dp[i + 1][j], dp[i][j - 1])\n }\n }\n return dp[0][n - 1]\n};\n\n// another\n\n/**\n * @param {string} s\n * @return {number}\n */\nconst longestPalindromeSubseq = function(s) {\n const n = s.length\n const dp = Array.from({ length: n }, () => Array(n).fill(0))\n for(let i = 0; i < n; i++) {\n dp[i][i] = 1\n for(let j = i - 1; j >= 0; j--) {\n if(s[i] === s[j]) {\n dp[i][j] = dp[i - 1][j + 1] + 2\n } else {\n dp[i][j] = Math.max(dp[i - 1][j], dp[i][j + 1])\n }\n }\n }\n \n return dp[n - 1][0]\n};\n\n// another\n\n/**\n * @param {string} s\n * @return {number}\n */\nconst longestPalindromeSubseq = function(s) {\n const len = s.length\n const dp = Array.from({length: len + 1}, () => new Array(len + 1).fill(0))\n for(let i = len - 1; i >= 0; i--) {\n dp[i][i] = 1\n for(let j = i + 1; j < len; j++) {\n if(s[i] === s[j]) {\n dp[i][j] = dp[i+1][j-1] + 2\n } else {\n dp[i][j] = Math.max(dp[i][j - 1], dp[i+1][j])\n }\n }\n }\n return dp[0][s.length - 1]\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720bde", + "questionid": 275, + "title": "Super Washing Machines", + "slug": "super-washing-machines", + "description": "You have n super washing machines on a line. Initially, each washing machine has some dresses or is empty. For each move, you could choose any m (1 <= m <= n) washing machines, and pass one dress of each washing machine to one of its adjacent washing machines at the same time. Given an integer array machines representing the number of dresses in each washing machine from left to right on the line, return the minimum number of moves to make all the washing machines have the same number of dresses. If it is not possible to do it, return -1. ", + "category": [ + "Array", + "Greedy" + ], + "complexity": "Hard", + "successrate": 39.4, + "totalsubmissions": 55433, + "totalaccepted": 21827, + "likes": 530, + "dislikes": 178, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "machines = [1,0,5]", + "expected_output": "3", + "explanation": "1st move: 1 0 <-- 5 => 1 1 4\n2nd move: 1 <-- 1 <-- 4 => 2 1 3\n3rd move: 2 1 <-- 3 => 2 2 2" + }, + { + "example_num": 2, + "expected_input": "machines = [0,3,0]", + "expected_output": "2", + "explanation": "1st move: 0 <-- 3 0 => 1 2 0\n2nd move: 1 2 --> 0 => 1 1 1" + }, + { + "example_num": 3, + "expected_input": "machines = [0,2,0]", + "expected_output": "-1", + "explanation": "It's impossible to make all three washing machines have the same number of dresses." + } + ], + "solution": "/**\n * @param {number[]} machines\n * @return {number}\n */\nconst findMinMoves = function(machines) {\n let total = 0\n for (let i of machines) total += i\n if (total % machines.length !== 0) return -1\n let avg = (total / machines.length) >> 0,\n cnt = 0,\n max = 0\n for (let load of machines) {\n cnt += load - avg\n max = Math.max(Math.max(max, Math.abs(cnt)), load - avg)\n }\n return max\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720be6", + "questionid": 283, + "title": "Minimum Absolute Difference in BST", + "slug": "minimum-absolute-difference-in-bst", + "description": "Given the root of a Binary Search Tree (BST), return the minimum absolute difference between the values of any two different nodes in the tree. ", + "category": [ + "Tree", + "Depth-First Search", + "Breadth-First Search", + "Binary Search Tree", + "Binary Tree" + ], + "complexity": "Easy", + "successrate": 56.2, + "totalsubmissions": 273418, + "totalaccepted": 153691, + "likes": 1994, + "dislikes": 117, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [4,2,6,1,3]", + "expected_output": "1", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "root = [1,0,48,null,null,12,49]", + "expected_output": "1", + "explanation": "" + } + ], + "solution": null + }, + { + "_id": "66f925ddfdfb8e1665720bea", + "questionid": 287, + "title": "Diameter of Binary Tree", + "slug": "diameter-of-binary-tree", + "description": "Given the root of a binary tree, return the length of the diameter of the tree. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root. The length of a path between two nodes is represented by the number of edges between them. ", + "category": [ + "Tree", + "Depth-First Search", + "Binary Tree" + ], + "complexity": "Easy", + "successrate": 54.1, + "totalsubmissions": 1310070, + "totalaccepted": 708322, + "likes": 7587, + "dislikes": 481, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [1,2,3,4,5]", + "expected_output": "3", + "explanation": "3 is the length of the path [4,2,1,3] or [5,2,1,3]." + }, + { + "example_num": 2, + "expected_input": "root = [1,2]", + "expected_output": "1", + "explanation": "" + } + ], + "solution": "/**\n * Definition for a binary tree node.\n * function TreeNode(val) {\n * this.val = val;\n * this.left = this.right = null;\n * }\n */\n/**\n * @param {TreeNode} root\n * @return {number}\n */\nconst diameterOfBinaryTree = function (root) {\n if (root === null) return 0\n let longest = 0\n function dfs(node) {\n if (node === null) return 0\n let leftmax = dfs(node.left)\n let rightmax = dfs(node.right)\n longest = Math.max(longest, leftmax + 1 + rightmax)\n return Math.max(leftmax, rightmax) + 1\n }\n dfs(root)\n return longest - 1\n}\n\n// another\n\n/**\n * Definition for a binary tree node.\n * function TreeNode(val, left, right) {\n * this.val = (val===undefined ? 0 : val)\n * this.left = (left===undefined ? null : left)\n * this.right = (right===undefined ? null : right)\n * }\n */\n/**\n * @param {TreeNode} root\n * @return {number}\n */\nconst diameterOfBinaryTree = function(root) {\n let res = 0\n dfs(root)\n return res\n\n function dfs(node) {\n if(node == null) return 0\n const left = dfs(node.left), right = dfs(node.right)\n res = Math.max(res, left + right)\n return Math.max(left, right) + 1\n }\n};\n\n// another\n\n/**\n * Definition for a binary tree node.\n * function TreeNode(val, left, right) {\n * this.val = (val===undefined ? 0 : val)\n * this.left = (left===undefined ? null : left)\n * this.right = (right===undefined ? null : right)\n * }\n */\n/**\n * @param {TreeNode} root\n * @return {number}\n */\nconst diameterOfBinaryTree = function(root) {\n let res = -Infinity\n dfs(root)\n return res\n function dfs(node) {\n if(node == null) return -1\n const left = dfs(node.left)\n const right = dfs(node.right)\n res = Math.max(res, left + right + 2)\n return Math.max(left, right) + 1\n }\n};\n\n" + }, + { + "_id": "66f925ddfdfb8e1665720bed", + "questionid": 290, + "title": "Brick Wall", + "slug": "brick-wall", + "description": "There is a rectangular brick wall in front of you with n rows of bricks. The ith row has some number of bricks each of the same height (i.e., one unit) but they can be of different widths. The total width of each row is the same. Draw a vertical line from the top to the bottom and cross the least bricks. If your line goes through the edge of a brick, then the brick is not considered as crossed. You cannot draw a line just along one of the two vertical edges of the wall, in which case the line will obviously cross no bricks. Given the 2D array wall that contains the information about the wall, return the minimum number of crossed bricks after drawing such a vertical line. ", + "category": [ + "Array", + "Hash Table" + ], + "complexity": "Medium", + "successrate": 52.6, + "totalsubmissions": 189678, + "totalaccepted": 99768, + "likes": 1789, + "dislikes": 101, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "wall = [[1,2,2,1],[3,1,2],[1,3,2],[2,4],[3,1,2],[1,3,1,1]]", + "expected_output": "2", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "wall = [[1],[1],[1]]", + "expected_output": "3", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[][]} wall\n * @return {number}\n */\nconst leastBricks = function(wall) {\n const hash = {};\n let row;\n let rowSum = 0;\n for (let i = 0; i < wall.length; i++) {\n rowSum = 0;\n row = wall[i];\n for (let j = 0; j < row.length - 1; j++) {\n rowSum += row[j];\n hash[rowSum] = hash.hasOwnProperty(rowSum) ? hash[rowSum] + 1 : 1;\n }\n }\n return (\n wall.length -\n (Object.keys(hash).length > 0\n ? Math.max(...Object.keys(hash).map(key => hash[key]))\n : 0)\n );\n};\n\nconsole.log(leastBricks([[1], [1], [1]]));\n" + }, + { + "_id": "66f925ddfdfb8e1665720bee", + "questionid": 291, + "title": "Next Greater Element III", + "slug": "next-greater-element-iii", + "description": "Given a positive integer n, find the smallest integer which has exactly the same digits existing in the integer n and is greater in value than n. If no such positive integer exists, return -1. Note that the returned integer should fit in 32-bit integer, if there is a valid answer but it does not fit in 32-bit integer, return -1. ", + "category": [ + "Math", + "Two Pointers", + "String" + ], + "complexity": "Medium", + "successrate": 33.8, + "totalsubmissions": 285936, + "totalaccepted": 96588, + "likes": 2171, + "dislikes": 342, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 12", + "expected_output": "21", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "n = 21", + "expected_output": "-1", + "explanation": "" + } + ], + "solution": "/**\n * @param {number} n\n * @return {number}\n */\nconst nextGreaterElement = function(n) {\n let i, j;\n const arr = (n + \"\").split(\"\").map(el => +el);\n for (i = arr.length - 2; i >= 0; i--) {\n if (arr[i] < arr[i + 1]) {\n break;\n }\n }\n if (i < 0) return -1;\n j = arr.length - 1;\n while (arr[j] <= arr[i]) {\n j--;\n }\n swap(arr, i, j);\n reverse(arr, i + 1, arr.length - 1);\n\n const res = arr.reduce((ac, el) => ac + el, \"\");\n return res > Math.pow(2, 31) - 1 ? -1 : +res\n};\n\nfunction swap(arr, i, j) {\n arr[i] ^= arr[j];\n arr[j] ^= arr[i];\n arr[i] ^= arr[j];\n}\n\nfunction reverse(arr, start, end) {\n let l = start;\n let h = end;\n while (l < h) {\n swap(arr, l++, h--);\n }\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720bf8", + "questionid": 301, + "title": "Out of Boundary Paths", + "slug": "out-of-boundary-paths", + "description": "There is an m x n grid with a ball. The ball is initially at the position [startRow, startColumn]. You are allowed to move the ball to one of the four adjacent cells in the grid (possibly out of the grid crossing the grid boundary). You can apply at most maxMove moves to the ball. Given the five integers m, n, maxMove, startRow, startColumn, return the number of paths to move the ball out of the grid boundary. Since the answer can be very large, return it modulo 109 + 7. ", + "category": [ + "Dynamic Programming" + ], + "complexity": "Medium", + "successrate": 40.1, + "totalsubmissions": 157850, + "totalaccepted": 63268, + "likes": 1475, + "dislikes": 182, + "hints": "Is traversing every path feasible? There are many possible paths for a small matrix. Try to optimize it. Can we use some space to store the number of paths and update them after every move? One obvious thing: the ball will go out of the boundary only by crossing it. Also, there is only one possible way the ball can go out of the boundary from the boundary cell except for corner cells. From the corner cell, the ball can go out in two different ways.\r\n\r\nCan you use this thing to solve the problem?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "m = 2, n = 2, maxMove = 2, startRow = 0, startColumn = 0", + "expected_output": "6", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "m = 1, n = 3, maxMove = 3, startRow = 0, startColumn = 1", + "expected_output": "12", + "explanation": "" + } + ], + "solution": "/**\n * @param {number} m\n * @param {number} n\n * @param {number} N\n * @param {number} i\n * @param {number} j\n * @return {number}\n */\nconst findPaths = function (m, n, N, i, j) {\n const dp = [...Array(2)].map((_) =>\n [...Array(50)].map((_) => Array(50).fill(0))\n )\n while (N-- > 0) {\n for (let i = 0; i < m; i++) {\n for (let j = 0, nc = (N + 1) % 2, np = N % 2; j < n; j++) {\n dp[nc][i][j] =\n ((i === 0 ? 1 : dp[np][i - 1][j]) +\n (i === m - 1 ? 1 : dp[np][i + 1][j]) +\n (j === 0 ? 1 : dp[np][i][j - 1]) +\n (j === n - 1 ? 1 : dp[np][i][j + 1])) %\n 1000000007\n }\n }\n }\n return dp[1][i][j]\n}\n\n// another\n\n/**\n * @param {number} m\n * @param {number} n\n * @param {number} N\n * @param {number} i\n * @param {number} j\n * @return {number}\n */\nconst findPaths = function (m, n, N, i, j) {\n if (N <= 0) return 0;\n const MOD = 1000000007;\n let count = Array.from({ length: m }, () => new Array(n).fill(0));\n count[i][j] = 1;\n let result = 0;\n const dirs = [\n [-1, 0],\n [1, 0],\n [0, -1],\n [0, 1],\n ];\n for (let step = 0; step < N; step++) {\n const temp = Array.from({ length: m }, () => new Array(n).fill(0));\n for (let r = 0; r < m; r++) {\n for (let c = 0; c < n; c++) {\n for (let d of dirs) {\n const nr = r + d[0];\n const nc = c + d[1];\n if (nr < 0 || nr >= m || nc < 0 || nc >= n) {\n result = (result + count[r][c]) % MOD;\n } else {\n temp[nr][nc] = (temp[nr][nc] + count[r][c]) % MOD;\n }\n }\n }\n }\n count = temp;\n }\n return result;\n};\n\n// another\n\n/**\n * @param {number} m\n * @param {number} n\n * @param {number} N\n * @param {number} i\n * @param {number} j\n * @return {number}\n */\nconst findPaths = function (m, n, N, i, j, memo = new Map()) {\n const key = N + ',' + i + ',' + j;\n if (memo.has(key)) return memo.get(key);\n const isOutside = i === -1 || i === m || j === -1 || j === n;\n if (N === 0 || isOutside) return +isOutside;\n memo.set(key, (\n findPaths(m, n, N - 1, i - 1, j, memo)\n + findPaths(m, n, N - 1, i + 1, j, memo)\n + findPaths(m, n, N - 1, i, j + 1, memo)\n + findPaths(m, n, N - 1, i, j - 1, memo)\n ) % 1000000007);\n return memo.get(key);\n}\n\n\n\n" + }, + { + "_id": "66f925ddfdfb8e1665720bf9", + "questionid": 302, + "title": "Shortest Unsorted Continuous Subarray", + "slug": "shortest-unsorted-continuous-subarray", + "description": "Given an integer array nums, you need to find one continuous subarray that if you only sort this subarray in ascending order, then the whole array will be sorted in ascending order. Return the shortest such subarray and output its length. ", + "category": [ + "Array", + "Two Pointers", + "Stack", + "Greedy", + "Sorting", + "Monotonic Stack" + ], + "complexity": "Medium", + "successrate": 34.2, + "totalsubmissions": 631258, + "totalaccepted": 215582, + "likes": 4950, + "dislikes": 201, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [2,6,4,8,10,9,15]", + "expected_output": "5", + "explanation": "You need to sort [6, 4, 8, 10, 9] in ascending order to make the whole array sorted in ascending order." + }, + { + "example_num": 2, + "expected_input": "nums = [1,2,3,4]", + "expected_output": "0", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "nums = [1]", + "expected_output": "0", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} nums\n * @return {number}\n */\nconst findUnsortedSubarray = function(nums) {\n let stack = []\n let left = nums.length\n let right = 0\n for(let i = 0; i < nums.length; i++) {\n while(stack.length > 0 && nums[stack[stack.length - 1]] > nums[i]) {\n left = Math.min(left, stack.pop())\n }\n stack.push(i)\n }\n stack = []\n for(let i = nums.length - 1; i >= 0; i--) {\n while(stack.length > 0 && nums[stack[stack.length - 1]] < nums[i] ) {\n right = Math.max(right, stack.pop())\n }\n stack.push(i)\n }\n \n \n return right > left ? right - left + 1: 0\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720c03", + "questionid": 312, + "title": "Construct String from Binary Tree", + "slug": "construct-string-from-binary-tree", + "description": "Given the root of a binary tree, construct a string consisting of parenthesis and integers from a binary tree with the preorder traversal way, and return it. Omit all the empty parenthesis pairs that do not affect the one-to-one mapping relationship between the string and the original binary tree. ", + "category": [ + "String", + "Tree", + "Depth-First Search", + "Binary Tree" + ], + "complexity": "Easy", + "successrate": 57.6, + "totalsubmissions": 220994, + "totalaccepted": 127369, + "likes": 1343, + "dislikes": 1714, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [1,2,3,4]", + "expected_output": ""1(2(4))(3)"", + "explanation": "Originally, it needs to be "1(2(4)())(3()())", but you need to omit all the empty parenthesis pairs. And it will be "1(2(4))(3)"." + }, + { + "example_num": 2, + "expected_input": "root = [1,2,3,null,4]", + "expected_output": ""1(2()(4))(3)"", + "explanation": "Almost the same as the first example, except the () after 2 is necessary to indicate the absence of a left child for 2 and the presence of a right child." + } + ], + "solution": "/**\n * Definition for a binary tree node.\n * function TreeNode(val) {\n * this.val = val;\n * this.left = this.right = null;\n * }\n */\n/**\n * @param {TreeNode} t\n * @return {string}\n */\nconst tree2str = function(t) {\n if (!t) return ''\n const left = tree2str(t.left)\n const right = tree2str(t.right)\n if (right) return `${t.val}(${left})(${right})`\n else if (left) return `${t.val}(${left})`\n else return `${t.val}`\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720c0a", + "questionid": 319, + "title": "Sum of Square Numbers", + "slug": "sum-of-square-numbers", + "description": "Given a non-negative integer c, decide whether there're two integers a and b such that a2 + b2 = c. ", + "category": [ + "Math", + "Two Pointers", + "Binary Search" + ], + "complexity": "Medium", + "successrate": 34.6, + "totalsubmissions": 382523, + "totalaccepted": 132443, + "likes": 1360, + "dislikes": 462, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "c = 5", + "expected_output": "true", + "explanation": "1 * 1 + 2 * 2 = 5" + }, + { + "example_num": 2, + "expected_input": "c = 3", + "expected_output": "false", + "explanation": "" + } + ], + "solution": "/**\n * @param {number} c\n * @return {boolean}\n */\nconst judgeSquareSum = function(c) {\n if (c < 0) return false;\n const max = Math.floor(Math.sqrt(c));\n for (let i = 0; i < max + 1; i++) {\n if (Number.isInteger(Math.sqrt(c - i * i))) {\n return true;\n }\n }\n return false;\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720bcf", + "questionid": 260, + "title": "Max Consecutive Ones", + "slug": "max-consecutive-ones", + "description": "Given a binary array nums, return the maximum number of consecutive 1's in the array. ", + "category": [ + "Array" + ], + "complexity": "Easy", + "successrate": 55, + "totalsubmissions": 1160124, + "totalaccepted": 638413, + "likes": 2517, + "dislikes": 395, + "hints": "You need to think about two things as far as any window is concerned. One is the starting point for the window. How do you detect that a new window of 1s has started? The next part is detecting the ending point for this window.\r\n\r\nHow do you detect the ending point for an existing window? If you figure these two things out, you will be able to detect the windows of consecutive ones. All that remains afterward is to find the longest such window and return the size.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,1,0,1,1,1]", + "expected_output": "3", + "explanation": "The first two digits or the last three digits are consecutive 1s. The maximum number of consecutive 1s is 3." + }, + { + "example_num": 2, + "expected_input": "nums = [1,0,1,1,0,1]", + "expected_output": "2", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} nums\n * @return {number}\n */\nconst findMaxConsecutiveOnes = function(nums) {\n let sum = 0,\n max = 0;\n\n for (let i = 0; i < nums.length; i++) {\n let temp = sum;\n sum += nums[i];\n if (temp === sum || i === nums.length - 1) {\n max = Math.max(sum, max);\n sum = 0;\n }\n }\n\n return max;\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720bd3", + "questionid": 264, + "title": "Teemo Attacking", + "slug": "teemo-attacking", + "description": "Our hero Teemo is attacking an enemy Ashe with poison attacks! When Teemo attacks Ashe, Ashe gets poisoned for a exactly duration seconds. More formally, an attack at second t will mean Ashe is poisoned during the inclusive time interval [t, t + duration - 1]. If Teemo attacks again before the poison effect ends, the timer for it is reset, and the poison effect will end duration seconds after the new attack. You are given a non-decreasing integer array timeSeries, where timeSeries[i] denotes that Teemo attacks Ashe at second timeSeries[i], and an integer duration. Return the total number of seconds that Ashe is poisoned. ", + "category": [ + "Array", + "Simulation" + ], + "complexity": "Easy", + "successrate": 56.8, + "totalsubmissions": 171664, + "totalaccepted": 97561, + "likes": 396, + "dislikes": 37, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "timeSeries = [1,4], duration = 2", + "expected_output": "4", + "explanation": "Teemo's attacks on Ashe go as follows:\n- At second 1, Teemo attacks, and Ashe is poisoned for seconds 1 and 2.\n- At second 4, Teemo attacks, and Ashe is poisoned for seconds 4 and 5.\nAshe is poisoned for seconds 1, 2, 4, and 5, which is 4 seconds in total." + }, + { + "example_num": 2, + "expected_input": "timeSeries = [1,2], duration = 2", + "expected_output": "3", + "explanation": "Teemo's attacks on Ashe go as follows:\n- At second 1, Teemo attacks, and Ashe is poisoned for seconds 1 and 2.\n- At second 2 however, Teemo attacks again and resets the poison timer. Ashe is poisoned for seconds 2 and 3.\nAshe is poisoned for seconds 1, 2, and 3, which is 3 seconds in total." + } + ], + "solution": "/**\n * @param {number[]} timeSeries\n * @param {number} duration\n * @return {number}\n */\nconst findPoisonedDuration = function(timeSeries, duration) {\n if (timeSeries == null || timeSeries.length === 0) return 0\n let res = 0\n for (let i = 1, len = timeSeries.length; i < len; i++) {\n const tmp =\n timeSeries[i - 1] + duration > timeSeries[i]\n ? timeSeries[i] - timeSeries[i - 1]\n : duration\n res += tmp\n }\n return res + duration\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720bd5", + "questionid": 266, + "title": "Diagonal Traverse", + "slug": "diagonal-traverse", + "description": "Given an m x n matrix mat, return an array of all the elements of the array in a diagonal order. ", + "category": [ + "Array", + "Matrix", + "Simulation" + ], + "complexity": "Medium", + "successrate": 56.5, + "totalsubmissions": 344843, + "totalaccepted": 194981, + "likes": 2118, + "dislikes": 524, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "mat = [[1,2,3],[4,5,6],[7,8,9]]", + "expected_output": "[1,2,4,7,5,3,6,8,9]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "mat = [[1,2],[3,4]]", + "expected_output": "[1,2,3,4]", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[][]} matrix\n * @return {number[]}\n */\nconst findDiagonalOrder = function(matrix) {\n if (!matrix.length || !matrix[0].length) {\n return []\n }\n const m = matrix.length\n const n = matrix[0].length\n const output = []\n for (let sum = 0; sum <= m + n - 2; sum++) {\n for (\n let i = Math.min(m - 1, sum);\n sum % 2 === 0 && isValid(i, sum - i, m, n);\n i--\n ) {\n const j = sum - i\n output.push(matrix[i][j])\n }\n for (\n let j = Math.min(n - 1, sum);\n sum % 2 === 1 && isValid(sum - j, j, m, n);\n j--\n ) {\n const i = sum - j\n output.push(matrix[i][j])\n }\n }\n return output\n}\n\nfunction isValid(i, j, m, n) {\n if (i < 0 || i >= m || j < 0 || j >= n) {\n return false\n }\n return true\n}\n\n// another\n\n/**\n * @param {number[][]} matrix\n * @return {number[]}\n */\nconst findDiagonalOrder = function(matrix) {\n if (matrix.length == 0) return []\n let r = 0,\n c = 0,\n m = matrix.length,\n n = matrix[0].length,\n arr = new Array(m * n)\n for (let i = 0; i < arr.length; i++) {\n arr[i] = matrix[r][c]\n if ((r + c) % 2 === 0) {\n // moving up\n if (c === n - 1) {\n r++\n } else if (r === 0) {\n c++\n } else {\n r--\n c++\n }\n } else {\n // moving down\n if (r === m - 1) {\n c++\n } else if (c === 0) {\n r++\n } else {\n r++\n c--\n }\n }\n }\n return arr\n}\n\n\n\n" + }, + { + "_id": "66f925ddfdfb8e1665720bdb", + "questionid": 272, + "title": "Find Bottom Left Tree Value", + "slug": "find-bottom-left-tree-value", + "description": "Given the root of a binary tree, return the leftmost value in the last row of the tree. ", + "category": [ + "Tree", + "Depth-First Search", + "Breadth-First Search", + "Binary Tree" + ], + "complexity": "Medium", + "successrate": 65.2, + "totalsubmissions": 259658, + "totalaccepted": 169188, + "likes": 2052, + "dislikes": 213, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [2,1,3]", + "expected_output": "1", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "root = [1,2,3,4,null,5,6,null,null,7]", + "expected_output": "7", + "explanation": "" + } + ], + "solution": "/**\n * Definition for a binary tree node.\n * function TreeNode(val) {\n * this.val = val;\n * this.left = this.right = null;\n * }\n */\n/**\n * @param {TreeNode} root\n * @return {number}\n */\nconst findBottomLeftValue = function(root) {\n const res = [];\n single(root, 0, res);\n return res[res.length - 1][0].val;\n};\n\nfunction single(node, row, arr) {\n if (node == null) {\n return null;\n }\n if (row < arr.length) {\n arr[row].push(node);\n } else {\n arr[row] = [node];\n }\n single(node.left, row + 1, arr);\n single(node.right, row + 1, arr);\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720be4", + "questionid": 281, + "title": "Contiguous Array", + "slug": "contiguous-array", + "description": "Given a binary array nums, return the maximum length of a contiguous subarray with an equal number of 0 and 1. ", + "category": [ + "Array", + "Hash Table", + "Prefix Sum" + ], + "complexity": "Medium", + "successrate": 46.3, + "totalsubmissions": 558046, + "totalaccepted": 258336, + "likes": 5250, + "dislikes": 227, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [0,1]", + "expected_output": "2", + "explanation": "[0, 1] is the longest contiguous subarray with an equal number of 0 and 1." + }, + { + "example_num": 2, + "expected_input": "nums = [0,1,0]", + "expected_output": "2", + "explanation": "[0, 1] (or [1, 0]) is a longest contiguous subarray with equal number of 0 and 1." + } + ], + "solution": "/**\n * @param {number[]} nums\n * @return {number}\n */\nconst findMaxLength = function(nums) {\n let res = 0, sum = 0\n const hash = {0: -1}, n = nums.length\n \n for(let i = 0; i < n; i++) {\n const cur = nums[i]\n sum += cur === 0 ? -1 : 1\n if(hash[sum] != null) {\n res = Math.max(res, i - hash[sum])\n } else {\n hash[sum] = i\n }\n \n }\n \n return res\n};\n\n// another\n\n/**\n * @param {number[]} nums\n * @return {number}\n */\nconst findMaxLength = function (nums) {\n const map = new Map()\n map.set(0, -1)\n let count = 0\n let max = 0\n for (let i = 0; i < nums.length; i++) {\n let num = nums[i]\n if (num === 0) {\n count -= 1\n }\n if (num === 1) {\n count += 1\n }\n if (map.has(count)) {\n max = Math.max(max, i - map.get(count))\n } else {\n map.set(count, i)\n }\n }\n return max\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720be5", + "questionid": 282, + "title": "Swapping Nodes in a Linked List", + "slug": "swapping-nodes-in-a-linked-list", + "description": "You are given the head of a linked list, and an integer k. Return the head of the linked list after swapping the values of the kth node from the beginning and the kth node from the end (the list is 1-indexed). ", + "category": [ + "Linked List", + "Two Pointers" + ], + "complexity": "Medium", + "successrate": 68.4, + "totalsubmissions": 229189, + "totalaccepted": 156841, + "likes": 2691, + "dislikes": 100, + "hints": "We can transform the linked list to an array this should ease things up After transforming the linked list to an array it becomes as easy as swapping two integers in an array then rebuilding the linked list", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "head = [1,2,3,4,5], k = 2", + "expected_output": "[1,4,3,2,5]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "head = [7,9,6,6,7,8,3,0,9,5], k = 5", + "expected_output": "[7,9,6,6,8,7,3,0,9,5]", + "explanation": "" + } + ], + "solution": "/**\n * Definition for singly-linked list.\n * function ListNode(val, next) {\n * this.val = (val===undefined ? 0 : val)\n * this.next = (next===undefined ? null : next)\n * }\n */\n/**\n * @param {ListNode} head\n * @param {number} k\n * @return {ListNode}\n */\nconst swapNodes = function(head, k) {\n const dummy = new ListNode()\n dummy.next = head\n const arr = []\n let cur = head\n while(cur) {\n arr.push(cur)\n cur = cur.next\n }\n const n = arr.length\n if(k < 1 || k > n) return dummy.next\n let first = arr[k - 1], second = arr[n - k]\n \n arr[k - 1] = second\n arr[n - k] = first\n \n dummy.next = arr[0]\n let pre = arr[0]\n for(let i = 1, len = arr.length; i < len; i++) {\n const tmp = arr[i]\n pre.next = tmp\n pre = tmp\n }\n \n pre.next = null\n \n return dummy.next\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720bef", + "questionid": 292, + "title": "Reverse Words in a String III", + "slug": "reverse-words-in-a-string-iii", + "description": "Given a string s, reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order. ", + "category": [ + "Two Pointers", + "String" + ], + "complexity": "Easy", + "successrate": 78.5, + "totalsubmissions": 548465, + "totalaccepted": 430729, + "likes": 2698, + "dislikes": 160, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "Let's take LeetCode contest"", + "expected_output": ""s'teL ekat edoCteeL tsetnoc"", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "s = "Mr Ding"", + "expected_output": ""rM gniD"", + "explanation": "" + } + ], + "solution": null + }, + { + "_id": "66f925ddfdfb8e1665720bf7", + "questionid": 300, + "title": "Distribute Candies", + "slug": "distribute-candies", + "description": "Alice has n candies, where the ith candy is of type candyType[i]. Alice noticed that she started to gain weight, so she visited a doctor. The doctor advised Alice to only eat n / 2 of the candies she has (n is always even). Alice likes her candies very much, and she wants to eat the maximum number of different types of candies while still following the doctor's advice. Given the integer array candyType of length n, return the maximum number of different types of candies she can eat if she only eats n / 2 of them. ", + "category": [ + "Array", + "Hash Table" + ], + "complexity": "Easy", + "successrate": 65.6, + "totalsubmissions": 308181, + "totalaccepted": 202137, + "likes": 936, + "dislikes": 1147, + "hints": "To maximize the number of kinds of candies, we should try to distribute candies such that sister will gain all kinds. What is the upper limit of the number of kinds of candies sister will gain? Remember candies are to distributed equally. Which data structure is the most suitable for finding the number of kinds of candies? Will hashset solves the problem? Inserting all candies kind in the hashset and then checking its size with upper limit.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "candyType = [1,1,2,2,3,3]", + "expected_output": "3", + "explanation": "Alice can only eat 6 / 2 = 3 candies. Since there are only 3 types, she can eat one of each type." + }, + { + "example_num": 2, + "expected_input": "candyType = [1,1,2,3]", + "expected_output": "2", + "explanation": "Alice can only eat 4 / 2 = 2 candies. Whether she eats types [1,2], [1,3], or [2,3], she still can only eat 2 different types." + }, + { + "example_num": 3, + "expected_input": "candyType = [6,6,6,6]", + "expected_output": "1", + "explanation": "Alice can only eat 4 / 2 = 2 candies. Even though she can eat 2 candies, she only has 1 type." + } + ], + "solution": "/**\n * @param {number[]} candies\n * @return {number}\n */\nconst distributeCandies = function(candies) {\n const uniqNum = candies.filter((el, idx, arr) => arr.indexOf(el) === idx)\n .length;\n const halfNum = candies.length / 2;\n return halfNum > uniqNum ? uniqNum : halfNum;\n};\n\nconsole.log(distributeCandies([1, 1, 2, 2, 3, 3]));\nconsole.log(distributeCandies([1, 1, 2, 3]));\n" + }, + { + "_id": "66f925ddfdfb8e1665720bfa", + "questionid": 303, + "title": "Delete Operation for Two Strings", + "slug": "delete-operation-for-two-strings", + "description": "Given two strings word1 and word2, return the minimum number of steps required to make word1 and word2 the same. In one step, you can delete exactly one character in either string. ", + "category": [ + "String", + "Dynamic Programming" + ], + "complexity": "Medium", + "successrate": 55.7, + "totalsubmissions": 203295, + "totalaccepted": 113212, + "likes": 2708, + "dislikes": 45, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "word1 = "sea", word2 = "eat"", + "expected_output": "2", + "explanation": "You need one step to make "sea" to "ea" and another step to make "eat" to "ea"." + }, + { + "example_num": 2, + "expected_input": "word1 = "leetcode", word2 = "etco"", + "expected_output": "4", + "explanation": "" + } + ], + "solution": "/**\n * @param {string} word1\n * @param {string} word2\n * @return {number}\n */\nconst minDistance = function (word1, word2, memo = new Map()) {\n if (word1 === word2) return 0\n if (word1 === '' || word2 === '') return Math.max(word1.length, word2.length)\n const len1 = word1.length\n const len2 = word2.length\n if (memo.has(`${word1}-${word2}`)) return memo.get(`${word1}-${word2}`)\n let res\n if (word1[len1 - 1] === word2[len2 - 1]) {\n res = minDistance(word1.slice(0, len1 - 1), word2.slice(0, len2 - 1), memo)\n } else {\n res =\n 1 +\n Math.min(\n minDistance(word1.slice(0, len1 - 1), word2, memo),\n minDistance(word1, word2.slice(0, len2 - 1), memo)\n )\n }\n memo.set(`${word1}-${word2}`, res)\n return res\n}\n\n// another\n\n/**\n * @param {string} word1\n * @param {string} word2\n * @return {number}\n */\nconst minDistance = function (word1, word2) {\n const len1 = word1.length\n const len2 = word2.length\n const dp = Array.from({ length: len1 + 1 }, () => new Array(len2 + 1).fill(0))\n for(let i = 1; i <= len1; i++) {\n for(let j = 1; j<= len2; j++) {\n if(word1[i - 1] === word2[j - 1]) dp[i][j] = dp[i - 1][j - 1] + 1\n else dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1])\n }\n }\n return len1 + len2 - dp[len1][len2] * 2\n}\n\n// another\n\n/**\n * @param {string} word1\n * @param {string} word2\n * @return {number}\n */\nconst minDistance = function (word1, word2) {\n const len1 = word1.length\n const len2 = word2.length\n const dp = Array.from({ length: len1 + 1 }, () => new Array(len2 + 1).fill(0))\n for(let i = 1; i <= len2; i++) {\n dp[0][i] = i\n }\n for(let j = 1; j <= len1; j++) {\n dp[j][0] = j\n }\n for(let i = 1; i <= len1; i++) {\n for(let j = 1; j<= len2; j++) {\n if(word1[i - 1] === word2[j - 1]) dp[i][j] = dp[i - 1][j - 1]\n else dp[i][j] = Math.min(dp[i - 1][j], dp[i][j - 1]) + 1\n }\n }\n return dp[len1][len2]\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720bff", + "questionid": 308, + "title": "Range Addition II", + "slug": "range-addition-ii", + "description": "You are given an m x n matrix M initialized with all 0's and an array of operations ops, where ops[i] = [ai, bi] means M[x][y] should be incremented by one for all 0 <= x < ai and 0 <= y < bi. Count and return the number of maximum integers in the matrix after performing all the operations. ", + "category": [ + "Array", + "Math" + ], + "complexity": "Easy", + "successrate": 54.7, + "totalsubmissions": 141345, + "totalaccepted": 77261, + "likes": 649, + "dislikes": 803, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "m = 3, n = 3, ops = [[2,2],[3,3]]", + "expected_output": "4", + "explanation": "The maximum integer in M is 2, and there are four of it in M. So return 4." + }, + { + "example_num": 2, + "expected_input": "m = 3, n = 3, ops = [[2,2],[3,3],[3,3],[3,3],[2,2],[3,3],[3,3],[3,3],[2,2],[3,3],[3,3],[3,3]]", + "expected_output": "4", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "m = 3, n = 3, ops = []", + "expected_output": "9", + "explanation": "" + } + ], + "solution": "/**\n * @param {number} m\n * @param {number} n\n * @param {number[][]} ops\n * @return {number}\n */\nconst maxCount = function (m, n, ops) {\n for (let i = 0, len = ops.length; i < len; i++) {\n if (ops[i][0] < m) m = ops[i][0]\n if (ops[i][1] < n) n = ops[i][1]\n }\n return m * n\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720c01", + "questionid": 310, + "title": "Non-negative Integers without Consecutive Ones", + "slug": "non-negative-integers-without-consecutive-ones", + "description": "Given a positive integer n, return the number of the integers in the range [0, n] whose binary representations do not contain consecutive ones. ", + "category": [ + "Dynamic Programming" + ], + "complexity": "Hard", + "successrate": 38.8, + "totalsubmissions": 78458, + "totalaccepted": 30430, + "likes": 1055, + "dislikes": 114, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 5", + "expected_output": "5", + "explanation": "Here are the non-negative integers <= 5 with their corresponding binary representations:\n0 : 0\n1 : 1\n2 : 10\n3 : 11\n4 : 100\n5 : 101\nAmong them, only integer 3 disobeys the rule (two consecutive ones) and the other 5 satisfy the rule." + }, + { + "example_num": 2, + "expected_input": "n = 1", + "expected_output": "2", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "n = 2", + "expected_output": "3", + "explanation": "" + } + ], + "solution": "/**\n * @param {number} num\n * @return {number}\n */\nconst findIntegers = function (num) {\n const binary = num.toString(2)\n const fibonacci = [1, 2]\n for (let i = 2; i < binary.length; ++i) {\n fibonacci.push(fibonacci[i - 2] + fibonacci[i - 1])\n }\n let answer = binary.indexOf('11') === -1 ? 1 : 0\n for (let i = 0; i < binary.length; ++i) {\n if (binary[i] === '1') {\n answer += fibonacci[binary.length - 1 - i]\n if (binary[i - 1] === '1') {\n break\n }\n }\n }\n return answer\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720c02", + "questionid": 311, + "title": "Can Place Flowers", + "slug": "can-place-flowers", + "description": "You have a long flowerbed in which some of the plots are planted, and some are not. However, flowers cannot be planted in adjacent plots. Given an integer array flowerbed containing 0's and 1's, where 0 means empty and 1 means not empty, and an integer n, return if n new flowers can be planted in the flowerbed without violating the no-adjacent-flowers rule. ", + "category": [ + "Array", + "Greedy" + ], + "complexity": "Easy", + "successrate": 33.1, + "totalsubmissions": 874930, + "totalaccepted": 289310, + "likes": 2857, + "dislikes": 641, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "flowerbed = [1,0,0,0,1], n = 1", + "expected_output": "true", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "flowerbed = [1,0,0,0,1], n = 2", + "expected_output": "false", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} flowerbed\n * @param {number} n\n * @return {boolean}\n */\nconst canPlaceFlowers = function(flowerbed, n) {\n let count = 0\n const clone = flowerbed\n for(let i = 0; i < clone.length; i++) {\n if(clone[i] === 0) {\n if(i === 0 && (clone[i + 1] === 0 || clone[i+1] == null)){\n count++\n clone[i] = 1\n }\n if(i > 0 && i < clone.length - 1 && clone[i - 1] === 0 && clone[i + 1] === 0) {\n count++\n clone[i] = 1\n }\n if(i === clone.length - 1 && clone[i - 1] === 0 && clone[i] === 0) {\n count++\n clone[i] = 1\n }\n }\n }\n \n return count >= n ? true : false\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720c07", + "questionid": 316, + "title": "K Inverse Pairs Array", + "slug": "k-inverse-pairs-array", + "description": "For an integer array nums, an inverse pair is a pair of integers [i, j] where 0 <= i < j < nums.length and nums[i] > nums[j]. Given two integers n and k, return the number of different arrays consist of numbers from 1 to n such that there are exactly k inverse pairs. Since the answer can be huge, return it modulo 109 + 7. ", + "category": [ + "Dynamic Programming" + ], + "complexity": "Hard", + "successrate": 37.3, + "totalsubmissions": 66438, + "totalaccepted": 24766, + "likes": 752, + "dislikes": 108, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 3, k = 0", + "expected_output": "1", + "explanation": "Only the array [1,2,3] which consists of numbers from 1 to 3 has exactly 0 inverse pairs." + }, + { + "example_num": 2, + "expected_input": "n = 3, k = 1", + "expected_output": "2", + "explanation": "The array [1,3,2] and [2,1,3] have exactly 1 inverse pair." + } + ], + "solution": "/**\n * @param {number} n\n * @param {number} k\n * @return {number}\n */\nconst kInversePairs = function(n, k) {\n const mod = 1e9 + 7\n const dp = Array.from({ length: n + 1 }, () => Array(k + 1).fill(0))\n for(let i = 0; i <= n; i++) dp[i][0] = 1\n for(let i = 2; i <= n; i++) {\n for(let j = 1; j <= k; j++) {\n if(j >= i) dp[i][j] = (dp[i - 1][j] + dp[i][j - 1] - dp[i - 1][j - i]) % mod\n else dp[i][j] = (dp[i - 1][j] + dp[i][j - 1]) % mod\n\n if(dp[i][j] < 0) dp[i][j] += mod\n }\n }\n\n return dp[n][k]\n};\n\n// another\n\n\n/**\n * @param {number} n\n * @param {number} k\n * @return {number}\n */\nconst kInversePairs = function(n, k) {\n const dp = Array.from({ length: n + 1 }, () => new Array(k + 1).fill(0))\n for (let i = 1; i < n + 1; i++) {\n dp[i][0] = 1\n }\n const MOD = 1e9 + 7\n for (let i = 1; i < n + 1; i++) {\n for (let j = 1; j < k + 1; j++) {\n let val = (dp[i - 1][j] - (j >= i ? dp[i - 1][j - i] : 0) + MOD) % MOD\n dp[i][j] = (dp[i][j - 1] + val) % MOD\n }\n }\n return (dp[n][k] - (dp[n][k - 1] || 0) + MOD) % MOD\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720bce", + "questionid": 259, + "title": "Smallest Good Base", + "slug": "smallest-good-base", + "description": "Given an integer n represented as a string, return the smallest good base of n. We call k >= 2 a good base of n, if all digits of n base k are 1's. ", + "category": [ + "Math", + "Binary Search" + ], + "complexity": "Hard", + "successrate": 37.8, + "totalsubmissions": 44231, + "totalaccepted": 16728, + "likes": 265, + "dislikes": 429, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = "13"", + "expected_output": ""3"", + "explanation": "13 base 3 is 111." + }, + { + "example_num": 2, + "expected_input": "n = "4681"", + "expected_output": ""8"", + "explanation": "4681 base 8 is 11111." + }, + { + "example_num": 3, + "expected_input": "n = "1000000000000000000"", + "expected_output": ""999999999999999999"", + "explanation": "1000000000000000000 base 999999999999999999 is 11." + } + ], + "solution": "/**\n * @param {string} n\n * @return {string}\n */\nconst smallestGoodBase = function(n) {\n const N = BigInt(n),\n bigint2 = BigInt(2),\n bigint1 = BigInt(1),\n bigint0 = BigInt(0)\n let maxLen = countLength(N, bigint2)\n for (let length = maxLen; length > 0; length--) {\n let [found, base] = findMatchInHalf(length)\n if (found) return '' + base\n }\n return '' + (N - 1)\n function findMatchInHalf(length, smaller = bigint2, bigger = N) {\n if (smaller > bigger) return [false]\n if (smaller === bigger) {\n return [valueOf1s(smaller, length) === N, smaller]\n }\n let mid = (smaller + bigger) / bigint2\n let val = valueOf1s(mid, length)\n if (val === N) return [true, mid]\n if (val > N) return findMatchInHalf(length, smaller, mid - bigint1)\n return findMatchInHalf(length, mid + bigint1, bigger)\n }\n function valueOf1s(base, lengthOf1s) {\n let t = bigint1\n for (let i = 1; i < lengthOf1s; i++) {\n t *= base\n t += bigint1\n }\n return t\n }\n function countLength(N, base) {\n let t = N,\n len = 0\n while (t > bigint0) {\n t /= base\n len++\n }\n return len\n }\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720bd4", + "questionid": 265, + "title": "Next Greater Element I", + "slug": "next-greater-element-i", + "description": "The next greater element of some element x in an array is the first greater element that is to the right of x in the same array. You are given two distinct 0-indexed integer arrays nums1 and nums2, where nums1 is a subset of nums2. For each 0 <= i < nums1.length, find the index j such that nums1[i] == nums2[j] and determine the next greater element of nums2[j] in nums2. If there is no next greater element, then the answer for this query is -1. Return an array ans of length nums1.length such that ans[i] is the next greater element as described above. ", + "category": [ + "Array", + "Hash Table", + "Stack", + "Monotonic Stack" + ], + "complexity": "Easy", + "successrate": 70, + "totalsubmissions": 496323, + "totalaccepted": 347209, + "likes": 2593, + "dislikes": 176, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums1 = [4,1,2], nums2 = [1,3,4,2]", + "expected_output": "[-1,3,-1]", + "explanation": "The next greater element for each value of nums1 is as follows:\n- 4 is underlined in nums2 = [1,3,4,2]. There is no next greater element, so the answer is -1.\n- 1 is underlined in nums2 = [1,3,4,2]. The next greater element is 3.\n- 2 is underlined in nums2 = [1,3,4,2]. There is no next greater element, so the answer is -1." + }, + { + "example_num": 2, + "expected_input": "nums1 = [2,4], nums2 = [1,2,3,4]", + "expected_output": "[3,-1]", + "explanation": "The next greater element for each value of nums1 is as follows:\n- 2 is underlined in nums2 = [1,2,3,4]. The next greater element is 3.\n- 4 is underlined in nums2 = [1,2,3,4]. There is no next greater element, so the answer is -1." + } + ], + "solution": null + }, + { + "_id": "66f925ddfdfb8e1665720bd8", + "questionid": 269, + "title": "Base 7", + "slug": "base-7", + "description": "Given an integer num, return a string of its base 7 representation. ", + "category": [ + "Math" + ], + "complexity": "Easy", + "successrate": 47.5, + "totalsubmissions": 178434, + "totalaccepted": 84670, + "likes": 464, + "dislikes": 192, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "num = 100", + "expected_output": "\"202\"", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "num = -7", + "expected_output": "\"-10\"", + "explanation": "" + } + ], + "solution": "/**\n * @param {number} num\n * @return {string}\n */\nconst convertToBase7 = function(num) {\n if(num == null) return ''\n const sign = num >= 0 ? '+' : '-'\n let res = ''\n let remain = Math.abs(num)\n if(num === 0) return '0'\n while(remain > 0) {\n res = remain % 7 + res\n remain = Math.floor(remain / 7)\n }\n \n return sign === '+' ? res : '-' + res\n};\n\n// another\n\nconst convertToBase7 = function(num) {\n return num.toString(7)\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720be3", + "questionid": 280, + "title": "Longest Word in Dictionary through Deleting", + "slug": "longest-word-in-dictionary-through-deleting", + "description": "Given a string s and a string array dictionary, return the longest string in the dictionary that can be formed by deleting some of the given string characters. If there is more than one possible result, return the longest word with the smallest lexicographical order. If there is no possible result, return the empty string. ", + "category": [ + "Array", + "Two Pointers", + "String", + "Sorting" + ], + "complexity": "Medium", + "successrate": 50.9, + "totalsubmissions": 245280, + "totalaccepted": 124739, + "likes": 1308, + "dislikes": 329, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "abpcplea", dictionary = ["ale","apple","monkey","plea"]", + "expected_output": ""apple"", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "s = "abpcplea", dictionary = ["a","b","c"]", + "expected_output": ""a"", + "explanation": "" + } + ], + "solution": "/**\n * @param {string} s\n * @param {string[]} dictionary\n * @return {string}\n */\n const findLongestWord = function(s, dictionary) {\n let res = ''\n for (const word of dictionary) {\n let j = 0\n for (let i = 0, len = s.length; i < len; i++) {\n if(word[j] === s[i]) j++\n if(j === word.length) {\n if(word.length > res.length) res = word\n else if(word.length === res.length && word < res) res = word\n break\n }\n }\n }\n return res\n};\n\n// another\n\n/**\n * @param {string} s\n * @param {string[]} dictionary\n * @return {string}\n */\nconst findLongestWord = function (s, dictionary) {\n const n = dictionary.length\n const idxArr = Array(n).fill(0)\n let res = ''\n for (const ch of s) {\n for (let i = 0; i < n; i++) {\n const idx = idxArr[i]\n if (idx >= dictionary[i].length) continue\n if (ch === dictionary[i][idx]) {\n idxArr[i]++\n }\n\n if (\n idxArr[i] === dictionary[i].length &&\n (dictionary[i].length > res.length ||\n (dictionary[i].length === res.length && dictionary[i] < res))\n ) {\n res = dictionary[i]\n }\n }\n }\n return res\n}\n\n\n// another\n\n/**\n * @param {string} s\n * @param {string[]} dictionary\n * @return {string}\n */\nconst findLongestWord = function(s, dictionary) {\n let res = ''\n for(let d of dictionary) {\n let j = 0\n for(let i = 0, n = s.length; i < n; i++) {\n if(d[j] === s[i]) j++\n if(j === d.length && j >= res.length) {\n if(j > res.length || d < res) {\n res = d\n }\n break\n }\n }\n }\n return res\n};\n\n// another\n\n/**\n * @param {string} s\n * @param {string[]} dictionary\n * @return {string}\n */\nconst findLongestWord = function(s, dictionary) {\n dictionary.sort((a, b) => a.length === b.length ? cmp(a, b) : b.length - a.length)\n let res = ''\n for(let d of dictionary) {\n let j = 0\n for(let i = 0, n = s.length; i < n; i++) {\n if(d[j] === s[i]) j++\n if(j === d.length) return d\n }\n }\n return ''\n function cmp(s1, s2) {\n for(let i = 0, n = s1.length; i < n; i++) {\n if(s1[i] < s2[i]) return -1\n else if(s1[i] > s2[i]) return 1\n }\n return 0\n }\n};\n\n// another\n\n\n/**\n * @param {string} s\n * @param {string[]} d\n * @return {string}\n */\nconst findLongestWord = function(s, d) {\n let results = [];\n let maxLen = 0;\n for (const word of d) {\n let j = 0;\n for (let i = 0; i < s.length; i++) {\n if (s[i] === word[j]) {\n j++;\n if (j === word.length) break;\n }\n }\n if (j === word.length && word.length >= maxLen) {\n if (word.length > maxLen) {\n maxLen = word.length;\n results = [];\n }\n results.push(word);\n }\n }\n \n let result = results[0];\n for (let i = 1; i < results.length; i++) {\n if (results[i] < result) result = results[i];\n }\n return result || '';\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720be7", + "questionid": 284, + "title": "Single Element in a Sorted Array", + "slug": "single-element-in-a-sorted-array", + "description": "You are given a sorted array consisting of only integers where every element appears exactly twice, except for one element which appears exactly once. Return the single element that appears only once. Your solution must run in O(log n) time and O(1) space. ", + "category": [ + "Array", + "Binary Search" + ], + "complexity": "Medium", + "successrate": 58.7, + "totalsubmissions": 484707, + "totalaccepted": 284425, + "likes": 4963, + "dislikes": 111, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,1,2,3,3,4,4,8,8]", + "expected_output": "2", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "nums = [3,3,7,7,10,11,11]", + "expected_output": "10", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} nums\n * @return {number}\n */\nconst singleNonDuplicate = function(nums) {\n let i = 0;\n while (true) {\n if (nums[i] == nums[i + 1]) {\n i += 2;\n } else {\n return nums[i];\n }\n }\n};\n\n// another\n\n/**\n * @param {number[]} nums\n * @return {number}\n */\nconst singleNonDuplicate = function(nums) {\n const n = nums.length\n let left = 0, right = n - 1\n while(left < right) {\n const mid = left + ((right - left) >> 1)\n if(nums[mid] === nums[mid ^ 1]) left = mid + 1\n else right = mid\n }\n \n return nums[left]\n};\n\n// another\n\n/**\n * @param {number[]} nums\n * @return {number}\n */\nconst singleNonDuplicate = function(nums) {\n const n = nums.length\n let left = 0, right = n - 1\n while(left < right) {\n const mid = ~~((left + right) / 2)\n if((mid % 2 === 0 && nums[mid] === nums[mid + 1]) || (mid % 2 === 1 && nums[mid] === nums[mid - 1])) left = mid + 1\n else right = mid\n }\n \n return nums[left]\n};\n\n// another\n\n/**\n * @param {number[]} nums\n * @return {number}\n */\nconst singleNonDuplicate = function(nums) {\n if(nums.length === 0) return 0\n let res = nums[0]\n for(let i = 1, len = nums.length; i < len; i++) {\n res ^= nums[i]\n }\n return res\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720beb", + "questionid": 288, + "title": "Remove Boxes", + "slug": "remove-boxes", + "description": "You are given several boxes with different colors represented by different positive numbers. You may experience several rounds to remove boxes until there is no box left. Each time you can choose some continuous boxes with the same color (i.e., composed of k boxes, k >= 1), remove them and get k * k points. Return the maximum points you can get. ", + "category": [ + "Array", + "Dynamic Programming", + "Memoization" + ], + "complexity": "Hard", + "successrate": 47.3, + "totalsubmissions": 71483, + "totalaccepted": 33844, + "likes": 1491, + "dislikes": 92, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "boxes = [1,3,2,2,2,3,4,3,1]", + "expected_output": "23", + "explanation": "[1, 3, 2, 2, 2, 3, 4, 3, 1] \n----> [1, 3, 3, 4, 3, 1] (3*3=9 points) \n----> [1, 3, 3, 3, 1] (1*1=1 points) \n----> [1, 1] (3*3=9 points) \n----> [] (2*2=4 points)" + }, + { + "example_num": 2, + "expected_input": "boxes = [1,1,1]", + "expected_output": "9", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "boxes = [1]", + "expected_output": "1", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} boxes\n * @return {number}\n */\nconst removeBoxes = function(boxes) {\n const n = boxes.length\n const dp = Array.from(new Array(n), () => {\n return Array.from(new Array(n), () => {\n return new Array(n).fill(0)\n })\n })\n return removeBoxesSub(boxes, 0, n - 1, 0, dp)\n};\n\nfunction removeBoxesSub(boxes, i, j, k, dp) {\n if(i > j) return 0;\n if(dp[i][j][k] > 0) return dp[i][j][k]\n for(; i + 1 <= j && boxes[i+1] === boxes[i] ; i++, k++) {\n // optimization: all boxes of the same color counted continuously from the first box should be grouped together\n }\n let res = (k+1) * (k+1) + removeBoxesSub(boxes, i + 1, j, 0, dp)\n for(let m = i + 1; m <= j; m++) {\n if(boxes[i] === boxes[m]) {\n res = Math.max(res, removeBoxesSub(boxes, i + 1, m - 1, 0, dp) + removeBoxesSub(boxes, m, j, k + 1, dp) )\n }\n }\n dp[i][j][k] = res\n return res\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720bec", + "questionid": 289, + "title": "Number of Provinces", + "slug": "number-of-provinces", + "description": "There are n cities. Some of them are connected, while some are not. If city a is connected directly with city b, and city b is connected directly with city c, then city a is connected indirectly with city c. A province is a group of directly or indirectly connected cities and no other cities outside of the group. You are given an n x n matrix isConnected where isConnected[i][j] = 1 if the ith city and the jth city are directly connected, and isConnected[i][j] = 0 otherwise. Return the total number of provinces. ", + "category": [ + "Depth-First Search", + "Breadth-First Search", + "Union Find", + "Graph" + ], + "complexity": "Medium", + "successrate": 62.6, + "totalsubmissions": 713510, + "totalaccepted": 446459, + "likes": 4990, + "dislikes": 235, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "isConnected = [[1,1,0],[1,1,0],[0,0,1]]", + "expected_output": "2", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "isConnected = [[1,0,0],[0,1,0],[0,0,1]]", + "expected_output": "3", + "explanation": "" + } + ], + "solution": null + }, + { + "_id": "66f925ddfdfb8e1665720bf2", + "questionid": 295, + "title": "Binary Tree Tilt", + "slug": "binary-tree-tilt", + "description": "Given the root of a binary tree, return the sum of every tree node's tilt. The tilt of a tree node is the absolute difference between the sum of all left subtree node values and all right subtree node values. If a node does not have a left child, then the sum of the left subtree node values is treated as 0. The rule is similar if the node does not have a right child. ", + "category": [ + "Tree", + "Depth-First Search", + "Binary Tree" + ], + "complexity": "Easy", + "successrate": 58.5, + "totalsubmissions": 282699, + "totalaccepted": 165284, + "likes": 1601, + "dislikes": 1903, + "hints": "Don't think too much, this is an easy problem. Take some small tree as an example. Can a parent node use the values of its child nodes? How will you implement it? May be recursion and tree traversal can help you in implementing. What about postorder traversal, using values of left and right childs?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [1,2,3]", + "expected_output": "1", + "explanation": "Tilt of node 2 : |0-0| = 0 (no children)\nTilt of node 3 : |0-0| = 0 (no children)\nTilt of node 1 : |2-3| = 1 (left subtree is just left child, so sum is 2; right subtree is just right child, so sum is 3)\nSum of every tilt : 0 + 0 + 1 = 1" + }, + { + "example_num": 2, + "expected_input": "root = [4,2,9,3,5,null,7]", + "expected_output": "15", + "explanation": "Tilt of node 3 : |0-0| = 0 (no children)\nTilt of node 5 : |0-0| = 0 (no children)\nTilt of node 7 : |0-0| = 0 (no children)\nTilt of node 2 : |3-5| = 2 (left subtree is just left child, so sum is 3; right subtree is just right child, so sum is 5)\nTilt of node 9 : |0-7| = 7 (no left child, so sum is 0; right subtree is just right child, so sum is 7)\nTilt of node 4 : |(3+5+2)-(9+7)| = |10-16| = 6 (left subtree values are 3, 5, and 2, which sums to 10; right subtree values are 9 and 7, which sums to 16)\nSum of every tilt : 0 + 0 + 0 + 2 + 7 + 6 = 15" + }, + { + "example_num": 3, + "expected_input": "root = [21,7,14,1,1,2,2,3,3]", + "expected_output": "9", + "explanation": "" + } + ], + "solution": "/**\n * Definition for a binary tree node.\n * function TreeNode(val) {\n * this.val = val;\n * this.left = this.right = null;\n * }\n */\n/**\n * @param {TreeNode} root\n * @return {number}\n */\nconst findTilt = function(root) {\n const tilt = { val: 0 }\n dfs(root, tilt)\n function dfs(root, tilt) {\n if (!root) return 0\n let left = dfs(root.left, tilt)\n let right = dfs(root.right, tilt)\n tilt.val += Math.abs(left - right)\n return root.val + left + right\n }\n return tilt.val\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720bf3", + "questionid": 296, + "title": "Find the Closest Palindrome", + "slug": "find-the-closest-palindrome", + "description": "Given a string n representing an integer, return the closest integer (not including itself), which is a palindrome. If there is a tie, return the smaller one. The closest is defined as the absolute difference minimized between two integers. ", + "category": [ + "Math", + "String" + ], + "complexity": "Hard", + "successrate": 21.2, + "totalsubmissions": 145985, + "totalaccepted": 31011, + "likes": 474, + "dislikes": 1117, + "hints": "Will brute force work for this problem? Think of something else. Take some examples like 1234, 999,1000, etc and check their closest palindromes. How many different cases are possible? Do we have to consider only left half or right half of the string or both? Try to find the closest palindrome of these numbers- 12932, 99800, 12120. Did you observe something?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = "123"", + "expected_output": ""121"", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "n = "1"", + "expected_output": ""0"", + "explanation": "0 and 2 are the closest palindromes but we return the smallest which is 0." + } + ], + "solution": "/**\n * @param {string} n\n * @return {string}\n */\nconst nearestPalindromic = function(n) {\n const {floor} = Math\n const str = num => `${num}`\n const a = makeSmaller(n), b = makeGreater(n)\n // console.log(a, b)\n if(delta(b, n) >= delta(n, a)) {\n return a\n }\n return b\n\n function makeGreater(num) {\n const n = num.length\n const arr = num.split('')\n for(let i = 0, j = n - 1; i <= j;) {\n arr[j] = arr[i]\n i++\n j--\n }\n const tmp = arr.join('')\n // console.log(tmp)\n if(tmp > num) return tmp\n let carry = 1\n \n for(let i = floor((n - 1) / 2); i >= 0; i--) {\n const cur = +arr[i] + carry\n if(cur <= 9) {\n arr[i] = str(cur)\n carry = 0\n } else {\n arr[i] = '0'\n carry = 1\n }\n arr[n - 1 - i] = arr[i]\n }\n if(carry) {\n const ta = Array(n + 1).fill('0')\n ta[0] = '1'\n ta[ta.length - 1] = '1'\n return ta.join('')\n }\n return arr.join('')\n }\n\n function makeSmaller(num) {\n const n = num.length\n const arr = num.split('')\n for(let i = 0, j = n - 1; i <= j;) {\n arr[j] = arr[i]\n i++\n j--\n }\n const tmp = arr.join('')\n if(tmp < num) return tmp\n let carry = 1\n for(let i = floor((n - 1) / 2); i >= 0; i--) {\n const cur = +arr[i] - carry\n if(cur >= 0) {\n arr[i] = str(cur)\n carry = 0\n } else {\n arr[i] = '9'\n carry = 1\n }\n arr[n - 1 - i] = arr[i]\n }\n if(arr[0] === '0' && n > 1) {\n return '9'.repeat(n - 1)\n }\n return arr.join('')\n }\n function delta(a, b) {\n return BigInt(a) - BigInt(b)\n }\n};\n\n// another\n\n\n/**\n * @param {bigint | string} n\n * @return {string}\n */\nconst nearestPalindromic = function(n) {\n let bigInt = null\n\n if (typeof n === 'bigint') bigInt = n\n if (typeof n === 'string') bigInt = BigInt(n)\n if (typeof n == null) throw new Error('unknown input type')\n\n // take the number, keep adding 1 to it, then check if it's a palindrome\n const prevPalindrome = getPrevPalindrome(bigInt)\n const nextPalindrome = getNextPalindrome(bigInt)\n\n const scalarPrev = bigInt - prevPalindrome\n const scalarNext = nextPalindrome - bigInt\n\n if (scalarPrev <= scalarNext) return prevPalindrome.toString()\n else return nextPalindrome.toString()\n}\n\n/**\n *\n * @param {bigint} number\n */\nfunction getPrevPalindrome(number) {\n const decrementedNumber =\n typeof number === 'bigint' ? number - BigInt(1) : BigInt(number) - BigInt(1)\n\n if (decrementedNumber.toString().length === 1) return decrementedNumber\n\n const leftSide = getLeftSideNumber(decrementedNumber)\n const palindromedLeft = getPalindromeAsString(leftSide)\n\n const rightSide = getRightSideNumberAsString(decrementedNumber)\n const comparison = compareTwoValues(BigInt(palindromedLeft), BigInt(rightSide))\n if (comparison === 0) {\n // the right side is already the palindromedLeft - return the incrementedNumber\n return decrementedNumber\n }\n if (comparison === 1) {\n // this means the right side is already too far advanced (going downwards) compared to the palindromedLeft,\n // you need to take the leftSideWithBorder, decrement by 1, then return this new number concatenated with\n // the leftSide's palindrome - this is the answer\n const leftWithBorder = getLeftSideNumberWithBorder(decrementedNumber)\n const decremented = leftWithBorder - BigInt(1)\n\n if (decremented === BigInt(0)) return BigInt(9)\n\n const newWhole = BigInt(decremented.toString() + getRightSideNumberAsString(decrementedNumber))\n\n const newLeft = getLeftSideNumber(newWhole)\n const palindromedNewLeft = getPalindromeAsString(newLeft)\n return BigInt(decremented.toString() + palindromedNewLeft.toString())\n }\n if (comparison === -1) {\n // this means the right side can naturally increment to the palindromedLeft,\n // so you can just return the leftSideWithBorder concatenated with the palindromedLeft\n const leftSideWithBorder = getLeftSideNumberWithBorder(decrementedNumber)\n return BigInt(leftSideWithBorder.toString() + palindromedLeft)\n }\n}\n\n/**\n *\n * @param {bigint} number\n * @returns {*}\n */\nfunction getNextPalindrome(number) {\n const incrementedNumber =\n typeof number === 'bigint' ? number + BigInt(1) : BigInt(number) + BigInt(1)\n\n if (incrementedNumber.toString().length === 1) return incrementedNumber\n\n const leftSide = getLeftSideNumber(incrementedNumber)\n const palindromedLeft = getPalindromeAsString(leftSide)\n\n const rightSide = getRightSideNumberAsString(incrementedNumber)\n const comparison = compareTwoValues(BigInt(palindromedLeft), BigInt(rightSide))\n if (comparison === 0) {\n // the right side is already the palindromedLeft - return the incrementedNumber\n return incrementedNumber\n }\n if (comparison === 1) {\n // this means the right side can naturally increment to the palindromedLeft,\n // so you can just return the leftSideWithBorder concatenated with the palindromedLeft\n const leftSideWithBorder = getLeftSideNumberWithBorder(incrementedNumber)\n const leftAsString = leftSideWithBorder.toString()\n const combined = leftAsString + palindromedLeft\n return BigInt(combined)\n }\n if (comparison === -1) {\n // this means the right side is already too far advanced compared to the palindromedLeft,\n // you need to take the leftSideWithBorder, increment by 1, then return this new number concatenated with\n // the leftSide's palindrome - this is the answer\n const leftWithBorder = getLeftSideNumberWithBorder(incrementedNumber)\n const incrementedLeftWithBorder = leftWithBorder + BigInt(1)\n const newWhole = BigInt(\n incrementedLeftWithBorder.toString() + getRightSideNumberAsString(incrementedNumber)\n )\n\n const newLeft = getLeftSideNumber(newWhole)\n const palindromedNewLeft = getPalindromeAsString(newLeft)\n return BigInt(incrementedLeftWithBorder.toString() + palindromedNewLeft.toString())\n }\n}\n\n/**\n *\n * @param {bigint} number\n */\nfunction getLeftSideNumber(number) {\n const numberAsText = number.toString()\n const numCharsInLeftSide = Math.floor(numberAsText.length / 2)\n return BigInt(numberAsText.slice(0, numCharsInLeftSide))\n}\n\n/**\n *\n * @param {bigint} number\n * @returns {bigint}\n */\nfunction getLeftSideNumberWithBorder(number) {\n const numberAsText = number.toString()\n const hasOddNumChars = numberAsText.length % 2 === 1\n\n const left = getLeftSideNumber(number)\n\n // should return the left side only, if it's an even-digited number\n // else, return the left side together with the border number (since it's an odd-digited number)\n if (hasOddNumChars) {\n const middleChar = numberAsText.charAt(Math.floor(numberAsText.length / 2))\n return BigInt(left.toString() + middleChar)\n } else {\n return BigInt(left.toString())\n }\n}\n\n/**\n *\n * @param {bigint} number\n * @returns {string}\n */\nfunction getRightSideNumberAsString(number) {\n const numberAsText = number.toString()\n const numCharsInRightSide = Math.floor(numberAsText.length / 2)\n return numberAsText.slice(numberAsText.length - numCharsInRightSide)\n}\n\n/**\n *\n * @param {bigint} number\n * @returns {string}\n */\nfunction getPalindromeAsString(number) {\n const numberAsText = number.toString()\n return numberAsText\n .split('')\n .reverse()\n .join('')\n}\n\n/**\n *\n * @param {bigint} number1\n * @param {bigint} number2\n * @returns {number}\n */\nfunction compareTwoValues(number1, number2) {\n if (number1 < number2) return -1\n if (number1 === number2) return 0\n if (number1 > number2) return 1\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720bf5", + "questionid": 298, + "title": "Permutation in String", + "slug": "permutation-in-string", + "description": "Given two strings s1 and s2, return true if s2 contains a permutation of s1, or false otherwise. In other words, return true if one of s1's permutations is the substring of s2. ", + "category": [ + "Hash Table", + "Two Pointers", + "String", + "Sliding Window" + ], + "complexity": "Medium", + "successrate": 44.8, + "totalsubmissions": 824372, + "totalaccepted": 369629, + "likes": 5663, + "dislikes": 164, + "hints": "Obviously, brute force will result in TLE. Think of something else. How will you check whether one string is a permutation of another string? One way is to sort the string and then compare. But, Is there a better way? If one string is a permutation of another string then they must one common metric. What is that? Both strings must have same character frequencies, if one is permutation of another. Which data structure should be used to store frequencies? What about hash table? An array of size 26?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s1 = "ab", s2 = "eidbaooo"", + "expected_output": "true", + "explanation": "s2 contains one permutation of s1 ("ba")." + }, + { + "example_num": 2, + "expected_input": "s1 = "ab", s2 = "eidboaoo"", + "expected_output": "false", + "explanation": "" + } + ], + "solution": "/**\n * @param {string} s1\n * @param {string} s2\n * @return {boolean}\n */\nconst checkInclusion = function(s1, s2) {\n if(s1.length > s2.length) return false\n const s1map = new Array(26).fill(0)\n const s2map = new Array(26).fill(0)\n const aCode = ('a').charCodeAt(0)\n const zCode = ('z').charCodeAt(0)\n \n for(let i = 0; i < s1.length; i++) {\n s1map[s1.charCodeAt(i) - aCode]++\n s2map[s2.charCodeAt(i) - aCode]++\n }\n \n for(let i = 0; i < s2.length - s1.length; i++) {\n if(matches(s1map, s2map)) return true\n s2map[s2.charCodeAt(i + s1.length) - aCode]++\n s2map[s2.charCodeAt(i) - aCode]--\n }\n \n return matches(s1map, s2map)\n \n};\n\nfunction matches(s1map, s2map) {\n for(let i = 0; i < 26; i++) {\n if(s1map[i] !== s2map[i]) return false\n }\n return true\n}\n\n\n// another\n\n/**\n * @param {string} s1\n * @param {string} s2\n * @return {boolean}\n */\nconst checkInclusion = function(s1, s2) {\n const arr = Array(26).fill(0)\n const a = 'a'.charCodeAt(0)\n const s1l = s1.length\n for(let c of s1) arr[c.charCodeAt(0) - a] += 1\n for(let i = 0, len = s2.length; i < len; i++) {\n const tmp = s2[i]\n arr[tmp.charCodeAt(0) - a]--\n if(i >= s1l - 1) {\n if(allZeros(arr)) return true\n arr[s2.charCodeAt(i - s1l + 1) - a]++\n }\n \n }\n \n return false\n};\n\nfunction allZeros(arr) {\n for(let e of arr) {\n if(e !== 0) return false\n }\n return true\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720bfc", + "questionid": 305, + "title": "Fraction Addition and Subtraction", + "slug": "fraction-addition-and-subtraction", + "description": "Given a string expression representing an expression of fraction addition and subtraction, return the calculation result in string format. The final result should be an irreducible fraction. If your final result is an integer, change it to the format of a fraction that has a denominator 1. So in this case, 2 should be converted to 2/1. ", + "category": [ + "Math", + "String", + "Simulation" + ], + "complexity": "Medium", + "successrate": 51.7, + "totalsubmissions": 55560, + "totalaccepted": 28714, + "likes": 303, + "dislikes": 435, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "expression = "-1/2+1/2"", + "expected_output": ""0/1"", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "expression = "-1/2+1/2+1/3"", + "expected_output": ""1/3"", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "expression = "1/3-1/2"", + "expected_output": ""-1/6"", + "explanation": "" + } + ], + "solution": "/**\n * @param {string} expression\n * @return {string}\n */\nconst fractionAddition = function (expression) {\n if (expression[0] === '-') expression = '0/1' + expression\n const terms = expression.split(/[+-]/g)\n const ops = '+' + expression.replace(/[^+-]/g, '')\n const nums = [],\n dens = []\n for (let term of terms) {\n let t = term.split('/')\n nums.push(parseInt(t[0]))\n dens.push(parseInt(t[1]))\n }\n const lcm = LCM(dens)\n const numSum = nums.reduce(\n (sum, num, i) => sum + ((+(ops[i] === '+') || -1) * num * lcm) / dens[i],\n 0\n )\n const gcd = Math.abs(GCD(numSum, lcm))\n return numSum / gcd + '/' + lcm / gcd\n}\n\nfunction LCM(arr) {\n let res = arr[0]\n for (let i = 1; i < arr.length; i++) {\n res = (arr[i] * res) / GCD(arr[i], res)\n }\n return res\n}\n\nfunction GCD(a, b) {\n if (b === 0) return a\n return GCD(b, a % b)\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720bfd", + "questionid": 306, + "title": "Valid Square", + "slug": "valid-square", + "description": "Given the coordinates of four points in 2D space p1, p2, p3 and p4, return true if the four points construct a square. The coordinate of a point pi is represented as [xi, yi]. The input is not given in any order. A valid square has four equal sides with positive length and four equal angles (90-degree angles). ", + "category": [ + "Math", + "Geometry" + ], + "complexity": "Medium", + "successrate": 43.8, + "totalsubmissions": 186845, + "totalaccepted": 81890, + "likes": 674, + "dislikes": 739, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "p1 = [0,0], p2 = [1,1], p3 = [1,0], p4 = [0,1]", + "expected_output": "true", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "p1 = [0,0], p2 = [1,1], p3 = [1,0], p4 = [0,12]", + "expected_output": "false", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "p1 = [1,0], p2 = [-1,0], p3 = [0,1], p4 = [0,-1]", + "expected_output": "true", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} p1\n * @param {number[]} p2\n * @param {number[]} p3\n * @param {number[]} p4\n * @return {boolean}\n */\nconst validSquare = function(p1, p2, p3, p4) {\n const lenArr = [\n distance(p1, p2),\n distance(p1, p3),\n distance(p1, p4),\n distance(p2, p3),\n distance(p2, p4),\n distance(p3, p4)\n ]\n const obj = {}\n for (let el of lenArr) {\n if (obj[el] != null) obj[el] += 1\n else obj[el] = 1\n }\n const keys = Object.keys(obj)\n\n return keys.length === 2 && (obj[keys[0]] === 2 || obj[keys[1]] === 2)\n}\n\nfunction distance(p1, p2) {\n return Math.sqrt(Math.pow(p1[1] - p2[1], 2) + Math.pow(p1[0] - p2[0], 2))\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720c00", + "questionid": 309, + "title": "Minimum Index Sum of Two Lists", + "slug": "minimum-index-sum-of-two-lists", + "description": "Suppose Andy and Doris want to choose a restaurant for dinner, and they both have a list of favorite restaurants represented by strings. You need to help them find out their common interest with the least list index sum. If there is a choice tie between answers, output all of them with no order requirement. You could assume there always exists an answer. ", + "category": [ + "Array", + "Hash Table", + "String" + ], + "complexity": "Easy", + "successrate": 52.8, + "totalsubmissions": 279803, + "totalaccepted": 147774, + "likes": 1170, + "dislikes": 318, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "list1 = ["Shogun","Tapioca Express","Burger King","KFC"], list2 = ["Piatti","The Grill at Torrey Pines","Hungry Hunter Steakhouse","Shogun"]", + "expected_output": "["Shogun"]", + "explanation": "The only common string is "Shogun"." + }, + { + "example_num": 2, + "expected_input": "list1 = ["Shogun","Tapioca Express","Burger King","KFC"], list2 = ["KFC","Shogun","Burger King"]", + "expected_output": "["Shogun"]", + "explanation": "The common string with the least index sum is "Shogun" with index sum = (0 + 1) = 1." + }, + { + "example_num": 3, + "expected_input": "list1 = ["happy","sad","good"], list2 = ["sad","happy","good"]", + "expected_output": "["sad","happy"]", + "explanation": "There are three common strings:\n"happy" with index sum = (0 + 1) = 1.\n"sad" with index sum = (1 + 0) = 1.\n"good" with index sum = (2 + 2) = 4.\nThe strings with the least index sum are "sad" and "happy"." + } + ], + "solution": "/**\n * @param {string[]} list1\n * @param {string[]} list2\n * @return {string[]}\n */\nconst findRestaurant = function(list1, list2) {\n const hash = {};\n for (let i = 0; i < list1.length; i++) {\n if (!hash.hasOwnProperty(list1[i])) {\n hash[list1[i]] = i;\n }\n }\n const resArr = [];\n for (let j = 0; j < list2.length; j++) {\n if (hash.hasOwnProperty(list2[j])) {\n resArr.push([list2[j], hash[list2[j]] + j]);\n }\n }\n const resHash = {};\n resArr.forEach(el => {\n if (resHash.hasOwnProperty(el[1])) {\n resHash[el[1]].push(el[0]);\n } else {\n resHash[el[1]] = [el[0]];\n }\n });\n resArr.sort((a, b) => a[1] - b[1]);\n return resHash[resArr[0][1]];\n};\n\nconsole.log(\n findRestaurant(\n [\"Shogun\", \"Tapioca Express\", \"Burger King\", \"KFC\"],\n [\"KFC\", \"Burger King\", \"Tapioca Express\", \"Shogun\"]\n )\n);\n" + }, + { + "_id": "66f925ddfdfb8e1665720c05", + "questionid": 314, + "title": "Task Scheduler", + "slug": "task-scheduler", + "description": "Given a characters array tasks, representing the tasks a CPU needs to do, where each letter represents a different task. Tasks could be done in any order. Each task is done in one unit of time. For each unit of time, the CPU could complete either one task or just be idle. However, there is a non-negative integer\u00a0n that represents the cooldown period between\u00a0two same tasks\u00a0(the same letter in the array), that is that there must be at least n units of time between any two same tasks. Return the least number of units of times that the CPU will take to finish all the given tasks. ", + "category": [ + "Array", + "Hash Table", + "Greedy", + "Sorting", + "Heap (Priority Queue)", + "Counting" + ], + "complexity": "Medium", + "successrate": 54.4, + "totalsubmissions": 610179, + "totalaccepted": 332057, + "likes": 6262, + "dislikes": 1206, + "hints": "", + "deleted": false, + "examples": [], + "solution": "/**\n * @param {character[]} tasks\n * @param {number} n\n * @return {number}\n */\nconst leastInterval = function (tasks, n) {\n const len = tasks.length\n const cnt = Array(26).fill(0)\n\n const A = 'A'.charCodeAt(0)\n let maxFreq = 0,\n maxFreqCnt = 0\n for (const ch of tasks) {\n const idx = ch.charCodeAt(0) - A\n cnt[idx]++\n if (maxFreq === cnt[idx]) {\n maxFreqCnt++\n } else if (maxFreq < cnt[idx]) {\n maxFreqCnt = 1\n maxFreq = cnt[idx]\n }\n }\n\n const slot = maxFreq - 1\n const numOfPerSlot = n - (maxFreqCnt - 1)\n const available = len - maxFreq * maxFreqCnt\n const idles = Math.max(0, slot * numOfPerSlot - available)\n return len + idles\n}\n\n\n// another\n\n/**\n * @param {character[]} tasks\n * @param {number} n\n * @return {number}\n */\nconst leastInterval = function(tasks, n) {\n const map = Array(26).fill(0);\n const ca = \"A\".charCodeAt(0);\n for (let c of tasks) map[c.charCodeAt(0) - ca]++;\n map.sort((a, b) => a - b);\n let max_val = map[25] - 1,\n idle_slots = max_val * n;\n for (let i = 24; i >= 0 && map[i] > 0; i--) {\n idle_slots -= Math.min(map[i], max_val);\n }\n return idle_slots > 0 ? idle_slots + tasks.length : tasks.length;\n};\n\n// another\n\n/**\n * @param {character[]} tasks\n * @param {number} n\n * @return {number}\n */\nconst leastInterval = function(tasks, n) {\n const hash = {};\n for(let task of tasks) {\n hash[task] = hash[task] + 1 || 1\n }\n let max = 0, count = 0;\n for(let el in hash) {\n if(hash[el] > max) {\n max = hash[el];\n count = 1\n } else if(hash[el] === max) {\n count++;\n }\n }\n return Math.max((max - 1) * (n + 1) + count, tasks.length)\n};\n\n// another\n\n/**\n * @param {character[]} tasks\n * @param {number} n\n * @return {number}\n */\nconst leastInterval = function(tasks, n) {\n let max = 0, maxCnt = 0\n const len = tasks.length, cnt = Array(26).fill(0), A = 'A'.charCodeAt(0)\n \n for(let ch of tasks) {\n const idx = ch.charCodeAt(0) - A\n cnt[idx]++\n if(max === cnt[idx]) maxCnt++\n else if(max < cnt[idx]) {\n max = cnt[idx]\n maxCnt = 1\n }\n }\n \n const maxSlots = max * maxCnt\n const avaiSlots = (max - 1) * (n - (maxCnt - 1))\n const rem = len - maxSlots\n const emptySlots = Math.max(0, avaiSlots - rem)\n \n return len + emptySlots\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720c09", + "questionid": 318, + "title": "Smallest Range Covering Elements from K Lists", + "slug": "smallest-range-covering-elements-from-k-lists", + "description": "You have k lists of sorted integers in non-decreasing\u00a0order. Find the smallest range that includes at least one number from each of the k lists. We define the range [a, b] is smaller than range [c, d] if b - a < d - c or a < c if b - a == d - c. ", + "category": [ + "Array", + "Hash Table", + "Greedy", + "Sliding Window", + "Sorting", + "Heap (Priority Queue)" + ], + "complexity": "Hard", + "successrate": 58.4, + "totalsubmissions": 109130, + "totalaccepted": 63761, + "likes": 2094, + "dislikes": 36, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [[4,10,15,24,26],[0,9,12,20],[5,18,22,30]]", + "expected_output": "[20,24]\nExplanation: \nList 1: [4, 10, 15, 24,26], 24 is in range [20,24].\nList 2: [0, 9, 12, 20], 20 is in range [20,24].\nList 3: [5, 18, 22, 30], 22 is in range [20,24].", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "nums = [[1,2,3],[1,2,3],[1,2,3]]", + "expected_output": "[1,1]", + "explanation": "" + } + ], + "solution": null + }, + { + "_id": "66f925ddfdfb8e1665720bcc", + "questionid": 257, + "title": "Sliding Window Median", + "slug": "sliding-window-median", + "description": "The median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value. So the median is the mean of the two middle values. You are given an integer array nums and an integer k. There is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position. Return the median array for each window in the original array. Answers within 10-5 of the actual value will be accepted. ", + "category": [ + "Array", + "Hash Table", + "Sliding Window", + "Heap (Priority Queue)" + ], + "complexity": "Hard", + "successrate": 40.8, + "totalsubmissions": 252073, + "totalaccepted": 102947, + "likes": 2111, + "dislikes": 130, + "hints": "The simplest of solutions comes from the basic idea of finding the median given a set of numbers. We know that by definition, a median is the center element (or an average of the two center elements). Given an unsorted list of numbers, how do we find the median element? If you know the answer to this question, can we extend this idea to every sliding window that we come across in the array? Is there a better way to do what we are doing in the above hint? Don't you think there is duplication of calculation being done there? Is there some sort of optimization that we can do to achieve the same result? This approach is merely a modification of the basic approach except that it simply reduces duplication of calculations once done. The third line of thought is also based on this same idea but achieving the result in a different way. We obviously need the window to be sorted for us to be able to find the median. Is there a data-structure out there that we can use (in one or more quantities) to obtain the median element extremely fast, say O(1) time while having the ability to perform the other operations fairly efficiently as well?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,3,-1,-3,5,3,6,7], k = 3", + "expected_output": "[1.00000,-1.00000,-1.00000,3.00000,5.00000,6.00000]", + "explanation": "Window position Median\n--------------- -----\n[1 3 -1] -3 5 3 6 7 1\n 1 [3 -1 -3] 5 3 6 7 -1\n 1 3 [-1 -3 5] 3 6 7 -1\n 1 3 -1 [-3 5 3] 6 7 3\n 1 3 -1 -3 [5 3 6] 7 5\n 1 3 -1 -3 5 [3 6 7] 6" + }, + { + "example_num": 2, + "expected_input": "nums = [1,2,3,4,2,3,1,4,2], k = 3", + "expected_output": "[2.00000,3.00000,3.00000,3.00000,2.00000,3.00000,2.00000]", + "explanation": "" + } + ], + "solution": "/*\n * @lc app=leetcode id=480 lang=javascript\n *\n * [480] Sliding Window Median\n */\n/**\n * @param {number[]} nums\n * @param {number} k\n * @return {number[]}\n */\nconst medianSlidingWindow = function(nums, k) {\n const window = nums.slice(0, k).sort((x, y) => x - y)\n const resultLen = nums.length - k + 1\n nums.push(0)\n\n function insert(arr, val) {\n let i = 0\n while (i < arr.length && arr[i] < val) {\n i++\n }\n arr.splice(i, 0, val)\n }\n\n const medians = []\n const rightIdx = (k / 2) >>> 0\n const leftIdx = k + ~rightIdx\n for (let i = 0; i < resultLen; i++) {\n medians.push((window[leftIdx] + window[rightIdx]) / 2)\n window.splice(window.indexOf(nums[i]), 1)\n insert(window, nums[k + i])\n }\n return medians\n}\n\n// another\n\nconst medianSlidingWindow = function(nums, k) {\n let pq = []\n for (let i = 0; i < k; i++) {\n insert(nums[i])\n }\n let res = []\n res.push(findMid())\n for (let i = k; i < nums.length; i++) {\n remove(nums[i - k])\n insert(nums[i])\n res.push(findMid())\n }\n return res\n function findMid() {\n let mid = (pq.length - 1) / 2\n return (pq[Math.ceil(mid)] + pq[Math.floor(mid)]) / 2\n }\n function insert(n) {\n if (pq.length === 0 || pq[pq.length - 1] <= n) {\n pq.push(n)\n } else {\n let idx = bsEnd(pq, n)\n pq.splice(idx, 0, n)\n }\n }\n function bsEnd(arr, n) {\n let lo = 0,\n hi = arr.length - 1\n while (lo < hi) {\n let mid = Math.floor((lo + hi) / 2)\n if (arr[mid] < n) lo = mid + 1\n else hi = mid\n }\n return hi\n }\n function remove(n) {\n let idx = bsEnd(pq, n)\n pq.splice(idx, 1)\n }\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720bcd", + "questionid": 258, + "title": "License Key Formatting", + "slug": "license-key-formatting", + "description": "You are given a license key represented as a string s that consists of only alphanumeric characters and dashes. The string is separated into n + 1 groups by n dashes. You are also given an integer k. We want to reformat the string s such that each group contains exactly k characters, except for the first group, which could be shorter than k but still must contain at least one character. Furthermore, there must be a dash inserted between two groups, and you should convert all lowercase letters to uppercase. Return the reformatted license key. ", + "category": [ + "String" + ], + "complexity": "Easy", + "successrate": 43.1, + "totalsubmissions": 486859, + "totalaccepted": 209919, + "likes": 751, + "dislikes": 1077, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "5F3Z-2e-9-w", k = 4", + "expected_output": ""5F3Z-2E9W"", + "explanation": "The string s has been split into two parts, each part has 4 characters.\nNote that the two extra dashes are not needed and can be removed." + }, + { + "example_num": 2, + "expected_input": "s = "2-5g-3-J", k = 2", + "expected_output": ""2-5G-3J"", + "explanation": "The string s has been split into three parts, each part has 2 characters except the first part as it could be shorter as mentioned above." + } + ], + "solution": "/**\n * @param {string} S\n * @param {number} K\n * @return {string}\n */\nconst licenseKeyFormatting = function(S, K) {\n if (S == null || S === \"\") return \"\";\n const newStr = S.replace(/-/g, \"\").toUpperCase();\n const arr = newStr.split(\"\");\n for (let i = arr.length - 1 - K; i >= 0; i -= K) {\n arr[i] = arr[i] + \"-\";\n }\n return arr.join(\"\");\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720bd6", + "questionid": 267, + "title": "IPO", + "slug": "ipo", + "description": "Suppose LeetCode will start its IPO soon. In order to sell a good price of its shares to Venture Capital, LeetCode would like to work on some projects to increase its capital before the IPO. Since it has limited resources, it can only finish at most k distinct projects before the IPO. Help LeetCode design the best way to maximize its total capital after finishing at most k distinct projects. You are given n projects where the ith project has a pure profit profits[i] and a minimum capital of capital[i] is needed to start it. Initially, you have w capital. When you finish a project, you will obtain its pure profit and the profit will be added to your total capital. Pick a list of at most k distinct projects from given projects to maximize your final capital, and return the final maximized capital. The answer is guaranteed to fit in a 32-bit signed integer. ", + "category": [ + "Array", + "Greedy", + "Sorting", + "Heap (Priority Queue)" + ], + "complexity": "Hard", + "successrate": 44, + "totalsubmissions": 73070, + "totalaccepted": 32171, + "likes": 775, + "dislikes": 70, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "k = 2, w = 0, profits = [1,2,3], capital = [0,1,1]", + "expected_output": "4", + "explanation": "Since your initial capital is 0, you can only start the project indexed 0.\nAfter finishing it you will obtain profit 1 and your capital becomes 1.\nWith capital 1, you can either start the project indexed 1 or the project indexed 2.\nSince you can choose at most 2 projects, you need to finish the project indexed 2 to get the maximum capital.\nTherefore, output the final maximized capital, which is 0 + 1 + 3 = 4." + }, + { + "example_num": 2, + "expected_input": "k = 3, w = 0, profits = [1,2,3], capital = [0,1,2]", + "expected_output": "6", + "explanation": "" + } + ], + "solution": "/**\n * @param {number} k\n * @param {number} W\n * @param {number[]} Profits\n * @param {number[]} Capital\n * @return {number}\n */\nconst findMaximizedCapital = function(k, W, Profits, Capital) {\n const capPQ = new PriorityQueue((a, b) => a.cap < b.cap)\n const proPQ = new PriorityQueue((a, b) => a.pro > b.pro)\n for(let i = 0, len = Profits.length; i < len; i++) {\n capPQ.push({ cap: Capital[i], pro: Profits[i] })\n }\n while(k) {\n while(!capPQ.isEmpty() && capPQ.peek().cap <= W) {\n proPQ.push(capPQ.pop())\n }\n if(proPQ.isEmpty()) break\n \n W += proPQ.pop().pro\n k--\n }\n return W\n};\n\nclass PriorityQueue {\n constructor(comparator = (a, b) => a > b) {\n this.heap = []\n this.top = 0\n this.comparator = comparator\n }\n size() {\n return this.heap.length\n }\n isEmpty() {\n return this.size() === 0\n }\n peek() {\n return this.heap[this.top]\n }\n push(...values) {\n values.forEach((value) => {\n this.heap.push(value)\n this.siftUp()\n })\n return this.size()\n }\n pop() {\n const poppedValue = this.peek()\n const bottom = this.size() - 1\n if (bottom > this.top) {\n this.swap(this.top, bottom)\n }\n this.heap.pop()\n this.siftDown()\n return poppedValue\n }\n replace(value) {\n const replacedValue = this.peek()\n this.heap[this.top] = value\n this.siftDown()\n return replacedValue\n }\n\n parent = (i) => ((i + 1) >>> 1) - 1\n left = (i) => (i << 1) + 1\n right = (i) => (i + 1) << 1\n greater = (i, j) => this.comparator(this.heap[i], this.heap[j])\n swap = (i, j) => ([this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]])\n siftUp = () => {\n let node = this.size() - 1\n while (node > this.top && this.greater(node, this.parent(node))) {\n this.swap(node, this.parent(node))\n node = this.parent(node)\n }\n }\n siftDown = () => {\n let node = this.top\n while (\n (this.left(node) < this.size() && this.greater(this.left(node), node)) ||\n (this.right(node) < this.size() && this.greater(this.right(node), node))\n ) {\n let maxChild =\n this.right(node) < this.size() &&\n this.greater(this.right(node), this.left(node))\n ? this.right(node)\n : this.left(node)\n this.swap(node, maxChild)\n node = maxChild\n }\n }\n}\n\n// another\n\n/**\n * @param {number} k\n * @param {number} W\n * @param {number[]} Profits\n * @param {number[]} Capital\n * @return {number}\n */\nconst findMaximizedCapital = function(k, W, Profits, Capital) {\n const idxArr = Profits.map((_, i) => i).sort((ia, ib) => Profits[ib] - Profits[ia]);\n while (k) {\n const choose = idxArr.findIndex(i => Capital[i] <= W);\n if (choose == -1) return W;\n W += Profits[idxArr[choose]];\n idxArr.splice(choose, 1);\n k--;\n }\n return W;\n};\n\n// another\n\n/**\n * @param {number} k\n * @param {number} w\n * @param {number[]} profits\n * @param {number[]} capital\n * @return {number}\n */\nconst findMaximizedCapital = function(k, w, profits, capital) {\n const capPQ = new PQ((a, b) => a.cap < b.cap)\n const proPQ = new PQ((a, b) => a.pro > b.pro)\n const n = profits.length\n \n for(let i = 0; i < n; i++) {\n capPQ.push({ cap: capital[i], pro: profits[i] })\n }\n \n while(k) {\n \n while(!capPQ.isEmpty() && capPQ.peek().cap <= w) {\n proPQ.push(capPQ.pop())\n }\n \n if(proPQ.isEmpty()) break\n \n w += proPQ.pop().pro\n k--\n }\n \n \n return w\n};\n\nclass PQ {\n constructor(comparator = (a, b) => a > b) {\n this.heap = []\n this.top = 0\n this.comparator = comparator\n }\n size() {\n return this.heap.length\n }\n isEmpty() {\n return this.size() === 0\n }\n peek() {\n return this.heap[this.top]\n }\n push(...values) {\n values.forEach((value) => {\n this.heap.push(value)\n this.siftUp()\n })\n return this.size()\n }\n pop() {\n const poppedValue = this.peek()\n const bottom = this.size() - 1\n if (bottom > this.top) {\n this.swap(this.top, bottom)\n }\n this.heap.pop()\n this.siftDown()\n return poppedValue\n }\n replace(value) {\n const replacedValue = this.peek()\n this.heap[this.top] = value\n this.siftDown()\n return replacedValue\n }\n\n parent = (i) => ((i + 1) >>> 1) - 1\n left = (i) => (i << 1) + 1\n right = (i) => (i + 1) << 1\n greater = (i, j) => this.comparator(this.heap[i], this.heap[j])\n swap = (i, j) => ([this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]])\n siftUp = () => {\n let node = this.size() - 1\n while (node > this.top && this.greater(node, this.parent(node))) {\n this.swap(node, this.parent(node))\n node = this.parent(node)\n }\n }\n siftDown = () => {\n let node = this.top\n while (\n (this.left(node) < this.size() && this.greater(this.left(node), node)) ||\n (this.right(node) < this.size() && this.greater(this.right(node), node))\n ) {\n let maxChild =\n this.right(node) < this.size() &&\n this.greater(this.right(node), this.left(node))\n ? this.right(node)\n : this.left(node)\n this.swap(node, maxChild)\n node = maxChild\n }\n }\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720bda", + "questionid": 271, + "title": "Most Frequent Subtree Sum", + "slug": "most-frequent-subtree-sum", + "description": "Given the root of a binary tree, return the most frequent subtree sum. If there is a tie, return all the values with the highest frequency in any order. The subtree sum of a node is defined as the sum of all the node values formed by the subtree rooted at that node (including the node itself). ", + "category": [ + "Hash Table", + "Tree", + "Depth-First Search", + "Binary Tree" + ], + "complexity": "Medium", + "successrate": 62.7, + "totalsubmissions": 169666, + "totalaccepted": 106337, + "likes": 1455, + "dislikes": 222, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [5,2,-3]", + "expected_output": "[2,-3,4]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "root = [5,2,-5]", + "expected_output": "[2]", + "explanation": "" + } + ], + "solution": "/**\n * Definition for a binary tree node.\n * function TreeNode(val) {\n * this.val = val;\n * this.left = this.right = null;\n * }\n */\n/**\n * @param {TreeNode} root\n * @return {number[]}\n */\nconst findFrequentTreeSum = function(root) {\n if (root == null) return [];\n const valArr = [];\n calc(root, valArr);\n const hash = {};\n valArr.forEach((el, idx) => {\n if (hash.hasOwnProperty(el)) {\n hash[el] += 1;\n } else {\n hash[el] = 1;\n }\n });\n const arr = Object.entries(hash).sort((a, b) => b[1] - a[1]);\n const max = arr[0][1];\n const res = [+arr[0][0]];\n for (let i = 1; i < arr.length; i++) {\n if (arr[i][1] === max) {\n res.push(+arr[i][0]);\n } else {\n return res;\n }\n }\n return res;\n};\n\nfunction calc(node, arr) {\n let sum = 0;\n if (node.left) {\n sum += calc(node.left, arr);\n }\n if (node.right) {\n sum += calc(node.right, arr);\n }\n sum += node.val;\n arr.push(sum);\n return sum;\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720be0", + "questionid": 277, + "title": "Longest Uncommon Subsequence I", + "slug": "longest-uncommon-subsequence-i", + "description": "Given two strings a and b, return the length of the longest uncommon subsequence between a and b. If the longest uncommon subsequence does not exist, return -1. An uncommon subsequence between two strings is a string that is a subsequence of one but not the other. A subsequence of a string s is a string that can be obtained after deleting any number of characters from s. ", + "category": [ + "String" + ], + "complexity": "Easy", + "successrate": 60.1, + "totalsubmissions": 138850, + "totalaccepted": 83443, + "likes": 570, + "dislikes": 5566, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "a = "aba", b = "cdc"", + "expected_output": "3", + "explanation": "One longest uncommon subsequence is "aba" because "aba" is a subsequence of "aba" but not "cdc".\nNote that "cdc" is also a longest uncommon subsequence." + }, + { + "example_num": 2, + "expected_input": "a = "aaa", b = "bbb"", + "expected_output": "3", + "explanation": " The longest uncommon subsequences are "aaa" and "bbb"." + }, + { + "example_num": 3, + "expected_input": "a = "aaa", b = "aaa"", + "expected_output": "-1", + "explanation": " Every subsequence of string a is also a subsequence of string b. Similarly, every subsequence of string b is also a subsequence of string a. So the answer would be -1." + } + ], + "solution": "/**\n * @param {string} a\n * @param {string} b\n * @return {number}\n */\nconst findLUSlength = function(a, b) {\n return a === b ? -1 : Math.max(a.length, b.length);\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720be1", + "questionid": 278, + "title": "Longest Uncommon Subsequence II", + "slug": "longest-uncommon-subsequence-ii", + "description": "Given an array of strings strs, return the length of the longest uncommon subsequence between them. If the longest uncommon subsequence does not exist, return -1. An uncommon subsequence between an array of strings is a string that is a subsequence of one string but not the others. A subsequence of a string s is a string that can be obtained after deleting any number of characters from s. ", + "category": [ + "Array", + "Hash Table", + "Two Pointers", + "String", + "Sorting" + ], + "complexity": "Medium", + "successrate": 40.1, + "totalsubmissions": 106746, + "totalaccepted": 42789, + "likes": 367, + "dislikes": 1065, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "strs = [\"aba\",\"cdc\",\"eae\"]", + "expected_output": "3", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "strs = [\"aaa\",\"aaa\",\"aa\"]", + "expected_output": "-1", + "explanation": "" + } + ], + "solution": "/**\n * @param {string[]} strs\n * @return {number}\n */\nconst findLUSlength = function(strs) {\n strs.sort((a, b) => b.length - a.length)\n const dup = getDuplicates(strs)\n for(let i = 0; i < strs.length; i++) {\n if(!dup.has(strs[i])) {\n if(i === 0) return strs[0].length\n for(let j = 0; j < i; j++) {\n if(isSubsequence(strs[j], strs[i])) break\n if(j === i - 1) return strs[i].length\n }\n }\n }\n return -1\n};\n\nfunction isSubsequence(a, b) {\n let i = 0, j = 0\n while(i < a.length && j < b.length) {\n if(a.charAt(i) === b.charAt(j)) j++\n i++\n }\n return j === b.length\n}\n\nfunction getDuplicates(arr) {\n const set = new Set()\n const dup = new Set()\n for(let el of arr) {\n if(set.has(el)) dup.add(el)\n else set.add(el)\n }\n return dup\n}\n\n" + }, + { + "_id": "66f925ddfdfb8e1665720be2", + "questionid": 279, + "title": "Continuous Subarray Sum", + "slug": "continuous-subarray-sum", + "description": "Given an integer array nums and an integer k, return true if nums has a continuous subarray of size at least two whose elements sum up to a multiple of k, or false otherwise. An integer x is a multiple of k if there exists an integer n such that x = n * k. 0 is always a multiple of k. ", + "category": [ + "Array", + "Hash Table", + "Math", + "Prefix Sum" + ], + "complexity": "Medium", + "successrate": 27.2, + "totalsubmissions": 1047671, + "totalaccepted": 285001, + "likes": 1762, + "dislikes": 245, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [23,2,4,6,7], k = 6", + "expected_output": "true", + "explanation": "[2, 4] is a continuous subarray of size 2 whose elements sum up to 6." + }, + { + "example_num": 2, + "expected_input": "nums = [23,2,6,4,7], k = 6", + "expected_output": "true", + "explanation": "[23, 2, 6, 4, 7] is an continuous subarray of size 5 whose elements sum up to 42.\n42 is a multiple of 6 because 42 = 7 * 6 and 7 is an integer." + }, + { + "example_num": 3, + "expected_input": "nums = [23,2,6,4,7], k = 13", + "expected_output": "false", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} nums\n * @param {number} k\n * @return {boolean}\n */\nconst checkSubarraySum = function(nums, k) {\n const map = {0: -1}\n let runningSum = 0\n for(let i = 0; i < nums.length; i++) {\n runningSum += nums[i]\n if(k !== 0) runningSum %= k\n let prev = map[runningSum]\n if(prev != null) {\n if(i - prev > 1) return true\n } else {\n map[runningSum] = i\n }\n }\n return false\n};\n\n" + }, + { + "_id": "66f925ddfdfb8e1665720be8", + "questionid": 285, + "title": "Reverse String II", + "slug": "reverse-string-ii", + "description": "Given a string s and an integer k, reverse the first k characters for every 2k characters counting from the start of the string. If there are fewer than k characters left, reverse all of them. If there are less than 2k but greater than or equal to k characters, then reverse the first k characters and leave the other as original. ", + "category": [ + "Two Pointers", + "String" + ], + "complexity": "Easy", + "successrate": 50.1, + "totalsubmissions": 297991, + "totalaccepted": 149401, + "likes": 952, + "dislikes": 2363, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = \"abcdefg\", k = 2", + "expected_output": "\"bacdfeg\"", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "s = \"abcd\", k = 2", + "expected_output": "\"bacd\"", + "explanation": "" + } + ], + "solution": "/**\n * @param {string} s\n * @param {number} k\n * @return {string}\n */\nconst reverseStr = function(s, k) {\n const arr = s.split('')\n for(let i = 0, len = s.length; i < len; i += 2 * k) {\n helper(arr, i, k)\n }\n return arr.join('')\n};\n\nfunction helper(arr, start, k) {\n let s = start\n let e = arr.length > start + k - 1 ? start + k - 1 : arr.length\n while(s < e) {\n swap(arr, s, e)\n s++\n e--\n }\n}\n\nfunction swap(arr, s, e) {\n const tmp = arr[s]\n arr[s] = arr[e]\n arr[e] = tmp\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720be9", + "questionid": 286, + "title": "01 Matrix", + "slug": "01-matrix", + "description": "Given an m x n binary matrix mat, return the distance of the nearest 0 for each cell. The distance between two adjacent cells is 1. ", + "category": [ + "Array", + "Dynamic Programming", + "Breadth-First Search", + "Matrix" + ], + "complexity": "Medium", + "successrate": 43.8, + "totalsubmissions": 534554, + "totalaccepted": 233903, + "likes": 4442, + "dislikes": 221, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "mat = [[0,0,0],[0,1,0],[0,0,0]]", + "expected_output": "[[0,0,0],[0,1,0],[0,0,0]]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "mat = [[0,0,0],[0,1,0],[1,1,1]]", + "expected_output": "[[0,0,0],[0,1,0],[1,2,1]]", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[][]} matrix\n * @return {number[][]}\n */\n\nconst updateMatrix = function (matrix) {\n const rows = matrix.length, cols = matrix[0].length;\n const maxDist = rows + cols;\n let dist = new Array(rows).fill(null).map(() => new Array(cols).fill(0));\n \n for (let i = 0; i < rows; i++) {\n for (let j = 0; j < cols; j++) {\n if (matrix[i][j] !== 0) {\n dist[i][j] = hasNeighborZero(i, j, matrix, rows, cols) ? 1 : maxDist;\n }\n }\n }\n \n for (let i = 0; i < rows; i++) {\n for (let j = 0; j < cols; j++) {\n if (dist[i][j] === 1) {\n dfs(dist, i, j, -1);\n }\n }\n }\n \n return dist;\n };\n \n const dfs = function (dist, row, col, step) {\n if (row < 0 || row >= dist.length || col < 0 || col >= dist[0].length || dist[row][col] <= step) return;\n \n if (step > 0) dist[row][col] = step;\n \n dfs(dist, row + 1, col, dist[row][col] + 1);\n dfs(dist, row - 1, col, dist[row][col] + 1);\n dfs(dist, row, col + 1, dist[row][col] + 1);\n dfs(dist, row, col - 1, dist[row][col] + 1);\n };\n \n const hasNeighborZero = function (row, col, matrix, rows, cols) {\n if (row < rows - 1 && matrix[row + 1][col] === 0) return true;\n if (row > 0 && matrix[row - 1][col] === 0) return true;\n if (col > 0 && matrix[row][col - 1] === 0) return true;\n if (col < cols - 1 && matrix[row][col + 1] === 0) return true;\n \n return false;\n };\n" + }, + { + "_id": "66f925ddfdfb8e1665720bf0", + "questionid": 293, + "title": "Subarray Sum Equals K", + "slug": "subarray-sum-equals-k", + "description": "Given an array of integers nums and an integer k, return the total number of subarrays whose sum equals to k. ", + "category": [ + "Array", + "Hash Table", + "Prefix Sum" + ], + "complexity": "Medium", + "successrate": 44.2, + "totalsubmissions": 1715764, + "totalaccepted": 758711, + "likes": 12822, + "dislikes": 409, + "hints": "Will Brute force work here? Try to optimize it. Can we optimize it by using some extra space? What about storing sum frequencies in a hash table? Will it be useful? sum(i,j)=sum(0,j)-sum(0,i), where sum(i,j) represents the sum of all the elements from index i to j-1.\r\n\r\nCan we use this property to optimize it.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,1,1], k = 2", + "expected_output": "2", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "nums = [1,2,3], k = 3", + "expected_output": "2", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} nums\n * @param {number} k\n * @return {number}\n */\nconst subarraySum = function(nums, k) {\n let totalNum = 0\n const map = new Map()\n let cumulativeSum = 0\n map.set(0, 1)\n for (let i = 0, len = nums.length; i < len; i++) {\n cumulativeSum += nums[i]\n if (map.get(cumulativeSum - k)) {\n totalNum += map.get(cumulativeSum - k)\n }\n if (map.get(cumulativeSum)) {\n map.set(cumulativeSum, map.get(cumulativeSum) + 1)\n } else {\n map.set(cumulativeSum, 1)\n }\n }\n return totalNum\n}\n\n// another\n\n/**\n * @param {number[]} nums\n * @param {number} k\n * @return {number}\n */\nconst subarraySum = function (nums, k) {\n const n = nums.length, hash = { 0: 1 }\n let pre = 0\n let res = 0\n for (let i = 0; i < n; i++) {\n const cur = pre + nums[i]\n if (hash[cur - k] != null) res += hash[cur - k]\n hash[cur] = (hash[cur] || 0) + 1\n pre = cur\n }\n return res\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720bf4", + "questionid": 297, + "title": "Reshape the Matrix", + "slug": "reshape-the-matrix", + "description": "In MATLAB, there is a handy function called reshape which can reshape an m x n matrix into a new one with a different size r x c keeping its original data. You are given an m x n matrix mat and two integers r and c representing the number of rows and the number of columns of the wanted reshaped matrix. The reshaped matrix should be filled with all the elements of the original matrix in the same row-traversing order as they were. If the reshape operation with given parameters is possible and legal, output the new reshaped matrix; Otherwise, output the original matrix. ", + "category": [ + "Array", + "Matrix", + "Simulation" + ], + "complexity": "Easy", + "successrate": 62.4, + "totalsubmissions": 365645, + "totalaccepted": 228101, + "likes": 2155, + "dislikes": 243, + "hints": "Do you know how 2d matrix is stored in 1d memory? Try to map 2-dimensions into one. M[i][j]=M[n*i+j] , where n is the number of cols. \r\nThis is the one way of converting 2-d indices into one 1-d index. \r\nNow, how will you convert 1-d index into 2-d indices? Try to use division and modulus to convert 1-d index into 2-d indices. M[i] => M[i/n][i%n] Will it result in right mapping? Take some example and check this formula.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "mat = [[1,2],[3,4]], r = 1, c = 4", + "expected_output": "[[1,2,3,4]]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "mat = [[1,2],[3,4]], r = 2, c = 4", + "expected_output": "[[1,2],[3,4]]", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[][]} nums\n * @param {number} r\n * @param {number} c\n * @return {number[][]}\n */\nconst matrixReshape = function(nums, r, c) {\n if (isValid(nums, r, c) === false) {\n return nums;\n }\n const arr = [];\n nums.forEach(el => arr.push(...el));\n const res = [];\n for (let start = 0; start < arr.length; start = start + c) {\n res.push(arr.slice(start, start + c));\n }\n return res;\n};\n\nfunction isValid(matrix, r, c) {\n if (matrix.length * matrix[0].length !== r * c) {\n return false;\n } else {\n return true;\n }\n}\n\nconsole.log(matrixReshape([[1, 2], [3, 4]], 1, 4));\nconsole.log(matrixReshape([[1, 2], [3, 4]], 2, 4));\n" + }, + { + "_id": "66f925ddfdfb8e1665720bf6", + "questionid": 299, + "title": "Subtree of Another Tree", + "slug": "subtree-of-another-tree", + "description": "Given the roots of two binary trees root and subRoot, return true if there is a subtree of root with the same structure and node values of subRoot and false otherwise. A subtree of a binary tree tree is a tree that consists of a node in tree and all of this node's descendants. The tree tree could also be considered as a subtree of itself. ", + "category": [ + "Tree", + "Depth-First Search", + "String Matching", + "Binary Tree", + "Hash Function" + ], + "complexity": "Easy", + "successrate": 45.3, + "totalsubmissions": 996628, + "totalaccepted": 451495, + "likes": 5105, + "dislikes": 265, + "hints": "Which approach is better here- recursive or iterative? If recursive approach is better, can you write recursive function with its parameters? Two trees s and t are said to be identical if their root values are same and their left and right subtrees are identical. Can you write this in form of recursive formulae? Recursive formulae can be: \r\nisIdentical(s,t)= s.val==t.val AND isIdentical(s.left,t.left) AND isIdentical(s.right,t.right)", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [3,4,5,1,2], subRoot = [4,1,2]", + "expected_output": "true", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "root = [3,4,5,1,2,null,null,null,null,0], subRoot = [4,1,2]", + "expected_output": "false", + "explanation": "" + } + ], + "solution": "/**\n * Definition for a binary tree node.\n * function TreeNode(val) {\n * this.val = val;\n * this.left = this.right = null;\n * }\n */\n/**\n * @param {TreeNode} s\n * @param {TreeNode} t\n * @return {boolean}\n */\nconst isSubtree = function(s, t) {\n if (s == null) return false \n if (isSame(s, t)) return true\n return isSubtree(s.left, t) || isSubtree(s.right, t) \n};\n\nfunction isSame(s, t) {\n if (s == null && t == null) return true\n if (s == null || t == null) return false\n if (s.val !== t.val) return false\n return isSame(s.left, t.left) && isSame(s.right, t.right)\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720bfb", + "questionid": 304, + "title": "Erect the Fence", + "slug": "erect-the-fence", + "description": "You are given an array trees where trees[i] = [xi, yi] represents the location of a tree in the garden. You are asked to fence the entire garden using the minimum length of rope as it is expensive. The garden is well fenced only if all the trees are enclosed. Return the coordinates of trees that are exactly located on the fence perimeter. ", + "category": [ + "Array", + "Math", + "Geometry" + ], + "complexity": "Hard", + "successrate": 43.2, + "totalsubmissions": 55809, + "totalaccepted": 24131, + "likes": 550, + "dislikes": 344, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "trees = [[1,1],[2,2],[2,0],[2,4],[3,3],[4,2]]", + "expected_output": "[[1,1],[2,0],[4,2],[3,3],[2,4]]", + "explanation": "All the trees will be on the perimeter of the fence except the tree at [2, 2], which will be inside the fence." + }, + { + "example_num": 2, + "expected_input": "trees = [[1,2],[2,2],[4,2]]", + "expected_output": "[[4,2],[2,2],[1,2]]", + "explanation": "The fence forms a line that passes through all the trees." + } + ], + "solution": "/**\n * @param {number[][]} points\n * @return {number[][]}\n */\nconst outerTrees = function (points) {\n const orientation = (p1, p2, p3) => {\n return (p2[1] - p1[1]) * (p3[0] - p2[0]) - (p2[0] - p1[0]) * (p3[1] - p2[1])\n }\n points.sort((a, b) => {\n return a[0] === b[0] ? a[1] - b[1] : a[0] - b[0]\n })\n const stack = []\n for (let i = 0; i < points.length; i++) {\n while (\n stack.length >= 2 &&\n orientation(stack[stack.length - 2], stack[stack.length - 1], points[i]) >\n 0\n )\n stack.pop()\n stack.push(points[i])\n }\n stack.pop()\n for (let i = points.length - 1; i >= 0; i--) {\n while (\n stack.length >= 2 &&\n orientation(stack[stack.length - 2], stack[stack.length - 1], points[i]) >\n 0\n )\n stack.pop()\n stack.push(points[i])\n }\n return [...new Set(stack)]\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720bfe", + "questionid": 307, + "title": "Longest Harmonious Subsequence", + "slug": "longest-harmonious-subsequence", + "description": "We define a harmonious array as an array where the difference between its maximum value and its minimum value is exactly 1. Given an integer array nums, return the length of its longest harmonious subsequence among all its possible subsequences. A subsequence of array is a sequence that can be derived from the array by deleting some or no elements without changing the order of the remaining elements. ", + "category": [ + "Array", + "Hash Table", + "Sorting" + ], + "complexity": "Easy", + "successrate": 52.6, + "totalsubmissions": 217843, + "totalaccepted": 114669, + "likes": 1522, + "dislikes": 151, + "hints": "", + "deleted": false, + "examples": [], + "solution": "/**\n * @param {number[]} nums\n * @return {number}\n */\nconst findLHS = function(nums) {\n if(nums == null) return 0\n if(Object.prototype.toString.call(nums) === '[object Array]' && nums.length === 0) return 0\n let res = 0\n const map = {}\n for (let el of nums) {\n if(map.hasOwnProperty(el)) {\n map[el] += 1\n } else {\n map[el] = 1\n }\n }\n Object.keys(map).forEach(el => {\n if(map.hasOwnProperty(+el + 1)) {\n res = Math.max(res, map[el] + map[+el + 1])\n }\n })\n console.log(res)\n return res\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720c04", + "questionid": 313, + "title": "Valid Triangle Number", + "slug": "valid-triangle-number", + "description": "Given an integer array nums, return the number of triplets chosen from the array that can make triangles if we take them as side lengths of a triangle. ", + "category": [ + "Array", + "Two Pointers", + "Binary Search", + "Greedy", + "Sorting" + ], + "complexity": "Medium", + "successrate": 49.7, + "totalsubmissions": 270227, + "totalaccepted": 134273, + "likes": 2468, + "dislikes": 150, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [2,2,3,4]", + "expected_output": "3", + "explanation": "Valid combinations are: \n2,3,4 (using the first 2)\n2,3,4 (using the second 2)\n2,2,3" + }, + { + "example_num": 2, + "expected_input": "nums = [4,2,3,4]", + "expected_output": "4", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} nums\n * @return {number}\n */\nconst triangleNumber = function(nums) {\n nums.sort((a, b) => a - b);\n let count = 0;\n let n = nums.length;\n for (let i = n - 1; i >= 2; i--) {\n let lo = 0;\n let mid = i - 1;\n while (lo < mid) {\n if (nums[lo] + nums[mid] > nums[i]) {\n count += mid - lo;\n mid -= 1;\n } else {\n lo += 1;\n }\n }\n }\n return count;\n};\n\nconsole.log(triangleNumber([2, 2, 3, 4]));\n" + }, + { + "_id": "66f925ddfdfb8e1665720c06", + "questionid": 315, + "title": "Maximum Product of Three Numbers", + "slug": "maximum-product-of-three-numbers", + "description": "Given an integer array nums, find three numbers whose product is maximum and return the maximum product. ", + "category": [ + "Array", + "Math", + "Sorting" + ], + "complexity": "Easy", + "successrate": 46.8, + "totalsubmissions": 437389, + "totalaccepted": 204489, + "likes": 2617, + "dislikes": 520, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,2,3]", + "expected_output": "6", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "nums = [1,2,3,4]", + "expected_output": "24", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "nums = [-1,-2,-3]", + "expected_output": "-6", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} nums\n * @return {number}\n */\nconst maximumProduct = function (nums) {\n nums.sort((a, b) => a - b)\n return Math.max(\n nums[0] * nums[1] * nums[nums.length - 1],\n nums[nums.length - 1] * nums[nums.length - 2] * nums[nums.length - 3]\n )\n}\n\n// another\n\n/**\n * @param {number[]} nums\n * @return {number}\n */\nconst maximumProduct = function (nums) {\n let max1 = -Infinity\n let max2 = -Infinity\n let max3 = -Infinity\n let min1 = Infinity\n let min2 = Infinity\n for (let num of nums) {\n if (num > max1) {\n max3 = max2\n max2 = max1\n max1 = num\n } else if (num > max2) {\n max3 = max2\n max2 = num\n } else if (num > max3) {\n max3 = num\n }\n\n if (num < min1) {\n min2 = min1\n min1 = num\n } else if (num < min2) {\n min2 = num\n }\n }\n return Math.max(max1 * max2 * max3, max1 * min1 * min2)\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720c08", + "questionid": 317, + "title": "Course Schedule III", + "slug": "course-schedule-iii", + "description": "There are n different online courses numbered from 1 to n. You are given an array courses where courses[i] = [durationi, lastDayi] indicate that the ith course should be taken continuously for durationi days and must be finished before or on lastDayi. You will start on the 1st day and you cannot take two or more courses simultaneously. Return the maximum number of courses that you can take. ", + "category": [ + "Array", + "Greedy", + "Heap (Priority Queue)" + ], + "complexity": "Hard", + "successrate": 35.7, + "totalsubmissions": 157006, + "totalaccepted": 56052, + "likes": 1903, + "dislikes": 54, + "hints": "During iteration, say I want to add the current course, currentTotalTime being total time of all courses taken till now, but adding the current course might exceed my deadline or it doesn\u20ac\u2122t.\r\n\r\n1. If it doesn\u20ac\u2122t, then I have added one new course. Increment the currentTotalTime with duration of current course. 2. If it exceeds deadline, I can swap current course with current courses that has biggest duration.\r\n* No harm done and I might have just reduced the currentTotalTime, right? \r\n* What preprocessing do I need to do on my course processing order so that this swap is always legal?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "courses = [[100,200],[200,1300],[1000,1250],[2000,3200]]", + "expected_output": "3\nExplanation: \nThere are totally 4 courses, but you can take 3 courses at most:\nFirst, take the 1st course, it costs 100 days so you will finish it on the 100th day, and ready to take the next course on the 101st day.\nSecond, take the 3rd course, it costs 1000 days so you will finish it on the 1100th day, and ready to take the next course on the 1101st day. \nThird, take the 2nd course, it costs 200 days so you will finish it on the 1300th day. \nThe 4th course cannot be taken now, since you will finish it on the 3300th day, which exceeds the closed date.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "courses = [[1,2]]", + "expected_output": "1", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "courses = [[3,2],[4,3]]", + "expected_output": "0", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[][]} courses\n * @return {number}\n */\nconst scheduleCourse = function (courses) {\n const compare = (a, b) => a[0] === b[0] ? 0 : (a[0] > b[0] ? -1 : 1)\n const queue = new PriorityQueue({ compare })\n courses.sort((a, b) => a[1] - b[1])\n let time = 0\n for(let e of courses) {\n time += e[0]\n queue.enqueue(e)\n if(time > e[1]) {\n const tmp = queue.dequeue()\n time -= tmp[0]\n }\n }\n return queue.size()\n}\n\n// another\n\n/**\n * @param {number[][]} courses\n * @return {number}\n */\nconst scheduleCourse = function(courses) {\n const pq = new PQ((a, b) => a[0] === b[0] ? a[1] < b[1] : a[0] > b[0])\n const n = courses.length\n courses.sort((a, b) => a[1] === b[1] ? a[0] - b[0] : a[1] - b[1])\n \n let time = 0\n for(const e of courses) {\n const [dur, end] = e\n time += dur\n pq.push(e)\n if(time > end) {\n const tmp = pq.pop()\n time -= tmp[0]\n }\n }\n \n return pq.size()\n};\n\nclass PQ {\n constructor(comparator = (a, b) => a > b) {\n this.heap = []\n this.top = 0\n this.comparator = comparator\n }\n size() {\n return this.heap.length\n }\n isEmpty() {\n return this.size() === 0\n }\n peek() {\n return this.heap[this.top]\n }\n push(...values) {\n values.forEach((value) => {\n this.heap.push(value)\n this.siftUp()\n })\n return this.size()\n }\n pop() {\n const poppedValue = this.peek()\n const bottom = this.size() - 1\n if (bottom > this.top) {\n this.swap(this.top, bottom)\n }\n this.heap.pop()\n this.siftDown()\n return poppedValue\n }\n replace(value) {\n const replacedValue = this.peek()\n this.heap[this.top] = value\n this.siftDown()\n return replacedValue\n }\n\n parent = (i) => ((i + 1) >>> 1) - 1\n left = (i) => (i << 1) + 1\n right = (i) => (i + 1) << 1\n greater = (i, j) => this.comparator(this.heap[i], this.heap[j])\n swap = (i, j) => ([this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]])\n siftUp = () => {\n let node = this.size() - 1\n while (node > this.top && this.greater(node, this.parent(node))) {\n this.swap(node, this.parent(node))\n node = this.parent(node)\n }\n }\n siftDown = () => {\n let node = this.top\n while (\n (this.left(node) < this.size() && this.greater(this.left(node), node)) ||\n (this.right(node) < this.size() && this.greater(this.right(node), node))\n ) {\n let maxChild =\n this.right(node) < this.size() &&\n this.greater(this.right(node), this.left(node))\n ? this.right(node)\n : this.left(node)\n this.swap(node, maxChild)\n node = maxChild\n }\n }\n}\n\n// another\n\n\n/**\n * @param {number[][]} courses\n * @return {number}\n */\nconst scheduleCourse = function (courses) {\n const queue = new MaxPriorityQueue({\n priority: e => e[0]\n })\n courses.sort((a, b) => a[1] - b[1])\n let time = 0\n for(let e of courses) {\n time += e[0]\n queue.enqueue(e)\n if(time > e[1]) {\n const tmp = queue.dequeue().element\n time -= tmp[0]\n }\n }\n return queue.size()\n}\n\n// another\n\n/**\n * @param {number[][]} courses\n * @return {number}\n */\nconst scheduleCourse = function (courses) {\n courses.sort((c1, c2) => c1[1] - c2[1])\n let count = 0\n let time = 0\n const queue = []\n const inQueue = (val) => {\n let i = 0\n while (i < queue.length && queue[i] > val) i += 1\n queue.splice(i, 0, val)\n }\n for (let i = 0; i < courses.length; i += 1) {\n const [dur, end] = courses[i]\n if (time <= end - dur) {\n count += 1\n time += dur\n inQueue(dur)\n } else if (queue.length && queue[0] > dur) {\n time = time - queue.shift() + dur\n inQueue(dur)\n }\n }\n return count\n}\n\n// another\n\n/**\n * @param {number[][]} courses\n * @return {number}\n */\nconst scheduleCourse = function (courses) {\n courses.sort((a, b) => +a[1] - +b[1])\n let queue = new Heap()\n let time = 0\n for (let c of courses) {\n if (c[0] + time <= c[1]) {\n time += c[0]\n queue.push(c[0])\n } else if (queue.size() > 0) {\n let top = queue.peek()\n if (top > c[0]) {\n queue.pop()\n queue.push(c[0])\n time += c[0] - top\n }\n }\n }\n return queue.size()\n}\n\nconst parent = (i) => Math.floor((i - 1) / 2)\nconst left = (i) => 2 * i + 1\nconst right = (i) => 2 * i + 2\nclass Heap {\n constructor() {\n this.compare = (a, b) => +b - +a\n this._heap = []\n }\n size() {\n return this._heap.length\n }\n _upper(i, j) {\n return this.compare(this._heap[i], this._heap[j]) < 0\n }\n _swap(i, j) {\n let tmp = this._heap[i]\n this._heap[i] = this._heap[j]\n this._heap[j] = tmp\n }\n push(item) {\n this._heap.push(item)\n this._siftUp()\n return this.size()\n }\n _siftUp() {\n let node = this._heap.length - 1\n while (node > 0 && this._upper(node, parent(node))) {\n this._swap(node, parent(node))\n node = parent(node)\n }\n }\n peek() {\n return this._heap[0]\n }\n pop() {\n let ret = this._heap[0]\n if (this.size() > 1) {\n this._swap(0, this._heap.length - 1)\n }\n this._heap.pop()\n this._siftDown()\n return ret\n }\n _siftDown() {\n let node = 0\n while (\n (right(node) < this.size() && this._upper(right(node), node)) ||\n (left(node) < this.size() && this._upper(left(node), node))\n ) {\n let upperChild =\n right(node) < this.size() && this._upper(right(node), left(node))\n ? right(node)\n : left(node)\n this._swap(upperChild, node)\n node = upperChild\n }\n }\n}\n\n" + }, + { + "_id": "66f925ddfdfb8e1665720c0b", + "questionid": 320, + "title": "Shopping Offers", + "slug": "shopping-offers", + "description": "In LeetCode Store, there are n items to sell. Each item has a price. However, there are some special offers, and a special offer consists of one or more different kinds of items with a sale price. You are given an integer array price where price[i] is the price of the ith item, and an integer array needs where needs[i] is the number of pieces of the ith item you want to buy. You are also given an array special where special[i] is of size n + 1 where special[i][j] is the number of pieces of the jth item in the ith offer and special[i][n] (i.e., the last integer in the array) is the price of the ith offer. Return the lowest price you have to pay for exactly certain items as given, where you could make optimal use of the special offers. You are not allowed to buy more items than you want, even if that would lower the overall price. You could use any of the special offers as many times as you want. ", + "category": [ + "Array", + "Dynamic Programming", + "Backtracking", + "Bit Manipulation", + "Memoization", + "Bitmask" + ], + "complexity": "Medium", + "successrate": 54.6, + "totalsubmissions": 83312, + "totalaccepted": 45471, + "likes": 983, + "dislikes": 633, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "price = [2,5], special = [[3,0,5],[1,2,10]], needs = [3,2]", + "expected_output": "14", + "explanation": "There are two kinds of items, A and B. Their prices are $2 and $5 respectively. \nIn special offer 1, you can pay $5 for 3A and 0B\nIn special offer 2, you can pay $10 for 1A and 2B. \nYou need to buy 3A and 2B, so you may pay $10 for 1A and 2B (special offer #2), and $4 for 2A." + }, + { + "example_num": 2, + "expected_input": "price = [2,3,4], special = [[1,1,0,4],[2,2,1,9]], needs = [1,2,1]", + "expected_output": "11", + "explanation": "The price of A is $2, and $3 for B, $4 for C. \nYou may pay $4 for 1A and 1B, and $9 for 2A ,2B and 1C. \nYou need to buy 1A ,2B and 1C, so you may pay $4 for 1A and 1B (special offer #1), and $3 for 1B, $4 for 1C. \nYou cannot add more items, though only $9 for 2A ,2B and 1C." + } + ], + "solution": "/**\n * @param {number[]} price\n * @param {number[][]} special\n * @param {number[]} needs\n * @return {number}\n */\nconst shoppingOffers = function (price, special, needs) {\n return helper(price, special, needs, 0)\n}\n\nfunction helper(price, special, needs, pos) {\n let local_min = directPurchase(price, needs)\n for (let i = pos; i < special.length; i++) {\n let offer = special[i]\n let temp = []\n for (let j = 0; j < needs.length; j++) {\n if (needs[j] < offer[j]) {\n // check if the current offer is valid\n temp = null\n break\n }\n temp.push(needs[j] - offer[j])\n }\n\n if (temp !== null) {\n // use the current offer and try next\n local_min = Math.min(\n local_min,\n offer[offer.length - 1] + helper(price, special, temp, i),\n )\n }\n }\n\n return local_min\n}\n\nfunction directPurchase(price, needs) {\n let total = 0\n for (let i = 0; i < needs.length; i++) {\n total += price[i] * needs[i]\n }\n\n return total\n}\n\n\n// another\n\n/**\n * @param {number[]} price\n * @param {number[][]} special\n * @param {number[]} needs\n * @return {number}\n */\nconst shoppingOffers = function (price, special, needs) {\n const directBuy = function (price, needs) {\n let res = 0\n for (let i = 0; i < price.length; i++) {\n res += price[i] * needs[i]\n }\n return res\n }\n const isValid = function (offer, needs) {\n for (let i = 0; i < offer.length; i++) {\n if (offer[i] > needs[i]) return false\n }\n return true\n }\n const help = (price, special, needs) => {\n let curMin = directBuy(price, needs)\n for (let i = 0; i < special.length; i++) {\n let curOf = special[i]\n if (isValid(curOf, needs)) {\n let tem = []\n for (let j = 0; j < needs.length; j++) {\n tem.push(needs[j] - curOf[j])\n }\n if (tem.length > 0) {\n curMin = Math.min(\n curMin,\n curOf[curOf.length - 1] + help(price, special, tem)\n )\n }\n }\n }\n return curMin\n }\n return help(price, special, needs)\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720c10", + "questionid": 325, + "title": "Palindromic Substrings", + "slug": "palindromic-substrings", + "description": "Given a string s, return the number of palindromic substrings in it. A string is a palindrome when it reads the same backward as forward. A substring is a contiguous sequence of characters within the string. ", + "category": [ + "String", + "Dynamic Programming" + ], + "complexity": "Medium", + "successrate": 64.6, + "totalsubmissions": 614298, + "totalaccepted": 396625, + "likes": 6149, + "dislikes": 153, + "hints": "How can we reuse a previously computed palindrome to compute a larger palindrome? If \u20ac\u0153aba\u20ac\u009d is a palindrome, is \u20ac\u0153xabax\u20ac\u009d and palindrome? Similarly is \u20ac\u0153xabay\u20ac\u009d a palindrome? Complexity based hint:\r\nIf we use brute-force and check whether for every start and end position a substring is a palindrome we have O(n^2) start - end pairs and O(n) palindromic checks. Can we reduce the time for palindromic checks to O(1) by reusing some previous computation?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "abc"", + "expected_output": "3", + "explanation": "Three palindromic strings: "a", "b", "c"." + }, + { + "example_num": 2, + "expected_input": "s = "aaa"", + "expected_output": "6", + "explanation": "Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa"." + } + ], + "solution": "/**\n * @param {string} s\n * @return {number}\n */\nconst countSubstrings = function(s) {\n let count = 0;\n\n if (s == null || s.length === 0) {\n return 0;\n }\n\n for (let i = 0; i < s.length; i++) {\n extendPalindrome(s, i, i);\n extendPalindrome(s, i, i + 1);\n }\n\n function extendPalindrome(str, left, right) {\n while (\n left >= 0 &&\n right < s.length &&\n s.charAt(left) === s.charAt(right)\n ) {\n count++;\n left--;\n right++;\n }\n }\n return count;\n};\n\nconsole.log(countSubstrings(\"abc\"));\nconsole.log(countSubstrings(\"aaa\"));\n\n// another\n\n/**\n * @param {string} s\n * @return {number}\n */\nconst countSubstrings = function(s) {\n const arr = manachers(s)\n return arr.map(e => ~~((e + 1) / 2)).reduce((ac, e) => ac + e, 0)\n};\n\nfunction manachers(s) {\n const str = `@#${s.split('').join('#')}#$`\n const arr = Array(str.length).fill(0)\n \n let center = right = 0\n for(let i = 1, n = str.length; i < n - 1; i++) {\n if(i < right) {\n arr[i] = Math.min(right - i, arr[2 * center - i])\n }\n while(str[i + arr[i] + 1] === str[i - arr[i] - 1]) {\n arr[i] += 1\n }\n if(i + arr[i] > right) {\n center = i\n right = i + arr[i]\n }\n }\n \n return arr\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720c0c", + "questionid": 321, + "title": "Solve the Equation", + "slug": "solve-the-equation", + "description": "Solve a given equation and return the value of 'x' in the form of a string \"x=#value\". The equation contains only '+', '-' operation, the variable 'x' and its coefficient. You should return \"No solution\" if there is no solution for the equation, or \"Infinite solutions\" if there are infinite solutions for the equation. If there is exactly one solution for the equation, we ensure that the value of 'x' is an integer. ", + "category": [ + "Math", + "String", + "Simulation" + ], + "complexity": "Medium", + "successrate": 43.3, + "totalsubmissions": 74026, + "totalaccepted": 32029, + "likes": 367, + "dislikes": 691, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "equation = "x+5-3+x=6+x-2"", + "expected_output": ""x=2"", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "equation = "x=x"", + "expected_output": ""Infinite solutions"", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "equation = "2x=x"", + "expected_output": ""x=0"", + "explanation": "" + } + ], + "solution": "/**\n * @param {string} equation\n * @return {string}\n */\nfunction solveEquation (equation) {\n const strArr = equation.split('=')\n const leftHash = build(strArr[0])\n const rightHash = build(strArr[1])\n const xnum = leftHash.x - rightHash.x\n const num = rightHash.num - leftHash.num\n if(xnum === 0 && num !== 0) {\n return \"No solution\"\n } else if(xnum === 0) {\n return \"Infinite solutions\"\n } else {\n return `x=${num / xnum}`\n }\n};\n\nfunction build(str) {\n let cur = ''\n const map = {\n num:0,\n x:0\n }\n for(let i = 0; i < str.length; i++) {\n if(str[i] === '-' || str[i] === '+') {\n chkCur(cur, map)\n cur = str[i]\n } else {\n cur += str[i]\n }\n }\n if(cur !== '') {\n chkCur(cur, map)\n }\n return map\n}\nfunction chkCur(cur, map) {\n let xIdx = cur.indexOf('x')\n if(xIdx === -1) {\n map.num += +cur\n } else {\n map.x += chkX(cur, xIdx)\n }\n}\nfunction chkX(str, xIdx) {\n let tmp = str.slice(0,xIdx)\n let num = 0\n if(tmp === '-') {\n num = -1\n } else if(tmp === '' || tmp === '+') {\n num = 1\n } else {\n num = +tmp\n }\n return num\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720c11", + "questionid": 326, + "title": "Replace Words", + "slug": "replace-words", + "description": "In English, we have a concept called root, which can be followed by some other word to form another longer word - let's call this word successor. For example, when the root \"an\" is followed by the successor word \"other\", we can form a new word \"another\". Given a dictionary consisting of many roots and a sentence consisting of words separated by spaces, replace all the successors in the sentence with the root forming it. If a successor can be replaced by more than one root, replace it with the root that has the shortest length. Return the sentence after the replacement. ", + "category": [ + "Array", + "Hash Table", + "String", + "Trie" + ], + "complexity": "Medium", + "successrate": 61.9, + "totalsubmissions": 152554, + "totalaccepted": 94448, + "likes": 1483, + "dislikes": 152, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "dictionary = ["cat","bat","rat"], sentence = "the cattle was rattled by the battery"", + "expected_output": ""the cat was rat by the bat"", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "dictionary = ["a","b","c"], sentence = "aadsfasf absbs bbab cadsfafs"", + "expected_output": ""a a b c"", + "explanation": "" + } + ], + "solution": "/**\n * @param {string[]} dict\n * @param {string} sentence\n * @return {string}\n */\nconst replaceWords = function(dict, sentence) {\n dict.sort();\n const unsortedParts = sentence.split(\" \");\n const parts = unsortedParts.slice();\n parts.sort();\n\n let i = (j = 0);\n const rootMap = {};\n while (i < dict.length && j < parts.length) {\n let part = parts[j];\n let root = dict[i];\n // dict is ahead, increase part\n if (root > part) {\n j++;\n } else {\n if (part.startsWith(root)) {\n rootMap[part] = root;\n j++;\n } else {\n i++;\n }\n }\n }\n for (i = 0; i < unsortedParts.length; i++) {\n if (rootMap[unsortedParts[i]]) {\n unsortedParts[i] = rootMap[unsortedParts[i]];\n }\n }\n return unsortedParts.join(\" \");\n};\n\nconsole.log(\n replaceWords([\"cat\", \"bat\", \"rat\"], \"the cattle was rattled by the battery\")\n);\n" + }, + { + "_id": "66f925ddfdfb8e1665720c14", + "questionid": 329, + "title": "Image Smoother", + "slug": "image-smoother", + "description": "An image smoother is a filter of the size 3 x 3 that can be applied to each cell of an image by rounding down the average of the cell and the eight surrounding cells (i.e., the average of the nine cells in the blue smoother). If one or more of the surrounding cells of a cell is not present, we do not consider it in the average (i.e., the average of the four cells in the red smoother). Given an m x n integer matrix img representing the grayscale of an image, return the image after applying the smoother on each cell of it. ", + "category": [ + "Array", + "Matrix" + ], + "complexity": "Easy", + "successrate": 54.2, + "totalsubmissions": 117656, + "totalaccepted": 63743, + "likes": 376, + "dislikes": 1580, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "img = [[1,1,1],[1,0,1],[1,1,1]]", + "expected_output": "[[0,0,0],[0,0,0],[0,0,0]]", + "explanation": "For the points (0,0), (0,2), (2,0), (2,2): floor(3/4) = floor(0.75) = 0\nFor the points (0,1), (1,0), (1,2), (2,1): floor(5/6) = floor(0.83333333) = 0\nFor the point (1,1): floor(8/9) = floor(0.88888889) = 0" + }, + { + "example_num": 2, + "expected_input": "img = [[100,200,100],[200,50,200],[100,200,100]]", + "expected_output": "[[137,141,137],[141,138,141],[137,141,137]]", + "explanation": "For the points (0,0), (0,2), (2,0), (2,2): floor((100+200+200+50)/4) = floor(137.5) = 137\nFor the points (0,1), (1,0), (1,2), (2,1): floor((200+200+50+200+100+100)/6) = floor(141.666667) = 141\nFor the point (1,1): floor((50+200+200+200+200+100+100+100+100)/9) = floor(138.888889) = 138" + } + ], + "solution": "/**\n * @param {number[][]} M\n * @return {number[][]}\n */\nconst imageSmoother = function (M) {\n const r = M.length\n if (r === 0) return 0\n const c = M[0].length\n if (c === 0) return 0\n const res = Array.from({ length: r }, () => Array(c).fill(0))\n for (let i = 0; i < r; i++) {\n for (let j = 0; j < c; j++) {\n res[i][j] = helper(M, i, j, res)\n }\n }\n return res\n}\n\nfunction helper(M, i, j, res) {\n let val = M[i][j]\n let num = 1\n const dirs = [\n [-1, -1],\n [-1, 0],\n [-1, 1],\n [0, -1],\n [0, 1],\n [1, -1],\n [1, 0],\n [1, 1],\n ]\n for (let [dr, dc] of dirs) {\n const ii = i + dr\n const jj = j + dc\n if (M[ii] != null && M[ii][jj] != null) {\n val += M[ii][jj]\n num++\n }\n }\n return (val / num) >> 0\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720c1d", + "questionid": 338, + "title": "Valid Palindrome II", + "slug": "valid-palindrome-ii", + "description": "Given a string s, return true if the s can be palindrome after deleting at most one character from it. ", + "category": [ + "Two Pointers", + "String", + "Greedy" + ], + "complexity": "Easy", + "successrate": 39.4, + "totalsubmissions": 1227426, + "totalaccepted": 483424, + "likes": 5468, + "dislikes": 298, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "aba"", + "expected_output": "true", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "s = "abca"", + "expected_output": "true", + "explanation": "You could delete the character 'c'." + }, + { + "example_num": 3, + "expected_input": "s = "abc"", + "expected_output": "false", + "explanation": "" + } + ], + "solution": "/**\n * @param {string} s\n * @return {boolean}\n */\n\nconst validPalindrome = function(s) {\n let start = 0;\n let end = s.length - 1;\n\n const isPalindrome = function(start, end, removed) {\n while (start <= end) {\n if (s[start] !== s[end]) {\n if (removed) {\n return false;\n }\n\n return (\n isPalindrome(start + 1, end, true) ||\n isPalindrome(start, end - 1, true)\n );\n }\n start++;\n end--;\n }\n return true;\n };\n\n return isPalindrome(start, end, false);\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720c25", + "questionid": 346, + "title": "Count Binary Substrings", + "slug": "count-binary-substrings", + "description": "Give a binary string s, return the number of non-empty substrings that have the same number of 0's and 1's, and all the 0's and all the 1's in these substrings are grouped consecutively. Substrings that occur multiple times are counted the number of times they occur. ", + "category": [ + "Two Pointers", + "String" + ], + "complexity": "Easy", + "successrate": 64.8, + "totalsubmissions": 225586, + "totalaccepted": 146161, + "likes": 2806, + "dislikes": 593, + "hints": "How many valid binary substrings exist in \"000111\", and how many in \"11100\"? What about \"00011100\"?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "00110011"", + "expected_output": "6", + "explanation": "There are 6 substrings that have equal number of consecutive 1's and 0's: "0011", "01", "1100", "10", "0011", and "01".\nNotice that some of these substrings repeat and are counted the number of times they occur.\nAlso, "00110011" is not a valid substring because all the 0's (and 1's) are not grouped together." + }, + { + "example_num": 2, + "expected_input": "s = "10101"", + "expected_output": "4", + "explanation": "There are 4 substrings: "10", "01", "10", "01" that have equal number of consecutive 1's and 0's." + } + ], + "solution": null + }, + { + "_id": "66f925ddfdfb8e1665720c2c", + "questionid": 353, + "title": "Find K-th Smallest Pair Distance", + "slug": "find-k-th-smallest-pair-distance", + "description": "The distance of a pair of integers a and b is defined as the absolute difference between a and b. Given an integer array nums and an integer k, return the kth smallest distance among all the pairs nums[i] and nums[j] where 0 <= i < j < nums.length. ", + "category": [ + "Array", + "Two Pointers", + "Binary Search", + "Sorting" + ], + "complexity": "Hard", + "successrate": 35, + "totalsubmissions": 165915, + "totalaccepted": 58039, + "likes": 1921, + "dislikes": 62, + "hints": "Binary search for the answer. How can you check how many pairs have distance <= X?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,3,1], k = 1", + "expected_output": "0", + "explanation": "Here are all the pairs:\n(1,3) -> 2\n(1,1) -> 0\n(3,1) -> 2\nThen the 1st smallest distance pair is (1,1), and its distance is 0." + }, + { + "example_num": 2, + "expected_input": "nums = [1,1,1], k = 2", + "expected_output": "0", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "nums = [1,6,1], k = 3", + "expected_output": "5", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} nums\n * @param {number} k\n * @return {number}\n */\nfunction smallestDistancePair(nums, k) {\n nums.sort((a, b) => a - b)\n let l = 0, n = nums.length, r = nums[n - 1] - nums[0]\n \n let res = 0\n while(l < r) {\n let cnt = 0, mid = l + ((r - l) >> 1)\n for(let i = 0, j = 0; i < n; i++) {\n while(j < n && nums[j] <= nums[i] + mid) j++\n cnt += j - 1 - i\n }\n if(cnt < k) l = mid + 1\n else r = mid\n }\n\n return l\n}\n\n// another\n\n/**\n * @param {number[]} nums\n * @param {number} k\n * @return {number}\n */\nconst smallestDistancePair = function(nums, k) {\n nums.sort((a, b) => a - b)\n let lo = 0\n let hi = nums[nums.length - 1] - nums[0]\n while (lo < hi) {\n let mi = Math.floor((lo + hi) / 2)\n let count = 0\n let left = 0\n for (let right = 0; right < nums.length; right++) {\n while (nums[right] - nums[left] > mi) left++\n count += right - left\n }\n //count = number of pairs with distance <= mi\n if (count >= k) hi = mi\n else lo = mi + 1\n }\n return lo\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720c3b", + "questionid": 368, + "title": "Shortest Completing Word", + "slug": "shortest-completing-word", + "description": "Given a string licensePlate and an array of strings words, find the shortest completing word in words. A completing word is a word that contains all the letters in licensePlate. Ignore numbers and spaces in licensePlate, and treat letters as case insensitive. If a letter appears more than once in licensePlate, then it must appear in the word the same number of times or more. For example, if licensePlate = \"aBc 12c\", then it contains letters 'a', 'b' (ignoring case), and 'c' twice. Possible completing words are \"abccdef\", \"caaacab\", and \"cbca\". Return the shortest completing word in words. It is guaranteed an answer exists. If there are multiple shortest completing words, return the first one that occurs in words. ", + "category": [ + "Array", + "Hash Table", + "String" + ], + "complexity": "Easy", + "successrate": 58.9, + "totalsubmissions": 84073, + "totalaccepted": 49487, + "likes": 312, + "dislikes": 851, + "hints": "Count only the letters (possibly converted to lowercase) of each word. If a word is shorter and the count of each letter is at least the count of that letter in the licensePlate, it is the best answer we've seen yet.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "licensePlate = "1s3 PSt", words = ["step","steps","stripe","stepple"]", + "expected_output": ""steps"", + "explanation": "licensePlate contains letters 's', 'p', 's' (ignoring case), and 't'.\n"step" contains 't' and 'p', but only contains 1 's'.\n"steps" contains 't', 'p', and both 's' characters.\n"stripe" is missing an 's'.\n"stepple" is missing an 's'.\nSince "steps" is the only word containing all the letters, that is the answer." + }, + { + "example_num": 2, + "expected_input": "licensePlate = "1s3 456", words = ["looks","pest","stew","show"]", + "expected_output": ""pest"", + "explanation": "licensePlate only contains the letter 's'. All the words contain 's', but among these "pest", "stew", and "show" are shortest. The answer is "pest" because it is the word that appears earliest of the 3." + } + ], + "solution": "/**\n * @param {string} licensePlate\n * @param {string[]} words\n * @return {string}\n */\nconst shortestCompletingWord = function(licensePlate, words) {\n const letters = licensePlate\n .replace(/\\d/g, '')\n .replace(/ /g, '')\n .toLowerCase()\n .split('')\n let matchingWords = words.filter(word => {\n let completingWord = true\n letters.forEach(letter => {\n let letterIndex = word.indexOf(letter)\n if (letterIndex > -1) {\n let re = new RegExp(letter)\n word = word.replace(re, '')\n } else {\n completingWord = false\n }\n })\n return completingWord\n })\n const wordLengths = matchingWords.map(word => word.length)\n return matchingWords[wordLengths.indexOf(Math.min.apply(Math, wordLengths))]\n}\n\n// another\n\n/**\n * @param {string} licensePlate\n * @param {string[]} words\n * @return {string}\n */\nconst shortestCompletingWord = function(licensePlate, words) {\n licensePlate = licensePlate.toLowerCase()\n const plateCount = Array(26).fill(0)\n let plateLength = 0\n for (let i = 0; i < licensePlate.length; i += 1) {\n const code = licensePlate.charCodeAt(i)\n if (code < 97 || code > 122) {\n continue\n }\n plateCount[code - 97] += 1\n plateLength += 1\n }\n const longerOrEqualWords = words.filter(word => word.length >= plateLength)\n return longerOrEqualWords.reduce((shortest, word) => {\n if (shortest && shortest.length <= word.length) {\n return shortest\n }\n const wordCount = Array(26).fill(0)\n for (let i = 0; i < word.length; i += 1) {\n const code = word.charCodeAt(i)\n wordCount[code - 97] += 1\n }\n for (let i = 0; i < 26; i += 1) {\n if (wordCount[i] - plateCount[i] < 0) {\n return shortest\n }\n }\n return word\n }, null)\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720c41", + "questionid": 374, + "title": "Flatten a Multilevel Doubly Linked List", + "slug": "flatten-a-multilevel-doubly-linked-list", + "description": "You are given a doubly linked list, which contains nodes that have a next pointer, a previous pointer, and an additional child pointer. This child pointer may or may not point to a separate doubly linked list, also containing these special nodes. These child lists may have one or more children of their own, and so on, to produce a multilevel data structure as shown in the example below. Given the head of the first level of the list, flatten the list so that all the nodes appear in a single-level, doubly linked list. Let curr be a node with a child list. The nodes in the child list should appear after curr and before curr.next in the flattened list. Return the head of the flattened list. The nodes in the list must have all of their child pointers set to null. ", + "category": [ + "Linked List", + "Depth-First Search", + "Doubly-Linked List" + ], + "complexity": "Medium", + "successrate": 58.9, + "totalsubmissions": 389156, + "totalaccepted": 229148, + "likes": 3579, + "dislikes": 249, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "head = [1,2,3,4,5,6,null,null,null,7,8,9,10,null,null,11,12]", + "expected_output": "[1,2,3,7,8,11,12,9,10,4,5,6]", + "explanation": "The multilevel linked list in the input is shown.\nAfter flattening the multilevel linked list it becomes:\n" + }, + { + "example_num": 2, + "expected_input": "head = [1,2,null,3]", + "expected_output": "[1,3,2]", + "explanation": "The multilevel linked list in the input is shown.\nAfter flattening the multilevel linked list it becomes:\n" + }, + { + "example_num": 3, + "expected_input": "head = []", + "expected_output": "[]", + "explanation": "There could be empty list in the input." + } + ], + "solution": "/**\n * // Definition for a Node.\n * function Node(val,prev,next,child) {\n * this.val = val;\n * this.prev = prev;\n * this.next = next;\n * this.child = child;\n * };\n */\n/**\n * @param {Node} head\n * @return {Node}\n */\nconst flatten = function (head) {\n const handle = (node, next = null) => {\n if (!node) return null;\n handle(node.next, next);\n const child = handle(node.child, node.next);\n if (!node.next && next) {\n node.next = next;\n next.prev = node;\n }\n if (child) {\n node.next = child;\n node.child = null;\n child.prev = node;\n }\n return node;\n };\n return handle(head);\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720c42", + "questionid": 375, + "title": "Prime Number of Set Bits in Binary Representation", + "slug": "prime-number-of-set-bits-in-binary-representation", + "description": "Given two integers left and right, return the count of numbers in the inclusive range [left, right] having a prime number of set bits in their binary representation. Recall that the number of set bits an integer has is the number of 1's present when written in binary. ", + "category": [ + "Math", + "Bit Manipulation" + ], + "complexity": "Easy", + "successrate": 66.7, + "totalsubmissions": 102152, + "totalaccepted": 68143, + "likes": 452, + "dislikes": 460, + "hints": "Write a helper function to count the number of set bits in a number, then check whether the number of set bits is 2, 3, 5, 7, 11, 13, 17 or 19.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "left = 6, right = 10", + "expected_output": "4", + "explanation": "6 -> 110 (2 set bits, 2 is prime)\n7 -> 111 (3 set bits, 3 is prime)\n8 -> 1000 (1 set bit, 1 is not prime)\n9 -> 1001 (2 set bits, 2 is prime)\n10 -> 1010 (2 set bits, 2 is prime)\n4 numbers have a prime number of set bits." + }, + { + "example_num": 2, + "expected_input": "left = 10, right = 15", + "expected_output": "5", + "explanation": "10 -> 1010 (2 set bits, 2 is prime)\n11 -> 1011 (3 set bits, 3 is prime)\n12 -> 1100 (2 set bits, 2 is prime)\n13 -> 1101 (3 set bits, 3 is prime)\n14 -> 1110 (3 set bits, 3 is prime)\n15 -> 1111 (4 set bits, 4 is not prime)\n5 numbers have a prime number of set bits." + } + ], + "solution": "/**\n * @param {number} L\n * @param {number} R\n * @return {number}\n */\nconst countPrimeSetBits = function(L, R) {\n let res = 0;\n for (let i = L; i <= R; i++) {\n if (chkPrime(i)) {\n res += 1;\n }\n }\n return res;\n};\n\nfunction chkPrime(num) {\n const str = bin(num);\n const snum = setNum(str);\n return isPrime(snum);\n}\n\nfunction setNum(str) {\n let num = 0;\n for (let i = 0; i < str.length; i++) {\n if (str.charAt(i) === \"1\") {\n num += 1;\n }\n }\n return num;\n}\n\nfunction bin(num) {\n return (num >>> 0).toString(2);\n}\nfunction isPrime(num) {\n for (let i = 2; i < num; i++) {\n if (num % i === 0) return false;\n }\n return num !== 1;\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720c43", + "questionid": 376, + "title": "Partition Labels", + "slug": "partition-labels", + "description": "You are given a string s. We want to partition the string into as many parts as possible so that each letter appears in at most one part. Note that the partition is done so that after concatenating all the parts in order, the resultant string should be s. Return a list of integers representing the size of these parts. ", + "category": [ + "Hash Table", + "Two Pointers", + "String", + "Greedy" + ], + "complexity": "Medium", + "successrate": 79.5, + "totalsubmissions": 475982, + "totalaccepted": 378565, + "likes": 7541, + "dislikes": 287, + "hints": "Try to greedily choose the smallest partition that includes the first letter. If you have something like \"abaccbdeffed\", then you might need to add b. You can use an map like \"last['b'] = 5\" to help you expand the width of your partition.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "ababcbacadefegdehijhklij"", + "expected_output": "[9,7,8]", + "explanation": "The partition is "ababcbaca", "defegde", "hijhklij".\nThis is a partition so that each letter appears in at most one part.\nA partition like "ababcbacadefegde", "hijhklij" is incorrect, because it splits s into less parts." + }, + { + "example_num": 2, + "expected_input": "s = "eccbbbbdec"", + "expected_output": "[10]", + "explanation": "" + } + ], + "solution": "/**\n * @param {string} S\n * @return {number[]}\n */\nconst partitionLabels = function (S) {\n if (S == null || S.length === 0) {\n return null\n }\n const list = []\n // record the last index of the each char\n const map = new Array(26).fill(0)\n const a = 'a'.charCodeAt(0)\n for (let i = 0, len = S.length; i < len; i++) {\n map[S.charCodeAt(i) - a] = i\n }\n // record the end index of the current sub string\n let last = 0\n let start = 0\n for (let i = 0, len = S.length; i < len; i++) {\n last = Math.max(last, map[S.charCodeAt(i) - a])\n if (last === i) {\n list.push(last - start + 1)\n start = last + 1\n }\n }\n return list\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720c46", + "questionid": 379, + "title": "Maximum Depth of N-ary Tree", + "slug": "maximum-depth-of-n-ary-tree", + "description": "Given a n-ary tree, find its maximum depth. The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See examples). ", + "category": [ + "Tree", + "Depth-First Search", + "Breadth-First Search" + ], + "complexity": "Easy", + "successrate": 71, + "totalsubmissions": 291893, + "totalaccepted": 207200, + "likes": 1947, + "dislikes": 69, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [1,null,3,2,4,null,5,6]", + "expected_output": "3", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]", + "expected_output": "5", + "explanation": "" + } + ], + "solution": "/**\n * // Definition for a Node.\n * function Node(val,children) {\n * this.val = val;\n * this.children = children;\n * };\n */\n/**\n * @param {Node} root\n * @return {number}\n */\nconst maxDepth = function(root) {\n let max = 0\n if(root == null) return 0\n function dfs(node, depth) {\n if(node == null || node.children.length === 0) {\n depth++\n if(depth > max) max = depth\n return\n }\n depth++\n for(let n of node.children) {\n dfs(n, depth)\n }\n }\n dfs(root, 0)\n return max\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720c49", + "questionid": 382, + "title": "Toeplitz Matrix", + "slug": "toeplitz-matrix", + "description": "Given an m x n matrix, return\u00a0true\u00a0if the matrix is Toeplitz. Otherwise, return false. A matrix is Toeplitz if every diagonal from top-left to bottom-right has the same elements. ", + "category": [ + "Array", + "Matrix" + ], + "complexity": "Easy", + "successrate": 68, + "totalsubmissions": 269427, + "totalaccepted": 183077, + "likes": 1915, + "dislikes": 119, + "hints": "Check whether each value is equal to the value of it's top-left neighbor.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "matrix = [[1,2,3,4],[5,1,2,3],[9,5,1,2]]", + "expected_output": "true", + "explanation": "In the above grid, the diagonals are:\n"[9]", "[5, 5]", "[1, 1, 1]", "[2, 2, 2]", "[3, 3]", "[4]".\nIn each diagonal all elements are the same, so the answer is True." + }, + { + "example_num": 2, + "expected_input": "matrix = [[1,2],[2,2]]", + "expected_output": "false", + "explanation": "The diagonal "[1, 2]" has different elements." + } + ], + "solution": "/**\n * @param {number[][]} matrix\n * @return {boolean}\n */\nconst isToeplitzMatrix = function(matrix) {\n for (let r = 0; r < matrix.length; r++) {\n for (let c = 0; c < matrix[0].length; c++) {\n if (r > 0 && c > 0 && matrix[r - 1][c - 1] !== matrix[r][c]) {\n return false;\n }\n }\n }\n return true;\n};\n\nconsole.log(isToeplitzMatrix([[1, 2, 3, 4], [5, 1, 2, 3], [9, 5, 1, 2]]));\n\nconsole.log(isToeplitzMatrix([[1, 2], [2, 2]]));\n" + }, + { + "_id": "66f925ddfdfb8e1665720c4a", + "questionid": 383, + "title": "Reorganize String", + "slug": "reorganize-string", + "description": "Given a string s, rearrange the characters of s so that any two adjacent characters are not the same. Return any possible rearrangement of s or return \"\" if not possible. ", + "category": [ + "Hash Table", + "String", + "Greedy", + "Sorting", + "Heap (Priority Queue)", + "Counting" + ], + "complexity": "Medium", + "successrate": 52, + "totalsubmissions": 395857, + "totalaccepted": 205838, + "likes": 4519, + "dislikes": 173, + "hints": "Alternate placing the most common letters.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = \"aab\"", + "expected_output": "\"aba\"", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "s = \"aaab\"", + "expected_output": "\"\"", + "explanation": "" + } + ], + "solution": "/**\n * @param {string} s\n * @return {string}\n */\nconst reorganizeString = function (s) {\n const freq = Array(26).fill(0)\n const a = 'a'.charCodeAt(0), n = s.length\n for(const e of s) {\n freq[e.charCodeAt(0) - a]++\n }\n let max = 0, maxIdx = 0\n for(let i = 0; i < 26; i++) {\n if(freq[i] > max) {\n max = freq[i]\n maxIdx = i\n }\n }\n\n if(max > (n + 1) / 2) return ''\n\n const res = Array(n)\n\n let idx = 0\n while(freq[maxIdx]) {\n res[idx] = String.fromCharCode(a + maxIdx)\n idx += 2\n freq[maxIdx]--\n }\n\n for(let i = 0; i < 26; i++) {\n while(freq[i]) {\n if(idx >= n) idx = 1\n res[idx] = String.fromCharCode(i + a)\n idx += 2\n freq[i]--\n }\n }\n\n return res.join('')\n}\n\n// another\n\n\n/**\n * @param {string} S\n * @return {string}\n */\nconst reorganizeString = function(S) {\n if (!S || S.length <= 1) {\n return S;\n }\n const freqs = Array(26).fill(0);\n const acode = 'a'.charCodeAt(0);\n for (let i = 0, n = S.length; i < n; i++) {\n const index = S.charCodeAt(i) - acode;\n freqs[index]++;\n if (freqs[index] > Math.ceil(n / 2)) {\n return '';\n }\n }\n const list = [];\n for (let i = 0, n = S.length; i < 26; i++) {\n if (freqs[i] === 0) {\n continue;\n }\n list.push({ch: String.fromCharCode(i + acode), freq: freqs[i]});\n }\n list.sort((l1, l2) => l2.freq - l1.freq);\n const parts = [];\n for (let i = 0, n = list[0].freq; i < n; i++) {\n parts.push(list[0].ch);\n }\n let idx = 0;\n for (let i = 1, n = list.length; i < n; i++) {\n for (let j = 0, m = list[i].freq; j < m; j++) {\n idx %= list[0].freq;\n parts[idx++] += list[i].ch;\n }\n }\n return parts.join('');\n};\n\n// another\n\n/**\n * @param {string} s\n * @return {string}\n */\nconst reorganizeString = function(s) {\n const arr = Array(26).fill(0), a = 'a'.charCodeAt(0)\n for(let ch of s) arr[ch.charCodeAt(0) - a]++\n let max = 0, idx = -1\n for(let i = 0; i < 26; i++) {\n if(arr[i] > max) {\n max = arr[i]\n idx = i\n }\n }\n const n = s.length\n const res = Array(n)\n if(max > (n + 1) / 2) return ''\n\n let i = 0\n while(arr[idx] > 0) {\n res[i] = String.fromCharCode(a + idx)\n i += 2\n arr[idx]--\n }\n \n for(let j = 0; j < 26; j++) {\n while(arr[j]) {\n if(i >= n) i = 1\n res[i] = String.fromCharCode(a + j)\n i += 2\n arr[j]--\n }\n }\n return res.join('')\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720c15", + "questionid": 330, + "title": "Maximum Width of Binary Tree", + "slug": "maximum-width-of-binary-tree", + "description": "Given the root of a binary tree, return the maximum width of the given tree. The maximum width of a tree is the maximum width among all levels. The width of one level is defined as the length between the end-nodes (the leftmost and rightmost non-null nodes), where the null nodes between the end-nodes that would be present in a complete binary tree extending down to that level are also counted into the length calculation. It is guaranteed that the answer will in the range of a 32-bit signed integer. ", + "category": [ + "Tree", + "Depth-First Search", + "Breadth-First Search", + "Binary Tree" + ], + "complexity": "Medium", + "successrate": 40.2, + "totalsubmissions": 448427, + "totalaccepted": 180303, + "likes": 4442, + "dislikes": 714, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [1,3,2,5,3,null,9]", + "expected_output": "4", + "explanation": "The maximum width exists in the third level with length 4 (5,3,null,9)." + }, + { + "example_num": 2, + "expected_input": "root = [1,3,2,5,null,null,9,6,null,7]", + "expected_output": "7", + "explanation": "The maximum width exists in the fourth level with length 7 (6,null,null,null,null,null,7)." + }, + { + "example_num": 3, + "expected_input": "root = [1,3,2,5]", + "expected_output": "2", + "explanation": "The maximum width exists in the second level with length 2 (3,2)." + } + ], + "solution": "/**\n * Definition for a binary tree node.\n * function TreeNode(val, left, right) {\n * this.val = (val===undefined ? 0 : val)\n * this.left = (left===undefined ? null : left)\n * this.right = (right===undefined ? null : right)\n * }\n */\n/**\n * @param {TreeNode} root\n * @return {number}\n */\nconst widthOfBinaryTree = function (root) {\n let max = 1n\n const stack = []\n const bi = BigInt\n const width = (root, level, pos) => {\n if (root == null) return\n if (level >= stack.length) stack.push(pos)\n else {\n // console.log(stack)\n const tmp = pos - stack[level] + 1n\n if(tmp > max) max = tmp\n }\n width(root.left, level + 1, 2n * pos)\n width(root.right, level + 1, 2n * pos + 1n)\n }\n width(root, 0, 1n)\n return Number(max)\n}\n\n\n// another\n\n/**\n * Definition for a binary tree node.\n * function TreeNode(val) {\n * this.val = val;\n * this.left = this.right = null;\n * }\n */\n/**\n * @param {TreeNode} root\n * @return {number}\n */\nconst widthOfBinaryTree = function(root) {\n const mins = [0]\n let max = 0\n \n dfs(root, 0, 0)\n return max\n \n // depth first search\n function dfs(currentNode, depth, position) {\n if (!currentNode) return\n if (depth === mins.length) {\n mins[depth] = position\n }\n \n const delta = position - mins[depth]\n max = Math.max(max, delta + 1)\n dfs(currentNode.left, depth + 1, delta * 2)\n dfs(currentNode.right, depth + 1, delta * 2 + 1)\n }\n }\n" + }, + { + "_id": "66f925ddfdfb8e1665720c17", + "questionid": 332, + "title": "Kth Smallest Number in Multiplication Table", + "slug": "kth-smallest-number-in-multiplication-table", + "description": "Nearly everyone has used the Multiplication Table. The multiplication table of size m x n is an integer matrix mat where mat[i][j] == i * j (1-indexed). Given three integers m, n, and k, return the kth smallest element in the m x n multiplication table. ", + "category": [ + "Binary Search" + ], + "complexity": "Hard", + "successrate": 51, + "totalsubmissions": 93964, + "totalaccepted": 47939, + "likes": 1592, + "dislikes": 45, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "m = 3, n = 3, k = 5", + "expected_output": "3", + "explanation": "The 5th smallest number is 3." + }, + { + "example_num": 2, + "expected_input": "m = 2, n = 3, k = 6", + "expected_output": "6", + "explanation": "The 6th smallest number is 6." + } + ], + "solution": "/**\n * @param {number} m\n * @param {number} n\n * @param {number} k\n * @return {number}\n */\nconst findKthNumber = function(m, n, k) {\n let left = 1;\n let right = m * n;\n while (left < right) {\n const mid = Math.floor((left + right) / 2);\n const nSmaller = count(m, n, mid);\n if (nSmaller >= k) {\n right = mid;\n } else {\n left = mid + 1;\n }\n }\n return left;\n};\n\nfunction count(m, n, target) {\n let nSmaller = 0;\n let j = n;\n for (let i = 1; i <= m; i++) {\n while (i * j > target) {\n j -= 1;\n }\n nSmaller += j;\n }\n return nSmaller;\n}\n\n// another\n\n/**\n * @param {number} m\n * @param {number} n\n * @param {number} k\n * @return {number}\n */\nconst findKthNumber = function(m, n, k) {\n let left = 1;\n let right = m * n;\n while (left < right) {\n const mid = Math.floor((left + right) / 2);\n const num = count(m, n, mid);\n if (num < k) left = mid + 1;\n else right = mid;\n }\n return left;\n};\n\nfunction count(m, n, target) {\n let res = 0;\n let j = n;\n for (let i = 1; i <= m; i++) {\n while (i * j > target) j--\n res += j;\n }\n return res;\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720c1f", + "questionid": 340, + "title": "Redundant Connection II", + "slug": "redundant-connection-ii", + "description": "In this problem, a rooted tree is a directed graph such that, there is exactly one node (the root) for which all other nodes are descendants of this node, plus every node has exactly one parent, except for the root node which has no parents. The given input is a directed graph that started as a rooted tree with n nodes (with distinct values from 1 to n), with one additional directed edge added. The added edge has two different vertices chosen from 1 to n, and was not an edge that already existed. The resulting graph is given as a 2D-array of edges. Each element of edges is a pair [ui, vi] that represents a directed edge connecting nodes ui and vi, where ui is a parent of child vi. Return an edge that can be removed so that the resulting graph is a rooted tree of n nodes. If there are multiple answers, return the answer that occurs last in the given 2D-array. ", + "category": [ + "Depth-First Search", + "Breadth-First Search", + "Union Find", + "Graph" + ], + "complexity": "Hard", + "successrate": 33.7, + "totalsubmissions": 152361, + "totalaccepted": 51386, + "likes": 1538, + "dislikes": 265, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "edges = [[1,2],[1,3],[2,3]]", + "expected_output": "[2,3]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "edges = [[1,2],[2,3],[3,4],[4,1],[1,5]]", + "expected_output": "[4,1]", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[][]} edges\n * @return {number[]}\n */\nconst findRedundantDirectedConnection = function (edges) {\n const parent = []\n //detect circle\n for (let i = 1; i <= edges.length; i++) {\n parent[i] = i\n }\n let circleEdge, removedEdge, candidateEdge\n for (let i = 0; i < edges.length; i++) {\n const [u, v] = edges[i]\n const pu = findParent(parent, u)\n const pv = findParent(parent, v)\n if (pv !== v) {\n removedEdge = [u, v] // node with 2 parents\n } else {\n if (pv === pu) {\n circleEdge = [u, v] // circle edge\n }\n parent[v] = pu\n }\n }\n if (!removedEdge) {\n return circleEdge\n }\n if (circleEdge) {\n return edges.find((d) => d[1] === removedEdge[1] && d[0] !== removedEdge[0])\n } else {\n return removedEdge\n }\n}\nconst findParent = function (parent, i) {\n if (parent[i] !== i) {\n parent[i] = findParent(parent, parent[i])\n }\n return parent[i]\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720c21", + "questionid": 342, + "title": "Knight Probability in Chessboard", + "slug": "knight-probability-in-chessboard", + "description": "On an n x n chessboard, a knight starts at the cell (row, column) and attempts to make exactly k moves. The rows and columns are 0-indexed, so the top-left cell is (0, 0), and the bottom-right cell is (n - 1, n - 1). A chess knight has eight possible moves it can make, as illustrated below. Each move is two cells in a cardinal direction, then one cell in an orthogonal direction. Each time the knight is to move, it chooses one of eight possible moves uniformly at random (even if the piece would go off the chessboard) and moves there. The knight continues moving until it has made exactly k moves or has moved off the chessboard. Return the probability that the knight remains on the board after it has stopped moving. ", + "category": [ + "Dynamic Programming" + ], + "complexity": "Medium", + "successrate": 51.5, + "totalsubmissions": 153524, + "totalaccepted": 79062, + "likes": 1905, + "dislikes": 287, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 3, k = 2, row = 0, column = 0", + "expected_output": "0.06250", + "explanation": "There are two moves (to (1,2), (2,1)) that will keep the knight on the board.\nFrom each of those positions, there are also two moves that will keep the knight on the board.\nThe total probability the knight stays on the board is 0.0625." + }, + { + "example_num": 2, + "expected_input": "n = 1, k = 0, row = 0, column = 0", + "expected_output": "1.00000", + "explanation": "" + } + ], + "solution": "/**\n * @param {number} N\n * @param {number} K\n * @param {number} r\n * @param {number} c\n * @return {number}\n */\nconst knightProbability = function (N, K, r, c) {\n const moves = [\n [1, 2],\n [1, -2],\n [2, 1],\n [2, -1],\n [-1, 2],\n [-1, -2],\n [-2, 1],\n [-2, -1],\n ]\n const dp = [...Array(K + 1)].map(() =>\n [...Array(N)].map(() => Array(N).fill(0))\n )\n dp[0][r][c] = 1\n for (let step = 1; step <= K; step++) {\n for (let i = 0; i < N; i++) {\n for (let j = 0; j < N; j++) {\n for (let move of moves) {\n let row = i + move[0],\n col = j + move[1]\n if (row >= 0 && row < N && col >= 0 && col < N)\n dp[step][i][j] += dp[step - 1][row][col] / 8\n }\n }\n }\n }\n let res = 0\n for (let i = 0; i < N; i++) {\n for (let j = 0; j < N; j++) {\n res += dp[K][i][j]\n }\n }\n return res\n}\n\n" + }, + { + "_id": "66f925ddfdfb8e1665720c22", + "questionid": 343, + "title": "Maximum Sum of 3 Non-Overlapping Subarrays", + "slug": "maximum-sum-of-3-non-overlapping-subarrays", + "description": "Given an integer array nums and an integer k, find three non-overlapping subarrays of length k with maximum sum and return them. Return the result as a list of indices representing the starting position of each interval (0-indexed). If there are multiple answers, return the lexicographically smallest one. ", + "category": [ + "Array", + "Dynamic Programming" + ], + "complexity": "Hard", + "successrate": 48.5, + "totalsubmissions": 128154, + "totalaccepted": 62143, + "likes": 1590, + "dislikes": 97, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,2,1,2,6,7,5,1], k = 2", + "expected_output": "[0,3,5]", + "explanation": "Subarrays [1, 2], [2, 6], [7, 5] correspond to the starting indices [0, 3, 5].\nWe could have also taken [2, 1], but an answer of [1, 3, 5] would be lexicographically larger." + }, + { + "example_num": 2, + "expected_input": "nums = [1,2,1,2,1,2,1,2,1], k = 2", + "expected_output": "[0,2,4]", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} nums\n * @param {number} k\n * @return {number[]}\n */\nconst maxSumOfThreeSubarrays = (nums, k) => {\n let n = nums.length,\n maxsum = 0\n let sum = new Array(n + 1).fill(0),\n posLeft = new Array(n).fill(0),\n posRight = new Array(n).fill(0),\n ans = new Array(3).fill(0)\n for (let i = 0; i < n; i++) sum[i + 1] = sum[i] + nums[i]\n for (let 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 posLeft[i] = posLeft[i - 1]\n }\n posRight[n - k] = n - k\n for (let i = n - k - 1, tot = sum[n] - sum[n - k]; i >= 0; i--) {\n if (sum[i + k] - sum[i] >= tot) {\n posRight[i] = i\n tot = sum[i + k] - sum[i]\n } else posRight[i] = posRight[i + 1]\n }\n for (let i = k; i <= n - 2 * k; i++) {\n let l = posLeft[i - 1],\n r = posRight[i + k]\n let 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[0] = l\n ans[1] = i\n ans[2] = r\n }\n }\n return ans\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720c27", + "questionid": 348, + "title": "Partition to K Equal Sum Subsets", + "slug": "partition-to-k-equal-sum-subsets", + "description": "Given an integer array nums and an integer k, return true if it is possible to divide this array into k non-empty subsets whose sums are all equal. ", + "category": [ + "Array", + "Dynamic Programming", + "Backtracking", + "Bit Manipulation", + "Memoization", + "Bitmask" + ], + "complexity": "Medium", + "successrate": 44.2, + "totalsubmissions": 437177, + "totalaccepted": 193131, + "likes": 4667, + "dislikes": 300, + "hints": "We can figure out what target each subset must sum to. Then, let's recursively search, where at each call to our function, we choose which of k subsets the next value will join.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [4,3,2,3,5,2,1], k = 4", + "expected_output": "true", + "explanation": "It is possible to divide it into 4 subsets (5), (1, 4), (2,3), (2,3) with equal sums." + }, + { + "example_num": 2, + "expected_input": "nums = [1,2,3,4], k = 3", + "expected_output": "false", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} nums\n * @param {number} k\n * @return {boolean}\n */\nconst canPartitionKSubsets = function(nums, k) {\n const sum = nums.reduce((ac, el) => ac + el, 0)\n return k !== 0 && sum % k === 0 && canPartition(0, nums, [], k, 0, sum / k)\n \n};\n\nfunction canPartition(start, nums, seen, k, sum, target) {\n if(k === 1) return true\n if (sum === target) {\n return canPartition(0, nums, seen, k - 1, 0, target)\n }\n for(let i = start; i < nums.length; i++) {\n if (!seen[i]) {\n seen[i] = true\n if(canPartition(i + 1, nums, seen, k, sum + nums[i], target)) {\n return true\n }\n seen[i] = false\n }\n }\n return false\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720c28", + "questionid": 349, + "title": "Falling Squares", + "slug": "falling-squares", + "description": "There are several squares being dropped onto the X-axis of a 2D plane. You are given a 2D integer array positions where positions[i] = [lefti, sideLengthi] represents the ith square with a side length of sideLengthi that is dropped with its left edge aligned with X-coordinate lefti. Each square is dropped one at a time from a height above any landed squares. It then falls downward (negative Y direction) until it either lands on the top side of another square or on the X-axis. A square brushing the left/right side of another square does not count as landing on it. Once it lands, it freezes in place and cannot be moved. After each square is dropped, you must record the height of the current tallest stack of squares. Return an integer array ans where ans[i] represents the height described above after dropping the ith square. ", + "category": [ + "Array", + "Segment Tree", + "Ordered Set" + ], + "complexity": "Hard", + "successrate": 43.8, + "totalsubmissions": 44288, + "totalaccepted": 19395, + "likes": 446, + "dislikes": 69, + "hints": "If positions = [[10, 20], [20, 30]], this is the same as [[1, 2], [2, 3]]. Currently, the values of positions are very large. Can you generalize this approach so as to make the values in positions manageable?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "positions = [[1,2],[2,3],[6,1]]", + "expected_output": "[2,5,5]", + "explanation": "After the first drop, the tallest stack is square 1 with a height of 2.\nAfter the second drop, the tallest stack is squares 1 and 2 with a height of 5.\nAfter the third drop, the tallest stack is still squares 1 and 2 with a height of 5.\nThus, we return an answer of [2, 5, 5]." + }, + { + "example_num": 2, + "expected_input": "positions = [[100,100],[200,100]]", + "expected_output": "[100,100]", + "explanation": "After the first drop, the tallest stack is square 1 with a height of 100.\nAfter the second drop, the tallest stack is either square 1 or square 2, both with heights of 100.\nThus, we return an answer of [100, 100].\nNote that square 2 only brushes the right side of square 1, which does not count as landing on it." + } + ], + "solution": "class Interval {\n constructor(s,e,h) {\n this.start = s\n this.end = e\n this.height = h\n }\n}\n/**\n * @param {number[][]} positions\n * @return {number[]}\n */\nconst fallingSquares = function(positions) {\n const n = positions.length\n const res = []\n const intervals = []\n let curMax = 0\n for(let i = 0; i < n; i++) {\n const [s, len] = positions[i]\n const ins = new Interval(s, s + len, len)\n curMax = Math.max(curMax, getHeight(intervals, ins))\n res.push(curMax)\n }\n \n return res\n};\n\nfunction getHeight(intervals, ins) {\n let preMax = 0\n for(const e of intervals) {\n if(ins.start >= e.end) continue\n if(ins.end <= e.start) continue\n preMax = Math.max(preMax, e.height)\n }\n \n ins.height += preMax\n intervals.push(ins)\n return ins.height\n}\n\n// another\n\n/**\n * @param {number[][]} positions\n * @return {number[]}\n */\nvar fallingSquares = function (positions) {\n let ranges = [{ left: 0, height: 0, right: 1e8 + 1e6 }], rtn = [], max = 0\n\n outer:\n for (let [left, length] of positions) {\n let curHeight = 0, startI = -1, right = left + length, newRanges = []\n for (let i = 0; i < ranges.length; i++) {\n let range = ranges[i]\n if (left < range.right && startI == -1) {\n startI = i\n // left part\n if (left != range.left) {\n newRanges.push({\n left: range.left,\n height: range.height,\n right: left\n })\n }\n }\n if (startI != -1) {\n curHeight = Math.max(curHeight, range.height)\n }\n if (right <= range.right) {\n // added part\n let newHeight = length + curHeight\n newRanges.push({\n left,\n height: newHeight,\n right,\n })\n // right part\n if (right != range.right) {\n newRanges.push({\n left: right,\n height: range.height,\n right: range.right,\n })\n }\n max = Math.max(newHeight, max)\n rtn.push(max)\n // replace\n ranges.splice(startI, i - startI + 1, ...newRanges)\n continue outer\n }\n }\n }\n return rtn\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720c29", + "questionid": 350, + "title": "Minimum ASCII Delete Sum for Two Strings", + "slug": "minimum-ascii-delete-sum-for-two-strings", + "description": "Given two strings s1 and\u00a0s2, return the lowest ASCII sum of deleted characters to make two strings equal. ", + "category": [ + "String", + "Dynamic Programming" + ], + "complexity": "Medium", + "successrate": 61.5, + "totalsubmissions": 99713, + "totalaccepted": 61334, + "likes": 1878, + "dislikes": 62, + "hints": "Let dp(i, j) be the answer for inputs s1[i:] and s2[j:].", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s1 = "sea", s2 = "eat"", + "expected_output": "231", + "explanation": "Deleting "s" from "sea" adds the ASCII value of "s" (115) to the sum.\nDeleting "t" from "eat" adds 116 to the sum.\nAt the end, both strings are equal, and 115 + 116 = 231 is the minimum sum possible to achieve this." + }, + { + "example_num": 2, + "expected_input": "s1 = "delete", s2 = "leet"", + "expected_output": "403", + "explanation": "Deleting "dee" from "delete" to turn the string into "let",\nadds 100[d] + 101[e] + 101[e] to the sum.\nDeleting "e" from "leet" adds 101[e] to the sum.\nAt the end, both strings are equal to "let", and the answer is 100+101+101+101 = 403.\nIf instead we turned both strings into "lee" or "eet", we would get answers of 433 or 417, which are higher." + } + ], + "solution": null + }, + { + "_id": "66f925ddfdfb8e1665720c2b", + "questionid": 352, + "title": "Maximum Length of Repeated Subarray", + "slug": "maximum-length-of-repeated-subarray", + "description": "Given two integer arrays nums1 and nums2, return the maximum length of a subarray that appears in both arrays. ", + "category": [ + "Array", + "Binary Search", + "Dynamic Programming", + "Sliding Window", + "Rolling Hash", + "Hash Function" + ], + "complexity": "Medium", + "successrate": 51.4, + "totalsubmissions": 326681, + "totalaccepted": 167799, + "likes": 3731, + "dislikes": 88, + "hints": "Use dynamic programming. dp[i][j] will be the answer for inputs A[i:], B[j:].", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums1 = [1,2,3,2,1], nums2 = [3,2,1,4,7]", + "expected_output": "3", + "explanation": "The repeated subarray with maximum length is [3,2,1]." + }, + { + "example_num": 2, + "expected_input": "nums1 = [0,0,0,0,0], nums2 = [0,0,0,0,0]", + "expected_output": "5", + "explanation": "The repeated subarray with maximum length is [0,0,0,0,0]." + } + ], + "solution": "/**\n * @param {number[]} A\n * @param {number[]} B\n * @return {number}\n */\nconst findLength = function(A, B) {\n let ans = 0;\n let memo = [];\n for (let i = 0; i < A.length + 1; i++) {\n memo[i] = Array(B.length + 1).fill(0);\n }\n for (let i = A.length - 1; i >= 0; --i) {\n for (let j = B.length - 1; j >= 0; --j) {\n if (A[i] == B[j]) {\n memo[i][j] = memo[i + 1][j + 1] + 1;\n if (ans < memo[i][j]) ans = memo[i][j];\n }\n }\n }\n return ans;\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720c2e", + "questionid": 355, + "title": "Find Pivot Index", + "slug": "find-pivot-index", + "description": "Given an array of integers nums, calculate the pivot index of this array. The pivot index is the index where the sum of all the numbers strictly to the left of the index is equal to the sum of all the numbers strictly to the index's right. If the index is on the left edge of the array, then the left sum is 0 because there are no elements to the left. This also applies to the right edge of the array. Return the leftmost pivot index. If no such index exists, return -1. ", + "category": [ + "Array", + "Prefix Sum" + ], + "complexity": "Easy", + "successrate": 51.5, + "totalsubmissions": 584791, + "totalaccepted": 300925, + "likes": 3064, + "dislikes": 364, + "hints": "We can precompute prefix sums P[i] = nums[0] + nums[1] + ... + nums[i-1].\r\nThen for each index, the left sum is P[i], and the right sum is P[P.length - 1] - P[i] - nums[i].", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,7,3,6,5,6]", + "expected_output": "3", + "explanation": "The pivot index is 3.\nLeft sum = nums[0] + nums[1] + nums[2] = 1 + 7 + 3 = 11\nRight sum = nums[4] + nums[5] = 5 + 6 = 11" + }, + { + "example_num": 2, + "expected_input": "nums = [1,2,3]", + "expected_output": "-1", + "explanation": "There is no index that satisfies the conditions in the problem statement." + }, + { + "example_num": 3, + "expected_input": "nums = [2,1,-1]", + "expected_output": "0", + "explanation": "The pivot index is 0.\nLeft sum = 0 (no elements to the left of index 0)\nRight sum = nums[1] + nums[2] = 1 + -1 = 0" + } + ], + "solution": "/**\n * @param {number[]} nums\n * @return {number}\n */\nconst pivotIndex = function(nums) {\n let sum = 0;\n let leftSum = 0;\n nums.forEach(num => {sum += num});\n \n for (let i = 0; i < nums.length; i++) {\n if (leftSum === sum - leftSum - nums[i]) return i;\n leftSum += nums[i];\n }\n return -1;\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720c36", + "questionid": 363, + "title": "To Lower Case", + "slug": "to-lower-case", + "description": "Given a string s, return the string after replacing every uppercase letter with the same lowercase letter. ", + "category": [ + "String" + ], + "complexity": "Easy", + "successrate": 81.3, + "totalsubmissions": 413860, + "totalaccepted": 336519, + "likes": 1053, + "dislikes": 2298, + "hints": "Most languages support lowercase conversion for a string data type. However, that is certainly not the purpose of the problem. Think about how the implementation of the lowercase function call can be done easily. Think ASCII! Think about the different capital letters and their ASCII codes and how that relates to their lowercase counterparts. Does there seem to be any pattern there? Any mathematical relationship that we can use?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "Hello"", + "expected_output": ""hello"", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "s = "here"", + "expected_output": ""here"", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "s = "LOVELY"", + "expected_output": ""lovely"", + "explanation": "" + } + ], + "solution": null + }, + { + "_id": "66f925ddfdfb8e1665720c37", + "questionid": 364, + "title": "Network Delay Time", + "slug": "network-delay-time", + "description": "You are given a network of n nodes, labeled from 1 to n. You are also given times, a list of travel times as directed edges times[i] = (ui, vi, wi), where ui is the source node, vi is the target node, and wi is the time it takes for a signal to travel from source to target. We will send a signal from a given node k. Return the time it takes for all the n nodes to receive the signal. If it is impossible for all the n nodes to receive the signal, return -1. ", + "category": [ + "Depth-First Search", + "Breadth-First Search", + "Graph", + "Heap (Priority Queue)", + "Shortest Path" + ], + "complexity": "Medium", + "successrate": 48.4, + "totalsubmissions": 479952, + "totalaccepted": 232392, + "likes": 3920, + "dislikes": 275, + "hints": "We visit each node at some time, and if that time is better than the fastest time we've reached this node, we travel along outgoing edges in sorted order. Alternatively, we could use Dijkstra's algorithm.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "times = [[2,1,1],[2,3,1],[3,4,1]], n = 4, k = 2", + "expected_output": "2", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "times = [[1,2,1]], n = 2, k = 1", + "expected_output": "1", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "times = [[1,2,1]], n = 2, k = 2", + "expected_output": "-1", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[][]} times\n * @param {number} n\n * @param {number} k\n * @return {number}\n */\nconst networkDelayTime = function(times, n, k) {\n const g = Array.from({ length: n + 1 }, () => Array(n + 1).fill(Infinity))\n const graph = {} \n for(const [u,v,w] of times) {\n if(graph[u] == null) graph[u] = {}\n graph[u][v] = w\n g[u][v] = w\n }\n for(let k = 1; k <= n; k++) {\n for(let i = 1; i <= n; i++) {\n for(let j = 1; j <= n; j++) {\n g[i][j] = Math.min(g[i][j], g[i][k] + g[k][j])\n }\n }\n }\n\n let q = [k]\n const visited = new Set()\n const dis = Array(n + 1).fill(Infinity)\n let res = 0\n dis[k] = 0\n // console.log(g)\n while(q.length) {\n const size = q.length, tmp = []\n for(let i = 0; i < size; i++) {\n const e = q[i]\n visited.add(e)\n for(let nxt of (Object.keys(graph[e] || {}) || [])) {\n nxt = +nxt\n if(!visited.has(nxt)) {\n tmp.push(nxt)\n }\n if(g[e][nxt]) dis[nxt] = Math.min(dis[nxt], dis[e] + g[e][nxt])\n }\n }\n\n q = tmp\n }\n // console.log(dis)\n for(let i = 1; i <= n; i++) {\n if(i === k) continue\n res = Math.max(res, dis[i])\n }\n\n return visited.size === n ? res : -1\n};\n\n// another\n\n/**\n * @param {number[][]} times\n * @param {number} n\n * @param {number} k\n * @return {number}\n */\nconst networkDelayTime = function(times, n, k) {\n const graph = {}\n for(const [u, v, w] of times) {\n if(graph[u] == null) graph[u] = []\n graph[u][v] = w\n }\n const visited = new Array(n + 1).fill(false)\n const pq = new PQ((a, b) => a[0] < b[0])\n pq.push([0, k])\n let res = 0\n while(!pq.isEmpty()) {\n const [dist, cur] = pq.pop()\n if(visited[cur]) continue\n visited[cur] = true\n n--\n res = dist\n if(graph[cur]) {\n for(const nxt of Object.keys(graph[cur])) {\n pq.push([res + graph[cur][nxt], nxt])\n }\n }\n }\n return n === 0 ? res : -1\n};\n\nclass PQ {\n constructor(comparator = (a, b) => a > b) {\n this.heap = []\n this.top = 0\n this.comparator = comparator\n }\n size() {\n return this.heap.length\n }\n isEmpty() {\n return this.size() === 0\n }\n peek() {\n return this.heap[this.top]\n }\n push(...values) {\n values.forEach((value) => {\n this.heap.push(value)\n this.siftUp()\n })\n return this.size()\n }\n pop() {\n const poppedValue = this.peek()\n const bottom = this.size() - 1\n if (bottom > this.top) {\n this.swap(this.top, bottom)\n }\n this.heap.pop()\n this.siftDown()\n return poppedValue\n }\n replace(value) {\n const replacedValue = this.peek()\n this.heap[this.top] = value\n this.siftDown()\n return replacedValue\n }\n\n parent = (i) => ((i + 1) >>> 1) - 1\n left = (i) => (i << 1) + 1\n right = (i) => (i + 1) << 1\n greater = (i, j) => this.comparator(this.heap[i], this.heap[j])\n swap = (i, j) => ([this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]])\n siftUp = () => {\n let node = this.size() - 1\n while (node > this.top && this.greater(node, this.parent(node))) {\n this.swap(node, this.parent(node))\n node = this.parent(node)\n }\n }\n siftDown = () => {\n let node = this.top\n while (\n (this.left(node) < this.size() && this.greater(this.left(node), node)) ||\n (this.right(node) < this.size() && this.greater(this.right(node), node))\n ) {\n let maxChild =\n this.right(node) < this.size() &&\n this.greater(this.right(node), this.left(node))\n ? this.right(node)\n : this.left(node)\n this.swap(node, maxChild)\n node = maxChild\n }\n }\n}\n\n// another\n\n/**\n * @param {number[][]} times\n * @param {number} N\n * @param {number} K\n * @return {number}\n */\nconst networkDelayTime = function (times, N, K) {\n const mins = new Array(N).fill(Infinity)\n mins[K - 1] = 0\n for (let i = 0; i < N; i++) {\n for (let [u, v, t] of times) {\n if (mins[u - 1] === Infinity) continue\n if (mins[v - 1] > mins[u - 1] + t) {\n mins[v - 1] = mins[u - 1] + t\n }\n }\n }\n return mins.includes(Infinity) ? -1 : Math.max(...mins)\n}\n\n// another\n\n/**\n * @param {number[][]} times\n * @param {number} N\n * @param {number} K\n * @return {number}\n */\nconst networkDelayTime = function(times, N, K) {\n const distances = new Array(N).fill(Infinity);\n distances[K - 1] = 0;\n \n for(let i = 0 ; i < N -1 ; i++){\n let counter = 0;\n for(let j = 0 ; j < times.length ; j++){\n const source = times[j][0];\n const target = times[j][1];\n const weight = times[j][2];\n if(distances[source - 1] + weight < distances[target - 1]){\n distances[target - 1] = distances[source - 1] + weight;\n counter++\n }\n }\n if(counter === 0) break\n }\n \n const res = Math.max(...distances);\n return res === Infinity ? -1 : res;\n};\n\n// another\n\n/**\n * @param {number[][]} times\n * @param {number} N\n * @param {number} K\n * @return {number}\n */\nconst networkDelayTime = function (times, N, K) {\n const hash = {}\n for(const [u, v, t] of times) {\n if(hash[u] == null) hash[u] = {}\n hash[u][v] = t\n }\n const pq = new PriorityQueue((a, b) => a[0] < b[0])\n pq.push([0, K])\n const visited = Array.from(N + 1)\n let res = 0\n while(!pq.isEmpty()) {\n const [dist, cur] = pq.pop()\n if(visited[cur]) continue\n visited[cur] = true\n res = dist\n N--\n if(hash[cur]) {\n for(let next of Object.keys(hash[cur])) {\n pq.push([dist + hash[cur][next], next])\n }\n }\n }\n return N === 0 ? res : -1\n}\n\nclass PriorityQueue {\n constructor(comparator = (a, b) => a > b) {\n this.heap = []\n this.top = 0\n this.comparator = comparator\n }\n size() {\n return this.heap.length\n }\n isEmpty() {\n return this.size() === 0\n }\n peek() {\n return this.heap[this.top]\n }\n push(...values) {\n values.forEach((value) => {\n this.heap.push(value)\n this.siftUp()\n })\n return this.size()\n }\n pop() {\n const poppedValue = this.peek()\n const bottom = this.size() - 1\n if (bottom > this.top) {\n this.swap(this.top, bottom)\n }\n this.heap.pop()\n this.siftDown()\n return poppedValue\n }\n replace(value) {\n const replacedValue = this.peek()\n this.heap[this.top] = value\n this.siftDown()\n return replacedValue\n }\n\n parent = (i) => ((i + 1) >>> 1) - 1\n left = (i) => (i << 1) + 1\n right = (i) => (i + 1) << 1\n greater = (i, j) => this.comparator(this.heap[i], this.heap[j])\n swap = (i, j) => ([this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]])\n siftUp = () => {\n let node = this.size() - 1\n while (node > this.top && this.greater(node, this.parent(node))) {\n this.swap(node, this.parent(node))\n node = this.parent(node)\n }\n }\n siftDown = () => {\n let node = this.top\n while (\n (this.left(node) < this.size() && this.greater(this.left(node), node)) ||\n (this.right(node) < this.size() && this.greater(this.right(node), node))\n ) {\n let maxChild =\n this.right(node) < this.size() &&\n this.greater(this.right(node), this.left(node))\n ? this.right(node)\n : this.left(node)\n this.swap(node, maxChild)\n node = maxChild\n }\n }\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720c3a", + "questionid": 367, + "title": "Largest Number At Least Twice of Others", + "slug": "largest-number-at-least-twice-of-others", + "description": "You are given an integer array nums where the largest integer is unique. Determine whether the largest element in the array is at least twice as much as every other number in the array. If it is, return the index of the largest element, or return -1 otherwise. ", + "category": [ + "Array", + "Sorting" + ], + "complexity": "Easy", + "successrate": 45.2, + "totalsubmissions": 342731, + "totalaccepted": 154812, + "likes": 665, + "dislikes": 752, + "hints": "Scan through the array to find the unique largest element `m`, keeping track of it's index `maxIndex`.\r\n\r\nScan through the array again. If we find some `x != m` with `m < 2*x`, we should return `-1`.\r\n\r\nOtherwise, we should return `maxIndex`.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [3,6,1,0]", + "expected_output": "1", + "explanation": "6 is the largest integer.\nFor every other number in the array x, 6 is at least twice as big as x.\nThe index of value 6 is 1, so we return 1." + }, + { + "example_num": 2, + "expected_input": "nums = [1,2,3,4]", + "expected_output": "-1", + "explanation": "4 is less than twice the value of 3, so we return -1." + } + ], + "solution": "/**\n * @param {number[]} nums\n * @return {number}\n */\nconst dominantIndex = function(nums) {\n let max = -Infinity\n let idx = -1\n for(let i = 0, len = nums.length; i < len; i++) {\n if(nums[i] > max) {\n max = nums[i]\n idx = i\n }\n }\n for(let i = 0, len = nums.length; i < len; i++) {\n if(nums[i] !== max && max < nums[i] * 2) return -1\n }\n return idx\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720c3c", + "questionid": 369, + "title": "Contain Virus", + "slug": "contain-virus", + "description": "A virus is spreading rapidly, and your task is to quarantine the infected area by installing walls. The world is modeled as an m x n binary grid isInfected, where isInfected[i][j] == 0 represents uninfected cells, and isInfected[i][j] == 1 represents cells contaminated with the virus. A wall (and only one wall) can be installed between any two 4-directionally adjacent cells, on the shared boundary. Every night, the virus spreads to all neighboring cells in all four directions unless blocked by a wall. Resources are limited. Each day, you can install walls around only one region (i.e., the affected area (continuous block of infected cells) that threatens the most uninfected cells the following night). There will never be a tie. Return the number of walls used to quarantine all the infected regions. If the world will become fully infected, return the number of walls used. ", + "category": [ + "Array", + "Depth-First Search", + "Breadth-First Search", + "Matrix", + "Simulation" + ], + "complexity": "Hard", + "successrate": 50, + "totalsubmissions": 16339, + "totalaccepted": 8173, + "likes": 229, + "dislikes": 367, + "hints": "The implementation is long - we want to perfrom the following steps:\r\n\r\n* Find all viral regions (connected components), additionally for each region keeping track of the frontier (neighboring uncontaminated cells), and the perimeter of the region.\r\n\r\n* Disinfect the most viral region, adding it's perimeter to the answer.\r\n\r\n* Spread the virus in the remaining regions outward by 1 square.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "isInfected = [[0,1,0,0,0,0,0,1],[0,1,0,0,0,0,0,1],[0,0,0,0,0,0,0,1],[0,0,0,0,0,0,0,0]]", + "expected_output": "10", + "explanation": "There are 2 contaminated regions.\nOn the first day, add 5 walls to quarantine the viral region on the left. The board after the virus spreads is:\n\"\"\nOn the second day, add 5 walls to quarantine the viral region on the right. The virus is fully contained.\n\"\"" + }, + { + "example_num": 2, + "expected_input": "isInfected = [[1,1,1],[1,0,1],[1,1,1]]", + "expected_output": "4", + "explanation": "Even though there is only one cell saved, there are 4 walls built.\nNotice that walls are only built on the shared boundary of two different cells." + }, + { + "example_num": 3, + "expected_input": "isInfected = [[1,1,1,0,0,0,0,0,0],[1,0,1,0,1,1,1,1,1],[1,1,1,0,0,0,0,0,0]]", + "expected_output": "13", + "explanation": "The region on the left only builds two new walls." + } + ], + "solution": "/**\n * @param {number[][]} grid\n * @return {number}\n */\nconst containVirus = function (grid) {\n let ans = 0\n while (true) {\n const walls = model(grid)\n if (walls === 0) break\n ans += walls\n }\n return ans\n function model(grid) {\n const m = grid.length,\n n = grid[0].length\n const virus = [],\n toInfect = []\n const visited = Array.from({ length: m }, () => Array(n).fill(0))\n const walls = []\n for (let i = 0; i < m; i++) {\n for (let j = 0; j < n; j++) {\n if (grid[i][j] === 1 && visited[i][j] === 0) {\n virus.push(new Set())\n toInfect.push(new Set())\n walls.push([0])\n dfs(\n grid,\n visited,\n virus[virus.length - 1],\n toInfect[toInfect.length - 1],\n walls[walls.length - 1],\n i,\n j\n )\n }\n }\n }\n let maxArea = 0,\n idx = -1\n for (let i = 0; i < toInfect.length; i++) {\n if (toInfect[i].size > maxArea) {\n maxArea = toInfect[i].size\n idx = i\n }\n }\n if (idx === -1) return 0\n for (let i = 0; i < toInfect.length; i++) {\n if (i !== idx) {\n for (let key of toInfect[i]) grid[(key / n) >> 0][key % n] = 1\n } else {\n for (let key of virus[i]) grid[(key / n) >> 0][key % n] = -1\n }\n }\n return walls[idx][0]\n }\n function dfs(grid, visited, virus, toInfect, wall, row, col) {\n const m = grid.length,\n n = grid[0].length\n if (row < 0 || row >= m || col < 0 || col >= n || visited[row][col] === 1)\n return\n if (grid[row][col] === 1) {\n visited[row][col] = 1\n virus.add(row * n + col)\n const dir = [0, -1, 0, 1, 0]\n for (let i = 0; i < 4; i++)\n dfs(\n grid,\n visited,\n virus,\n toInfect,\n wall,\n row + dir[i],\n col + dir[i + 1]\n )\n } else if (grid[row][col] === 0) {\n wall[0]++\n toInfect.add(row * n + col)\n }\n }\n}\n\n// another\n\n/**\n * @param {number[][]} grid\n * @return {number}\n */\nconst containVirus = (grid) => {\n const m = grid.length;\n const n = grid[0].length;\n let ans = 0;\n while (true) {\n // list of regions can spread virus\n const regions = [];\n const visited = Array.from({ length: m }, () => Array(n).fill(false));\n for (let i = 0; i < m; i++) {\n for (let j = 0; j < n; j++) {\n if (grid[i][j] === 1 && !visited[i][j]) {\n const region = new Region();\n dfs(grid, i, j, region, visited);\n if (region.uninfected.size > 0) regions.push(region);\n }\n }\n }\n\n if (regions.length === 0) break;\n regions.sort((a, b) => a.uninfected.size - b.uninfected.size);\n let idx = -1, wall = -Infinity\n for(let i = 0, len = regions.length; i < len; i++) {\n if(regions[i].uninfected.size > wall) {\n wall = regions[i].uninfected.size\n idx = i\n }\n }\n const mostToBeInfected = regions[idx]\n ans += mostToBeInfected.wallNeeded\n regions.splice(idx, 1)\n for (let x of mostToBeInfected.infected) {\n let i = (x / n) >> 0,\n j = x % n;\n grid[i][j] = 2;\n }\n\n for (let region of regions) {\n for (let x of region.uninfected) {\n let i = (x / n) >> 0,\n j = x % n;\n grid[i][j] = 1;\n }\n }\n }\n\n return ans;\n function dfs(grid, i, j, region, visited) {\n if (i < 0 || i == m || j < 0 || j == n) return;\n \n if (grid[i][j] === 1 && !visited[i][j]) {\n visited[i][j] = true;\n region.infected.add(i * n + j);\n dfs(grid, i - 1, j, region, visited);\n dfs(grid, i + 1, j, region, visited);\n dfs(grid, i, j - 1, region, visited);\n dfs(grid, i, j + 1, region, visited);\n } else if (grid[i][j] === 0) {\n region.wallNeeded += 1;\n region.uninfected.add(i * n + j);\n }\n }\n};\nclass Region {\n constructor() {\n this.wallNeeded = 0;\n this.infected = new Set();\n this.uninfected = new Set();\n }\n}\n\n// another\n\n/**\n * @param {number[][]} grid\n * @return {number}\n */\nconst containVirus = function (grid) {\n const infected = 1\n const healthy = 0\n const quarantined = 2\n const directions = [\n [1, 0],\n [-1, 0],\n [0, 1],\n [0, -1],\n ]\n const mod = 100\n const encode = (row, col) => row + col * mod\n const decode = (num) => [num % mod, Math.floor(num / mod)]\n const disjointSet = {}\n for (let row = 0; row < grid.length; row++) {\n for (let col = 0; col < grid[row].length; col++) {\n const coord = encode(row, col)\n disjointSet[coord] = coord\n if (grid[row][col] === 0) continue\n if (grid[row][col - 1] === 1) union(coord, encode(row, col - 1))\n if (row > 0 && grid[row - 1][col] === 1)\n union(coord, encode(row - 1, col))\n }\n }\n let numWalls = 0\n while (true) {\n const impact = quarantineAndContaminate()\n if (impact === 0) return numWalls\n numWalls += impact\n spreadVirus()\n }\n function find(coord) {\n return (disjointSet[coord] =\n disjointSet[coord] === coord ? coord : find(disjointSet[coord]))\n }\n function union(coord, toCoord) {\n return (disjointSet[find(coord)] = find(toCoord))\n }\n function quarantineAndContaminate() {\n const impact = new Map()\n for (let row = 0; row < grid.length; row++) {\n for (let col = 0; col < grid[row].length; col++) {\n if (grid[row][col] !== infected) continue\n const root = find(encode(row, col))\n if (!impact.has(root)) impact.set(root, new Set())\n for (let [down, right] of directions) {\n if (grid[row + down] && grid[row + down][col + right] === healthy) {\n impact.get(root).add(encode(row + down, col + right))\n }\n }\n }\n }\n let impactedCoords = new Set()\n let root = null\n for (let [node, coords] of impact) {\n if (impactedCoords.size < coords.size) {\n impactedCoords = coords\n root = node\n }\n }\n if (impactedCoords.size === 0) return 0\n return quarantine(...decode(root))\n }\n function quarantine(row, col) {\n if (row < 0 || row >= grid.length || col < 0 || col >= grid[0].length)\n return 0\n if (grid[row][col] === 2) return 0\n if (grid[row][col] === 0) return 1\n let totalWalls = 0\n grid[row][col] = 2\n for (let [down, right] of directions) {\n totalWalls += quarantine(row + down, col + right)\n }\n return totalWalls\n }\n function spreadVirus() {\n const infectedCoords = new Set()\n for (let row = 0; row < grid.length; row++) {\n for (let col = 0; col < grid[row].length; col++) {\n if (grid[row][col] !== healthy) continue\n for (let [down, right] of directions) {\n if (grid[row + down] && grid[row + down][col + right] === infected) {\n infectedCoords.add(encode(row, col))\n }\n }\n }\n }\n for (let coord of infectedCoords) {\n const [row, col] = decode(coord)\n grid[row][col] = 1\n for (let [down, right] of directions) {\n if (grid[row + down] && grid[row + down][col + right] === 1) {\n union(coord, encode(row + down, col + right))\n }\n }\n }\n }\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720c45", + "questionid": 378, + "title": "Couples Holding Hands", + "slug": "couples-holding-hands", + "description": "There are n couples sitting in 2n seats arranged in a row and want to hold hands. The people and seats are represented by an integer array row where row[i] is the ID of the person sitting in the ith seat. The couples are numbered in order, the first couple being (0, 1), the second couple being (2, 3), and so on with the last couple being (2n - 2, 2n - 1). Return the minimum number of swaps so that every couple is sitting side by side. A swap consists of choosing any two people, then they stand up and switch seats. ", + "category": [ + "Greedy", + "Depth-First Search", + "Breadth-First Search", + "Union Find", + "Graph" + ], + "complexity": "Hard", + "successrate": 56.5, + "totalsubmissions": 76653, + "totalaccepted": 43314, + "likes": 1580, + "dislikes": 85, + "hints": "Say there are N two-seat couches. For each couple, draw an edge from the couch of one partner to the couch of the other partner.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "row = [0,2,1,3]", + "expected_output": "1", + "explanation": "We only need to swap the second (row[1]) and third (row[2]) person." + }, + { + "example_num": 2, + "expected_input": "row = [3,2,0,1]", + "expected_output": "0", + "explanation": "All couples are already seated side by side." + } + ], + "solution": "/**\n * @param {number[]} row\n * @return {number}\n */\nconst minSwapsCouples = function (row) {\n let res = 0,\n N = row.length\n const ptn = new Array(N).fill(0)\n const pos = new Array(N).fill(0)\n for (let i = 0; i < N; i++) {\n ptn[i] = i % 2 === 0 ? i + 1 : i - 1\n pos[row[i]] = i\n }\n for (let i = 0; i < N; i++) {\n for (let j = ptn[pos[ptn[row[i]]]]; i !== j; j = ptn[pos[ptn[row[i]]]]) {\n swap(row, i, j)\n swap(pos, row[i], row[j])\n res++\n }\n }\n return res\n}\n\nfunction swap(arr, i, j) {\n ;[arr[i], arr[j]] = [arr[j], arr[i]]\n}\n\n// another\n\n/**\n * @param {number[]} row\n * @return {number}\n */\nconst minSwapsCouples = function (row) {\n const parents = Array.from({ length: row.length / 2 }, (_, i) => i)\n const positions = new Map()\n for (let i = 0; i < row.length / 2; i++) {\n const left = Math.floor(row[i * 2] / 2)\n const right = Math.floor(row[i * 2 + 1] / 2)\n if (positions.has(left)) {\n union(i, positions.get(left))\n } else {\n positions.set(left, i)\n }\n if (positions.has(right)) {\n union(i, positions.get(right))\n } else {\n positions.set(right, i)\n }\n }\n\n const uniqueRoots = new Set()\n for (const parent of parents) {\n uniqueRoots.add(find(parent))\n }\n return parents.length - uniqueRoots.size\n\n function union(a, b) {\n const aRoot = find(a)\n const bRoot = find(b)\n parents[aRoot] = bRoot\n }\n function root(x) {\n while (x !== parents[x]) {\n parents[x] = parents[parents[x]]\n x = parents[x]\n }\n return x\n }\n function find(node) {\n return root(node)\n }\n}\n\n// another\n\n/**\n * @param {number[]} row\n * @return {number}\n */\nconst minSwapsCouples = function (row) {\n let res = 0\n const n = row.length\n const ptn = Array(n).fill(0), pos = Array(n).fill(0)\n \n for(let i = 0; i < n; i++) {\n ptn[i] = (i % 2 === 0 ? i + 1 : i - 1)\n pos[row[i]] = i\n }\n\n for (let i = 0; i < n ;i++) {\n for (let j = ptn[pos[ptn[row[i]]]]; i != j; j = ptn[pos[ptn[row[i]]]]) {\n\t\t\tswap(row, i, j);\n\t\t\tswap(pos, row[i], row[j]);\n\t\t\tres++;\n\t\t}\n }\n \n return res\n\n function swap(arr, i, j) {\n const val = arr[i]\n arr[i] = arr[j]\n arr[j] = val\n }\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720c47", + "questionid": 380, + "title": "N-ary Tree Preorder Traversal", + "slug": "n-ary-tree-preorder-traversal", + "description": "Given the root of an n-ary tree, return the preorder traversal of its nodes' values. Nary-Tree input serialization is represented in their level order traversal. Each group of children is separated by the null value (See examples) ", + "category": [ + "Stack", + "Tree", + "Depth-First Search" + ], + "complexity": "Easy", + "successrate": 76.1, + "totalsubmissions": 295173, + "totalaccepted": 224480, + "likes": 1708, + "dislikes": 80, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [1,null,3,2,4,null,5,6]", + "expected_output": "[1,3,5,6,2,4]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]", + "expected_output": "[1,2,3,6,7,11,14,4,8,12,5,9,13,10]", + "explanation": "" + } + ], + "solution": "/**\n * // Definition for a Node.\n * function Node(val,children) {\n * this.val = val;\n * this.children = children;\n * };\n */\n/**\n * @param {Node} root\n * @return {number[]}\n */\nconst preorder = function(root) {\n const arr = []\n traverse(root, arr)\n return arr\n};\n\nfunction traverse(node, arr) {\n if(node === null) return\n arr.push(node.val)\n for(let i = 0; i < node.children.length; i++) {\n traverse(node.children[i], arr)\n }\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720c0e", + "questionid": 323, + "title": "Set Mismatch", + "slug": "set-mismatch", + "description": "You have a set of integers s, which originally contains all the numbers from 1 to n. Unfortunately, due to some error, one of the numbers in s got duplicated to another number in the set, which results in repetition of one number and loss of another number. You are given an integer array nums representing the data status of this set after the error. Find the number that occurs twice and the number that is missing and return them in the form of an array. ", + "category": [ + "Array", + "Hash Table", + "Bit Manipulation", + "Sorting" + ], + "complexity": "Easy", + "successrate": 41.3, + "totalsubmissions": 400479, + "totalaccepted": 165255, + "likes": 1865, + "dislikes": 554, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,2,2,4]", + "expected_output": "[2,3]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "nums = [1,1]", + "expected_output": "[1,2]", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} nums\n * @return {number[]}\n */\nconst findErrorNums = function(nums) {\n if(nums == null || nums.length === 0) return null\n const res = []\n const hash = {}\n for(let el of nums) {\n if(hash.hasOwnProperty(el)){\n res[0] = el\n } else hash[el] = 0\n hash[el]++\n }\n for(let i = 1, len = nums.length; i <= len; i++) {\n if(!hash.hasOwnProperty(i)) {\n res[1] = i\n break\n }\n }\n return res\n};\n\n// another\n\n/**\n * @param {number[]} nums\n * @return {number[]}\n */\nconst findErrorNums = function(nums) {\n const res = [];\n for (const i of nums) {\n if (nums[Math.abs(i) - 1] < 0) res[0] = Math.abs(i);\n\t else nums[Math.abs(i) - 1] *= -1;\n }\n for (let i = 0; i < nums.length; i++) {\n if (nums[i] > 0) res[1] = i + 1;\n }\n return res; \n};\n\n" + }, + { + "_id": "66f925ddfdfb8e1665720c0d", + "questionid": 322, + "title": "Maximum Average Subarray I", + "slug": "maximum-average-subarray-i", + "description": "You are given an integer array nums consisting of n elements, and an integer k. Find a contiguous subarray whose length is equal to k that has the maximum average value and return this value. Any answer with a calculation error less than 10-5 will be accepted. ", + "category": [ + "Array", + "Sliding Window" + ], + "complexity": "Easy", + "successrate": 43.5, + "totalsubmissions": 322079, + "totalaccepted": 140016, + "likes": 1565, + "dislikes": 156, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,12,-5,-6,50,3], k = 4", + "expected_output": "12.75000", + "explanation": "Maximum average is (12 - 5 - 6 + 50) / 4 = 51 / 4 = 12.75" + }, + { + "example_num": 2, + "expected_input": "nums = [5], k = 1", + "expected_output": "5.00000", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} nums\n * @param {number} k\n * @return {number}\n */\nconst findMaxAverage = function(nums, k) {\n let max = 0;\n let temp = 0;\n for(let i = 0; i < k; i++) {\n max += nums[i];\n }\n temp = max;\n for(let i = k; i < nums.length ; i++) {\n temp = temp - nums[i - k] + nums[i];\n max = Math.max(max, temp);\n }\n \n return max/k;\n };\n" + }, + { + "_id": "66f925ddfdfb8e1665720c16", + "questionid": 331, + "title": "Non-decreasing Array", + "slug": "non-decreasing-array", + "description": "Given an array nums with n integers, your task is to check if it could become non-decreasing by modifying at most one element. We define an array is non-decreasing if nums[i] <= nums[i + 1] holds for every i (0-based) such that (0 <= i <= n - 2). ", + "category": [ + "Array" + ], + "complexity": "Medium", + "successrate": 21.5, + "totalsubmissions": 795825, + "totalaccepted": 171208, + "likes": 3571, + "dislikes": 664, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [4,2,3]", + "expected_output": "true", + "explanation": "You could modify the first 4 to 1 to get a non-decreasing array." + }, + { + "example_num": 2, + "expected_input": "nums = [4,2,1]", + "expected_output": "false", + "explanation": "You cannot get a non-decreasing array by modifying at most one element." + } + ], + "solution": "/**\n * @param {number[]} nums\n * @return {boolean}\n */\nconst checkPossibility = function(nums) {\n let count = 0;\n let idx;\n if (nums.length === 1) return true;\n for (let i = 1; i < nums.length; i++) {\n if (nums[i - 1] > nums[i]) {\n count++;\n idx = i;\n }\n }\n if (count > 1) return false;\n if (idx === nums.length - 1 || idx === 1) return true;\n return (\n Math.max(...nums.slice(0, idx - 1)) <= Math.min(...nums.slice(idx)) ||\n Math.max(...nums.slice(0, idx)) <= Math.min(...nums.slice(idx + 1))\n );\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720c19", + "questionid": 334, + "title": "Maximum Swap", + "slug": "maximum-swap", + "description": "You are given an integer num. You can swap two digits at most once to get the maximum valued number. Return the maximum valued number you can get. ", + "category": [ + "Math", + "Greedy" + ], + "complexity": "Medium", + "successrate": 47.5, + "totalsubmissions": 346736, + "totalaccepted": 164735, + "likes": 2446, + "dislikes": 142, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "num = 2736", + "expected_output": "7236", + "explanation": "Swap the number 2 and the number 7." + }, + { + "example_num": 2, + "expected_input": "num = 9973", + "expected_output": "9973", + "explanation": "No swap." + } + ], + "solution": "/**\n * @param {number} num\n * @return {number}\n */\nconst maximumSwap = function(num) {\n const arr = ('' + num).split('')\n for(let i = 0; i < arr.length - 1; i++) {\n let cur = +arr[i]\n let nextMax = Math.max(...arr.slice(i+1).map(el => +el))\n if (nextMax > cur) {\n let idx = arr.lastIndexOf(''+nextMax)\n arr[i] = nextMax\n arr[idx] = cur\n break\n }\n }\n return +(arr.join(''))\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720c1c", + "questionid": 337, + "title": "Longest Continuous Increasing Subsequence", + "slug": "longest-continuous-increasing-subsequence", + "description": "Given an unsorted array of integers nums, return the length of the longest continuous increasing subsequence (i.e. subarray). The subsequence must be strictly increasing. A continuous increasing subsequence is defined by two indices l and r (l < r) such that it is [nums[l], nums[l + 1], ..., nums[r - 1], nums[r]] and for each l <= i < r, nums[i] < nums[i + 1]. ", + "category": [ + "Array" + ], + "complexity": "Easy", + "successrate": 48.3, + "totalsubmissions": 394056, + "totalaccepted": 190453, + "likes": 1660, + "dislikes": 164, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,3,5,4,7]", + "expected_output": "3", + "explanation": "The longest continuous increasing subsequence is [1,3,5] with length 3.\nEven though [1,3,5,7] is an increasing subsequence, it is not continuous as elements 5 and 7 are separated by element\n4." + }, + { + "example_num": 2, + "expected_input": "nums = [2,2,2,2,2]", + "expected_output": "1", + "explanation": "The longest continuous increasing subsequence is [2] with length 1. Note that it must be strictly\nincreasing." + } + ], + "solution": "/**\n * @param {number[]} nums\n * @return {number}\n */\nconst findLengthOfLCIS = function(nums) {\n if (nums.length == 1) {\n return 1;\n }\n let ans = 0,\n anchor = 0;\n for (let i = 1; i < nums.length; i++) {\n if (nums[i - 1] >= nums[i]) {\n anchor = i;\n }\n ans = Math.max(ans, i - anchor + 1);\n }\n return ans;\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720c1e", + "questionid": 339, + "title": "Redundant Connection", + "slug": "redundant-connection", + "description": "In this problem, a tree is an undirected graph that is connected and has no cycles. You are given a graph that started as a tree with n nodes labeled from 1 to n, with one additional edge added. The added edge has two different vertices chosen from 1 to n, and was not an edge that already existed. The graph is represented as an array edges of length n where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the graph. Return an edge that can be removed so that the resulting graph is a tree of n nodes. If there are multiple answers, return the answer that occurs last in the input. ", + "category": [ + "Depth-First Search", + "Breadth-First Search", + "Union Find", + "Graph" + ], + "complexity": "Medium", + "successrate": 61.1, + "totalsubmissions": 317920, + "totalaccepted": 194287, + "likes": 3572, + "dislikes": 286, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "edges = [[1,2],[1,3],[2,3]]", + "expected_output": "[2,3]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "edges = [[1,2],[2,3],[3,4],[1,4],[1,5]]", + "expected_output": "[1,4]", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[][]} edges\n * @return {number[]}\n */\nconst findRedundantConnection = function (edges) {\n const uf = {}\n for (let edge of edges) {\n let u = edge[0]\n let v = edge[1]\n if (find(u) === find(v)) {\n return edge\n } else {\n union(u, v)\n }\n }\n function union(a, b) {\n uf[find(a)] = uf[find(b)]\n }\n function find(x) {\n if (!uf[x]) uf[x] = x\n if (uf[x] === x) return x\n return find(uf[x])\n }\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720c23", + "questionid": 344, + "title": "Top K Frequent Words", + "slug": "top-k-frequent-words", + "description": "Given an array of strings words and an integer k, return the k most frequent strings. Return the answer sorted by the frequency from highest to lowest. Sort the words with the same frequency by their lexicographical order. ", + "category": [ + "Hash Table", + "String", + "Trie", + "Sorting", + "Heap (Priority Queue)", + "Bucket Sort", + "Counting" + ], + "complexity": "Medium", + "successrate": 54.3, + "totalsubmissions": 682591, + "totalaccepted": 370829, + "likes": 4346, + "dislikes": 245, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "words = ["i","love","leetcode","i","love","coding"], k = 2", + "expected_output": "["i","love"]", + "explanation": ""i" and "love" are the two most frequent words.\nNote that "i" comes before "love" due to a lower alphabetical order." + }, + { + "example_num": 2, + "expected_input": "words = ["the","day","is","sunny","the","the","the","sunny","is","is"], k = 4", + "expected_output": "["the","is","sunny","day"]", + "explanation": ""the", "is", "sunny" and "day" are the four most frequent words, with the number of occurrence being 4, 3, 2 and 1 respectively." + } + ], + "solution": "/**\n * @param {string[]} words\n * @param {number} k\n * @return {string[]}\n */\nconst topKFrequent = function(words, k) {\n const hash = {}\n words.forEach(el => {\n if(hash.hasOwnProperty(el)) {\n hash[el]++\n } else {\n hash[el] = 1\n }\n })\n const freqArr = new Array(words.length)\n const keys = Object.keys(hash)\n \n for(let k of keys) {\n let freq = hash[k]\n if(freqArr[freq] == null) {\n freqArr[freq] = []\n }\n freqArr[freq].push(k)\n }\n \n const res = []\n for(let i = freqArr.length; i >= 0 && res.length < k; i--) {\n if(freqArr[i] != null) {\n res.push(...(freqArr[i].sort()))\n }\n }\n \n return res.slice(0, k)\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720c26", + "questionid": 347, + "title": "Degree of an Array", + "slug": "degree-of-an-array", + "description": "Given a non-empty array of non-negative integers nums, the degree of this array is defined as the maximum frequency of any one of its elements. Your task is to find the smallest possible length of a (contiguous) subarray of nums, that has the same degree as nums. ", + "category": [ + "Array", + "Hash Table" + ], + "complexity": "Easy", + "successrate": 55.6, + "totalsubmissions": 265235, + "totalaccepted": 147495, + "likes": 1945, + "dislikes": 1289, + "hints": "Say 5 is the only element that occurs the most number of times - for example, nums = [1, 5, 2, 3, 5, 4, 5, 6]. What is the answer?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,2,2,3,1]", + "expected_output": "2", + "explanation": "The input array has a degree of 2 because both elements 1 and 2 appear twice.\nOf the subarrays that have the same degree:\n[1, 2, 2, 3, 1], [1, 2, 2, 3], [2, 2, 3, 1], [1, 2, 2], [2, 2, 3], [2, 2]\nThe shortest length is 2. So return 2." + }, + { + "example_num": 2, + "expected_input": "nums = [1,2,2,3,1,4,2]", + "expected_output": "6", + "explanation": "The degree is 3 because the element 2 is repeated 3 times.\nSo [2,2,3,1,4,2] is the shortest subarray, therefore returning 6." + } + ], + "solution": "/**\n * @param {number[]} nums\n * @return {number}\n */\nconst findShortestSubArray = function(nums) {\n const left = {};\n const right = {};\n const count = {};\n\n for (let i = 0; i < nums.length; i++) {\n if (!left.hasOwnProperty(nums[i])) {\n left[nums[i]] = i;\n }\n right[nums[i]] = i;\n count[nums[i]] = count[nums[i]] ? count[nums[i]] + 1 : 1;\n }\n const degree = Math.max(...Object.keys(count).map(el => count[el]));\n let res = nums.length;\n for (let el in count) {\n if (count.hasOwnProperty(el) && count[el] === degree) {\n res = Math.min(res, right[el] - left[el] + 1);\n }\n }\n\n return res;\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720c2a", + "questionid": 351, + "title": "Subarray Product Less Than K", + "slug": "subarray-product-less-than-k", + "description": "Given an array of integers nums and an integer k, return the number of contiguous subarrays where the product of all the elements in the subarray is strictly less than k. ", + "category": [ + "Array", + "Sliding Window" + ], + "complexity": "Medium", + "successrate": 43.7, + "totalsubmissions": 368610, + "totalaccepted": 160899, + "likes": 3826, + "dislikes": 132, + "hints": "For each j, let opt(j) be the smallest i so that nums[i] * nums[i+1] * ... * nums[j] is less than k. opt is an increasing function.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [10,5,2,6], k = 100", + "expected_output": "8", + "explanation": "The 8 subarrays that have product less than 100 are:\n[10], [5], [2], [6], [10, 5], [5, 2], [2, 6], [5, 2, 6]\nNote that [10, 5, 2] is not included as the product of 100 is not strictly less than k." + }, + { + "example_num": 2, + "expected_input": "nums = [1,2,3], k = 0", + "expected_output": "0", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} nums\n * @param {number} k\n * @return {number}\n */\nconst numSubarrayProductLessThanK = function(nums, k) {\n if (k == 0) return 0\n let cnt = 0\n let pro = 1\n for (let i = 0, j = 0, len = nums.length; j < len; j++) {\n pro *= nums[j]\n while (i <= j && pro >= k) {\n pro /= nums[i++]\n }\n cnt += j - i + 1\n }\n return cnt\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720c2d", + "questionid": 354, + "title": "Longest Word in Dictionary", + "slug": "longest-word-in-dictionary", + "description": "Given an array of strings words representing an English Dictionary, return the longest word in words that can be built one character at a time by other words in words. If there is more than one possible answer, return the longest word with the smallest lexicographical order. If there is no answer, return the empty string. ", + "category": [ + "Array", + "Hash Table", + "String", + "Trie", + "Sorting" + ], + "complexity": "Medium", + "successrate": 50.9, + "totalsubmissions": 220173, + "totalaccepted": 112159, + "likes": 1317, + "dislikes": 1288, + "hints": "For every word in the input list, we can check whether all prefixes of that word are in the input list by using a Set.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "words = ["w","wo","wor","worl","world"]", + "expected_output": ""world"", + "explanation": "The word "world" can be built one character at a time by "w", "wo", "wor", and "worl"." + }, + { + "example_num": 2, + "expected_input": "words = ["a","banana","app","appl","ap","apply","apple"]", + "expected_output": ""apple"", + "explanation": "Both "apply" and "apple" can be built from other words in the dictionary. However, "apple" is lexicographically smaller than "apply"." + } + ], + "solution": "/**\n * @param {string[]} words\n * @return {string}\n */\nconst longestWord = function(words) {\n if(words == null || words.length === 0) return ''\n words.sort()\n const s = new Set()\n let res = ''\n for(let i = 0, len = words.length; i < len; i++) {\n const w = words[i]\n if(w.length === 1 || s.has(w.slice(0, w.length - 1))) {\n res = w.length > res.length ? w : res\n s.add(w)\n }\n }\n return res\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720c2f", + "questionid": 356, + "title": "Self Dividing Numbers", + "slug": "self-dividing-numbers", + "description": "A self-dividing number is a number that is divisible by every digit it contains. A self-dividing number is not allowed to contain the digit zero. Given two integers left and right, return a list of all the self-dividing numbers in the range [left, right]. ", + "category": [ + "Math" + ], + "complexity": "Easy", + "successrate": 76.9, + "totalsubmissions": 226706, + "totalaccepted": 174351, + "likes": 1130, + "dislikes": 347, + "hints": "For each number in the range, check whether it is self dividing by converting that number to a character array (or string in Python), then checking that each digit is nonzero and divides the original number.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "left = 1, right = 22", + "expected_output": "[1,2,3,4,5,6,7,8,9,11,12,15,22]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "left = 47, right = 85", + "expected_output": "[48,55,66,77]", + "explanation": "" + } + ], + "solution": null + }, + { + "_id": "66f925ddfdfb8e1665720c32", + "questionid": 359, + "title": "Asteroid Collision", + "slug": "asteroid-collision", + "description": "We are given an array asteroids of integers representing asteroids in a row. For each asteroid, the absolute value represents its size, and the sign represents its direction (positive meaning right, negative meaning left). Each asteroid moves at the same speed. Find out the state of the asteroids after all collisions. If two asteroids meet, the smaller one will explode. If both are the same size, both will explode. Two asteroids moving in the same direction will never meet. ", + "category": [ + "Array", + "Stack" + ], + "complexity": "Medium", + "successrate": 44.4, + "totalsubmissions": 433907, + "totalaccepted": 192607, + "likes": 3407, + "dislikes": 267, + "hints": "Say a row of asteroids is stable. What happens when a new asteroid is added on the right?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "asteroids = [5,10,-5]", + "expected_output": "[5,10]", + "explanation": "The 10 and -5 collide resulting in 10. The 5 and 10 never collide." + }, + { + "example_num": 2, + "expected_input": "asteroids = [8,-8]", + "expected_output": "[]", + "explanation": "The 8 and -8 collide exploding each other." + }, + { + "example_num": 3, + "expected_input": "asteroids = [10,2,-5]", + "expected_output": "[10]", + "explanation": "The 2 and -5 collide resulting in -5. The 10 and -5 collide resulting in 10." + } + ], + "solution": "/**\n * @param {number[]} asteroids\n * @return {number[]}\n */\nconst asteroidCollision = function(asteroids) {\n const stk = [], n = asteroids.length, {abs} = Math\n for(const e of asteroids) {\n while(stk.length && stk.at(-1) > 0 && e < 0 && -e > stk.at(-1)) {\n stk.pop()\n }\n if(stk.length && stk.at(-1) > 0 && e < 0 && -e === stk.at(-1)) {\n stk.pop()\n }else if(stk.length && stk.at(-1) > 0 && e < 0 && -e < stk.at(-1)) {\n \n }else stk.push(e)\n }\n return stk\n};\n\n// another\n\n\n/**\n * @param {number[]} asteroids\n * @return {number[]}\n */\nconst asteroidCollision = function(asteroids) {\n const positive = []\n const res = []\n for(let i = 0; i < asteroids.length; i++) {\n if (asteroids[i] > 0) {\n positive.push(i)\n } else {\n const negVal = asteroids[i];\n\n while(positive.length > 0 && asteroids[ positive[positive.length - 1] ] + negVal < 0 ) {\n asteroids[ positive[positive.length - 1] ] = undefined\n positive.pop()\n }\n\n if (positive.length > 0) {\n if (asteroids[ positive[positive.length - 1] ] + negVal > 0) {\n asteroids[i] = undefined\n } else if(asteroids[ positive[positive.length - 1] ] + negVal === 0) {\n asteroids[i] = undefined\n asteroids[ positive[positive.length - 1] ] = undefined\n positive.pop()\n }\n }\n }\n }\n return asteroids.filter(el => el !== undefined)\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720c34", + "questionid": 361, + "title": "Monotone Increasing Digits", + "slug": "monotone-increasing-digits", + "description": "An integer has monotone increasing digits if and only if each pair of adjacent digits x and y satisfy x <= y. Given an integer n, return the largest number that is less than or equal to n with monotone increasing digits. ", + "category": [ + "Math", + "Greedy" + ], + "complexity": "Medium", + "successrate": 46.7, + "totalsubmissions": 79953, + "totalaccepted": 37361, + "likes": 901, + "dislikes": 87, + "hints": "Build the answer digit by digit, adding the largest possible one that would make the number still less than or equal to N.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 10", + "expected_output": "9", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "n = 1234", + "expected_output": "1234", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "n = 332", + "expected_output": "299", + "explanation": "" + } + ], + "solution": "/**\n * @param {number} N\n * @return {number}\n */\nfunction monotoneIncreasingDigits(N) {\n const arr = (''+N).split('').map(el => +el)\n let mark = arr.length\n for(let i = arr.length - 1; i > 0; i--) {\n if (arr[i] < arr[i - 1]) {\n mark = i - 1\n arr[i - 1]--\n }\n }\n for(let i = mark + 1; i < arr.length; i++) {\n arr[i] = 9\n }\n\n return arr.join('')\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720c35", + "questionid": 362, + "title": "Daily Temperatures", + "slug": "daily-temperatures", + "description": "Given an array of integers temperatures represents the daily temperatures, return an array answer such that answer[i] is the number of days you have to wait after the ith day to get a warmer temperature. If there is no future day for which this is possible, keep answer[i] == 0 instead. ", + "category": [ + "Array", + "Stack", + "Monotonic Stack" + ], + "complexity": "Medium", + "successrate": 67, + "totalsubmissions": 559365, + "totalaccepted": 374997, + "likes": 6760, + "dislikes": 155, + "hints": "If the temperature is say, 70 today, then in the future a warmer temperature must be either 71, 72, 73, ..., 99, or 100. We could remember when all of them occur next.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "temperatures = [73,74,75,71,69,72,76,73]", + "expected_output": "[1,1,4,2,1,1,0,0]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "temperatures = [30,40,50,60]", + "expected_output": "[1,1,1,0]", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "temperatures = [30,60,90]", + "expected_output": "[1,1,0]", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} T\n * @return {number[]}\n */\nconst dailyTemperatures = function(T) {\n const n = T.length;\n const sk = [];\n const res = new Array(n).fill(0);\n for (let i = 0; i < n; i++) {\n let cur = T[i];\n while (sk.length && T[sk[sk.length - 1]] < cur) {\n let tail = sk.pop();\n res[tail] = i - tail;\n }\n sk.push(i);\n }\n return res;\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720c38", + "questionid": 365, + "title": "Find Smallest Letter Greater Than Target", + "slug": "find-smallest-letter-greater-than-target", + "description": "Given a characters array letters that is sorted in non-decreasing order and a character target, return the smallest character in the array that is larger than target. Note that the letters wrap around. ", + "category": [ + "Array", + "Binary Search" + ], + "complexity": "Easy", + "successrate": 45.2, + "totalsubmissions": 402960, + "totalaccepted": 182233, + "likes": 1541, + "dislikes": 1403, + "hints": "Try to find whether each of 26 next letters are in the given string array.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "letters = ["c","f","j"], target = "a"", + "expected_output": ""c"", + "explanation": "The smallest character that is lexicographically greater than 'a' in letters is 'c'." + }, + { + "example_num": 2, + "expected_input": "letters = ["c","f","j"], target = "c"", + "expected_output": ""f"", + "explanation": "The smallest character that is lexicographically greater than 'c' in letters is 'f'." + }, + { + "example_num": 3, + "expected_input": "letters = ["x","x","y","y"], target = "z"", + "expected_output": ""x"", + "explanation": "There are no characters in letters that is lexicographically greater than 'z' so we return letters[0]." + } + ], + "solution": "/**\n * @param {character[]} letters\n * @param {character} target\n * @return {character}\n */\nconst nextGreatestLetter = function (letters, target) {\n const n = letters.length\n if (target < letters[0] || target >= letters[n - 1]) return letters[0]\n let left = 0\n let right = n - 1\n while (left < right) {\n let mid = left + ((right - left) >> 1)\n if (letters[mid] <= target) left = mid + 1\n else right = mid\n }\n return letters[right]\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720c3d", + "questionid": 370, + "title": "Cracking the Safe", + "slug": "cracking-the-safe", + "description": "There is a safe protected by a password. The password is a sequence of n digits where each digit can be in the range [0, k - 1]. The safe has a peculiar way of checking the password. When you enter in a sequence, it checks the most recent n digits that were entered each time you type a digit. Return any string of minimum length that will unlock the safe at some point of entering it. ", + "category": [ + "Depth-First Search", + "Graph", + "Eulerian Circuit" + ], + "complexity": "Hard", + "successrate": 54.6, + "totalsubmissions": 83640, + "totalaccepted": 45652, + "likes": 194, + "dislikes": 36, + "hints": "We can think of this problem as the problem of finding an Euler path (a path visiting every edge exactly once) on the following graph: there are $$k^{n-1}$$ nodes with each node having $$k$$ edges. It turns out this graph always has an Eulerian circuit (path starting where it ends.)\r\n\r\nWe should visit each node in \"post-order\" so as to not get stuck in the graph prematurely.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 1, k = 2", + "expected_output": ""10"", + "explanation": "The password is a single digit, so enter each digit. "01" would also unlock the safe." + }, + { + "example_num": 2, + "expected_input": "n = 2, k = 2", + "expected_output": ""01100"", + "explanation": "For each possible password:\n- "00" is typed in starting from the 4th digit.\n- "01" is typed in starting from the 1st digit.\n- "10" is typed in starting from the 3rd digit.\n- "11" is typed in starting from the 2nd digit.\nThus "01100" will unlock the safe. "10011", and "11001" would also unlock the safe." + } + ], + "solution": null + }, + { + "_id": "66f925ddfdfb8e1665720c3e", + "questionid": 371, + "title": "Pyramid Transition Matrix", + "slug": "pyramid-transition-matrix", + "description": "You are stacking blocks to form a pyramid. Each block has a color, which is represented by a single letter. Each row of blocks contains one less block than the row beneath it and is centered on top. To make the pyramid aesthetically pleasing, there are only specific triangular patterns that are allowed. A triangular pattern consists of a single block stacked on top of two blocks. The patterns are given\u00a0as a list of\u00a0three-letter strings allowed, where the first two characters of a pattern represent the left and right bottom blocks respectively, and the third character is the top block. You start with a bottom row of blocks bottom, given as a single string, that you must use as the base of the pyramid. Given bottom and allowed, return true if you can build the pyramid all the way to the top such that every triangular pattern in the pyramid is in allowed, or false otherwise. ", + "category": [ + "Bit Manipulation", + "Depth-First Search", + "Breadth-First Search" + ], + "complexity": "Medium", + "successrate": 54.6, + "totalsubmissions": 49490, + "totalaccepted": 27038, + "likes": 450, + "dislikes": 427, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "bottom = "BCD", allowed = ["BCC","CDE","CEA","FFF"]", + "expected_output": "true", + "explanation": "The allowed triangular patterns are shown on the right.\nStarting from the bottom (level 3), we can build "CE" on level 2 and then build "A" on level 1.\nThere are three triangular patterns in the pyramid, which are "BCC", "CDE", and "CEA". All are allowed." + }, + { + "example_num": 2, + "expected_input": "bottom = "AAAA", allowed = ["AAB","AAC","BCD","BBE","DEF"]", + "expected_output": "false", + "explanation": "The allowed triangular patterns are shown on the right.\nStarting from the bottom (level 4), there are multiple ways to build level 3, but trying all the possibilites, you will get always stuck before building level 1." + } + ], + "solution": "/**\n * @param {string} bottom\n * @param {string[]} allowed\n * @return {boolean}\n */\nconst pyramidTransition = function (bottom, allowed) {\n const m = new Map()\n for (let e of allowed) {\n const p = e.slice(0, 2)\n if (!m.has(p)) m.set(p, new Set())\n m.get(p).add(e[2])\n }\n return dfs(bottom, '', m, 0)\n}\n\nfunction dfs(row, next, m, i) {\n if (row.length === 1) return true\n if (next.length + 1 === row.length) return dfs(next, '', m, 0)\n for (let c of m.get(row.slice(i, i + 2)) || new Set())\n if (dfs(row, next + c, m, i + 1)) return true\n return false\n}\n\n" + }, + { + "_id": "66f925ddfdfb8e1665720c3f", + "questionid": 372, + "title": "Set Intersection Size At Least Two", + "slug": "set-intersection-size-at-least-two", + "description": "An integer interval [a, b] (for integers a < b) is a set of all consecutive integers from a to b, including a and b. Find the minimum size of a set S such that for every integer interval A in intervals, the intersection of S with A has a size of at least two. ", + "category": [ + "Array", + "Greedy", + "Sorting" + ], + "complexity": "Hard", + "successrate": 43.1, + "totalsubmissions": 35767, + "totalaccepted": 15431, + "likes": 445, + "dislikes": 59, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "intervals = [[1,3],[3,7],[8,9]]", + "expected_output": "5", + "explanation": "let nums = [2, 3, 4, 8, 9].\nIt can be shown that there cannot be any containing array of size 4." + }, + { + "example_num": 2, + "expected_input": "intervals = [[1,3],[1,4],[2,5],[3,5]]", + "expected_output": "3", + "explanation": "let nums = [2, 3, 4].\nIt can be shown that there cannot be any containing array of size 2." + }, + { + "example_num": 3, + "expected_input": "intervals = [[1,2],[2,3],[2,4],[4,5]]", + "expected_output": "5", + "explanation": "let nums = [1, 2, 3, 4, 5].\nIt can be shown that there cannot be any containing array of size 4." + } + ], + "solution": "/**\n * @param {number[][]} intervals\n * @return {number}\n */\nconst intersectionSizeTwo = function (intervals) {\n if (intervals.length === 1) return 2\n intervals.sort((a, b) => (a[1] !== b[1] ? a[1] - b[1] : b[0] - a[0]))\n let right = intervals[0][1]\n let left = right - 1\n let res = 2\n\n for (let i = 1, len = intervals.length; i < len; i++) {\n const cur = intervals[i]\n if(cur[0] <= left) continue\n else if(cur[0] <= right) {\n res++\n left = right\n right = cur[1]\n } else {\n res += 2\n right = cur[1]\n left = right - 1\n }\n }\n\n return res\n}\n\n// another\n\n\n/**\n * @param {number[][]} intervals\n * @return {number}\n */\nconst intersectionSizeTwo = function(intervals) {\n let highest = Number.NEGATIVE_INFINITY;\n let secondHighest = Number.NEGATIVE_INFINITY;\n return intervals\n .sort((a, b) => a[1] - b[1])\n .reduce((sum, interval) => {\n if (interval[0] > secondHighest) {\n secondHighest = interval[1];\n highest = interval[1] - 1;\n return sum + 2;\n }\n else if (interval[0] > highest) {\n highest = secondHighest;\n secondHighest = interval[1];\n return sum + 1;\n }\n return sum;\n }, 0);\n};\n\n// another\n\n/**\n * @param {number[][]} intervals\n * @return {number}\n */\nconst intersectionSizeTwo = function(intervals) {\n intervals.sort((a, b) => a[1] - b[1]);\n\n let n = intervals.length;\n if (n === 0) return 0;\n\n let count = 2;\n let last = intervals[0][1];\n let sec_last = intervals[0][1] - 1;\n\n for (let i = 1; i < n; i++) {\n if (intervals[i][0] <= sec_last) continue;\n else if (intervals[i][0] <= last) {\n sec_last = last;\n last = intervals[i][1];\n count++;\n } else {\n last = intervals[i][1];\n sec_last = intervals[i][1] - 1;\n count += 2;\n }\n }\n return count;\n};\n\n// another\n\n/**\n * @param {number[][]} intervals\n * @return {number}\n */\nconst intersectionSizeTwo = function (intervals) {\n if (intervals.length === 1) return 2\n intervals.sort((a, b) => (a[1] !== b[1] ? a[1] - b[1] : b[0] - a[0]))\n let right = intervals[0][1]\n let left = right - 1\n let result = 2\n for (let i = 1, len = intervals.length; i < len; i++) {\n const curr = intervals[i]\n if (curr[0] <= right && curr[0] > left) {\n result++\n left = right\n right = curr[1]\n } else if (curr[0] > right) {\n result += 2\n left = curr[1] - 1\n right = curr[1]\n }\n }\n\n return result\n}\n\n" + }, + { + "_id": "66f925ddfdfb8e1665720c40", + "questionid": 373, + "title": "N-ary Tree Level Order Traversal", + "slug": "n-ary-tree-level-order-traversal", + "description": "Given an n-ary tree, return the level order traversal of its nodes' values. Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See examples). ", + "category": [ + "Tree", + "Breadth-First Search" + ], + "complexity": "Medium", + "successrate": 68.8, + "totalsubmissions": 251213, + "totalaccepted": 172915, + "likes": 1774, + "dislikes": 81, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [1,null,3,2,4,null,5,6]", + "expected_output": "[[1],[3,2,4],[5,6]]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]", + "expected_output": "[[1],[2,3,4,5],[6,7,8,9,10],[11,12,13],[14]]", + "explanation": "" + } + ], + "solution": "/**\n * // Definition for a Node.\n * function Node(val,children) {\n * this.val = val;\n * this.children = children;\n * };\n */\n/**\n * @param {Node} root\n * @return {number[][]}\n */\nconst levelOrder = function(root) {\n const res = []\n if(root == null) return res\n helper(root, 0, res)\n return res\n};\n\nfunction helper(node, index, res) {\n if(node == null) return\n if(res[index] == null) res[index] = []\n res[index].push(node.val)\n for(let i = 0, len = node.children.length; i < len; i++) {\n helper(node.children[i], index + 1, res)\n }\n}\n\n// another\n\n/**\n * // Definition for a Node.\n * function Node(val,children) {\n * this.val = val;\n * this.children = children;\n * };\n */\n/**\n * @param {Node} root\n * @return {number[][]}\n */\nconst levelOrder = function(root) {\n const res = []\n if(root == null) return res\n const q = []\n q.push(root)\n while(q.length) {\n const size = q.length\n const cur = []\n for(let i = 0; i < size; i++) {\n const node = q.shift()\n cur.push(node.val)\n q.push(...node.children)\n }\n res.push(cur)\n }\n return res\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720c44", + "questionid": 377, + "title": "Largest Plus Sign", + "slug": "largest-plus-sign", + "description": "You are given an integer n. You have an n x n binary grid grid with all values initially 1's except for some indices given in the array mines. The ith element of the array mines is defined as mines[i] = [xi, yi] where grid[xi][yi] == 0. Return the order of the largest axis-aligned plus sign of 1's contained in grid. If there is none, return 0. An axis-aligned plus sign of 1's of order k has some center grid[r][c] == 1 along with four arms of length k - 1 going up, down, left, and right, and made of 1's. Note that there could be 0's or 1's beyond the arms of the plus sign, only the relevant area of the plus sign is checked for 1's. ", + "category": [ + "Array", + "Dynamic Programming" + ], + "complexity": "Medium", + "successrate": 48.6, + "totalsubmissions": 98947, + "totalaccepted": 48062, + "likes": 1104, + "dislikes": 189, + "hints": "For each direction such as \"left\", find left[r][c] = the number of 1s you will see before a zero starting at r, c and walking left. You can find this in N^2 time with a dp. The largest plus sign at r, c is just the minimum of left[r][c], up[r][c] etc.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 5, mines = [[4,2]]", + "expected_output": "2", + "explanation": "In the above grid, the largest plus sign can only be of order 2. One of them is shown." + }, + { + "example_num": 2, + "expected_input": "n = 1, mines = [[0,0]]", + "expected_output": "0", + "explanation": "There is no plus sign, so return 0." + } + ], + "solution": "/**\n * @param {number} N\n * @param {number[][]} mines\n * @return {number}\n */\nconst orderOfLargestPlusSign = function (N, mines) {\n const dp = [...Array(N)].map((_) => Array(N).fill(N))\n mines.map((m) => {\n dp[m[0]][m[1]] = 0\n })\n for (let i = 0; i < N; i++) {\n for (let j = 0, k = N - 1, l = (r = u = d = 0); j < N; j++, k--) {\n dp[i][j] = Math.min(dp[i][j], (l = dp[i][j] == 0 ? 0 : l + 1))\n dp[i][k] = Math.min(dp[i][k], (r = dp[i][k] == 0 ? 0 : r + 1))\n dp[j][i] = Math.min(dp[j][i], (d = dp[j][i] == 0 ? 0 : d + 1))\n dp[k][i] = Math.min(dp[k][i], (u = dp[k][i] == 0 ? 0 : u + 1))\n }\n }\n let max = 0\n for (let i = 0; i < N; i++) {\n for (let j = 0; j < N; j++) {\n max = Math.max(dp[i][j], max)\n }\n }\n return max\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720c4b", + "questionid": 384, + "title": "Max Chunks To Make Sorted II", + "slug": "max-chunks-to-make-sorted-ii", + "description": "You are given an integer array arr. We split arr into some number of chunks (i.e., partitions), and individually sort each chunk. After concatenating them, the result should equal the sorted array. Return the largest number of chunks we can make to sort the array. ", + "category": [ + "Array", + "Stack", + "Greedy", + "Sorting", + "Monotonic Stack" + ], + "complexity": "Hard", + "successrate": 51.9, + "totalsubmissions": 77723, + "totalaccepted": 40366, + "likes": 1141, + "dislikes": 32, + "hints": "Each k for which some permutation of arr[:k] is equal to sorted(arr)[:k] is where we should cut each chunk.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "arr = [5,4,3,2,1]", + "expected_output": "1", + "explanation": "Splitting into two or more chunks will not return the required result.\nFor example, splitting into [5, 4], [3, 2, 1] will result in [4, 5, 1, 2, 3], which isn't sorted." + }, + { + "example_num": 2, + "expected_input": "arr = [2,1,3,4,4]", + "expected_output": "4", + "explanation": "We can split into two chunks, such as [2, 1], [3, 4, 4].\nHowever, splitting into [2, 1], [3], [4], [4] is the highest number of chunks possible." + } + ], + "solution": null + }, + { + "_id": "66f925ddfdfb8e1665720c0f", + "questionid": 324, + "title": "Maximum Length of Pair Chain", + "slug": "maximum-length-of-pair-chain", + "description": "You are given an array of n pairs pairs where pairs[i] = [lefti, righti] and lefti < righti. A pair p2 = [c, d] follows a pair p1 = [a, b] if b < c. A chain of pairs can be formed in this fashion. Return the length longest chain which can be formed. You do not need to use up all the given intervals. You can select pairs in any order. ", + "category": [ + "Array", + "Dynamic Programming", + "Greedy", + "Sorting" + ], + "complexity": "Medium", + "successrate": 55.6, + "totalsubmissions": 192064, + "totalaccepted": 106828, + "likes": 2190, + "dislikes": 100, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "pairs = [[1,2],[2,3],[3,4]]", + "expected_output": "2", + "explanation": "The longest chain is [1,2] -> [3,4]." + }, + { + "example_num": 2, + "expected_input": "pairs = [[1,2],[7,8],[4,5]]", + "expected_output": "3", + "explanation": "The longest chain is [1,2] -> [4,5] -> [7,8]." + } + ], + "solution": "/**\n * @param {number[][]} pairs\n * @return {number}\n */\nconst findLongestChain = function(pairs) {\n let res = 0\n const n = pairs.length\n if(n === 0) return res\n pairs.sort((a, b) => a[1] - b[1])\n let end = pairs[0][1]\n res++\n for(let i = 1; i < n; i++) {\n const e = pairs[i]\n if(e[0] <= end) continue\n res++\n end = e[1]\n }\n\n return res\n};\n\n// another\n\n/**\n * @param {number[][]} pairs\n * @return {number}\n */\nconst findLongestChain = function(pairs) {\n pairs.sort((a, b) => a[1] - b[1])\n let end = pairs[0][1], res = 1\n for(let i = 1, len = pairs.length; i < len; i++) {\n if(pairs[i][0] > end) {\n res++\n end = pairs[i][1]\n } \n }\n return res\n};\n\n// another\n\n/**\n * @param {number[][]} pairs\n * @return {number}\n */\nconst findLongestChain = function(pairs) {\n pairs.sort((a, b) => a[1] - b[1]);\n let cur = Number.MIN_SAFE_INTEGER;\n let res = 0;\n for (let i = 0; i < pairs.length; i++) {\n if (cur < pairs[i][0]) {\n cur = pairs[i][1];\n res += 1;\n }\n }\n return res;\n};\n\n// another\n\n/**\n * @param {number[][]} pairs\n * @return {number}\n */\nconst findLongestChain = function (pairs) {\n pairs.sort((a, b) => a[0] - b[0])\n let out = 0\n let prevEnd = Number.MIN_SAFE_INTEGER\n for (let i = 0; i < pairs.length; i++) {\n const cur = pairs[i]\n if (prevEnd < cur[0]) {\n prevEnd = cur[1]\n out += 1\n } else {\n prevEnd = Math.min(cur[1], prevEnd)\n }\n }\n return out\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720c12", + "questionid": 327, + "title": "Find Duplicate Subtrees", + "slug": "find-duplicate-subtrees", + "description": "Given the root\u00a0of a binary tree, return all duplicate subtrees. For each kind of duplicate subtrees, you only need to return the root node of any one of them. Two trees are duplicate if they have the same structure with the same node values. ", + "category": [ + "Hash Table", + "Tree", + "Depth-First Search", + "Binary Tree" + ], + "complexity": "Medium", + "successrate": 55.7, + "totalsubmissions": 262584, + "totalaccepted": 146375, + "likes": 3150, + "dislikes": 294, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [1,2,3,4,null,2,4,null,null,4]", + "expected_output": "[[2,4],[4]]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "root = [2,1,1]", + "expected_output": "[[1]]", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "root = [2,2,2,3,null,3,null]", + "expected_output": "[[2,3],[3]]", + "explanation": "" + } + ], + "solution": "/**\n * Definition for a binary tree node.\n * function TreeNode(val, left, right) {\n * this.val = (val===undefined ? 0 : val)\n * this.left = (left===undefined ? null : left)\n * this.right = (right===undefined ? null : right)\n * }\n */\n/**\n * @param {TreeNode} root\n * @return {TreeNode[]}\n */\nconst findDuplicateSubtrees = function(root) {\n const hash = {}, res = []\n pre(root, hash, res)\n return res\n};\n\nfunction pre(node, hash, res) {\n if(node == null) return '#'\n const str = `${node.val},${pre(node.left, hash, res)},${pre(node.right, hash, res)}`\n if(hash[str] == null) hash[str] = 0\n hash[str]++\n if(hash[str] === 2) res.push(node)\n return str\n}\n\n// another\n\n/**\n * Definition for a binary tree node.\n * function TreeNode(val, left, right) {\n * this.val = (val===undefined ? 0 : val)\n * this.left = (left===undefined ? null : left)\n * this.right = (right===undefined ? null : right)\n * }\n */\n/**\n * @param {TreeNode} root\n * @return {TreeNode[]}\n */\nconst findDuplicateSubtrees = function(root) {\n const serId = {}, cntId = {}, res = []\n let id = 1\n post(root)\n return res\n \n function post(node) {\n if(node == null) return 0\n const curId = `${post(node.left)},${node.val},${post(node.right)}`\n serId[curId] = serId[curId] || id\n if(serId[curId] === id) id++\n cntId[curId] = (cntId[curId] || 0) + 1\n if(cntId[curId] === 2) res.push(node)\n return serId[curId]\n }\n};\n\n" + }, + { + "_id": "66f925ddfdfb8e1665720c13", + "questionid": 328, + "title": "Two Sum IV - Input is a BST", + "slug": "two-sum-iv-input-is-a-bst", + "description": "Given the root of a Binary Search Tree and a target number k, return true if there exist two elements in the BST such that their sum is equal to the given target. ", + "category": [ + "Hash Table", + "Two Pointers", + "Tree", + "Depth-First Search", + "Breadth-First Search", + "Binary Search Tree", + "Binary Tree" + ], + "complexity": "Easy", + "successrate": 58.7, + "totalsubmissions": 515724, + "totalaccepted": 302894, + "likes": 3536, + "dislikes": 199, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [5,3,6,2,4,null,7], k = 9", + "expected_output": "true", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "root = [5,3,6,2,4,null,7], k = 28", + "expected_output": "false", + "explanation": "" + } + ], + "solution": "/**\n * Definition for a binary tree node.\n * function TreeNode(val) {\n * this.val = val;\n * this.left = this.right = null;\n * }\n */\n/**\n * @param {TreeNode} root\n * @param {number} k\n * @return {boolean}\n */\nconst findTarget = function(root, k) {\n const m = new Map()\n return traverse(root, k, m)\n};\n\nfunction traverse(node, k, m) {\n if(node == null) return false\n if(m.has(k - node.val)) return true\n m.set(node.val, node)\n return traverse(node.left,k,m) || traverse(node.right,k,m)\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720c18", + "questionid": 333, + "title": "Trim a Binary Search Tree", + "slug": "trim-a-binary-search-tree", + "description": "Given the root of a binary search tree and the lowest and highest boundaries as low and high, trim the tree so that all its elements lies in [low, high]. Trimming the tree should not change the relative structure of the elements that will remain in the tree (i.e., any node's descendant should remain a descendant). It can be proven that there is a unique answer. Return the root of the trimmed binary search tree. Note that the root may change depending on the given bounds. ", + "category": [ + "Tree", + "Depth-First Search", + "Binary Search Tree", + "Binary Tree" + ], + "complexity": "Medium", + "successrate": 66.2, + "totalsubmissions": 345046, + "totalaccepted": 228414, + "likes": 4658, + "dislikes": 236, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [1,0,2], low = 1, high = 2", + "expected_output": "[1,null,2]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "root = [3,0,4,null,2,null,null,1], low = 1, high = 3", + "expected_output": "[3,2,null,1]", + "explanation": "" + } + ], + "solution": "/**\n * Definition for a binary tree node.\n * function TreeNode(val) {\n * this.val = val;\n * this.left = this.right = null;\n * }\n */\n/**\n * @param {TreeNode} root\n * @param {number} L\n * @param {number} R\n * @return {TreeNode}\n */\nconst trimBST = function(root, L, R) {\n return single(root, L, R);\n};\n\nfunction single(node, L, R) {\n if (node === null) {\n return null;\n }\n if (node.val > R) {\n return single(node.left, L, R);\n }\n if (node.val < L) {\n return single(node.right, L, R);\n }\n if (node.left !== null) {\n node.left = single(node.left, L, R);\n }\n if (node.right !== null) {\n node.right = single(node.right, L, R);\n }\n return node;\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720c1a", + "questionid": 335, + "title": "Second Minimum Node In a Binary Tree", + "slug": "second-minimum-node-in-a-binary-tree", + "description": "Given a non-empty special binary tree consisting of nodes with the non-negative value, where each node in this tree has exactly two or zero sub-node. If the node has two sub-nodes, then this node's value is the smaller value among its two sub-nodes. More formally, the property\u00a0root.val = min(root.left.val, root.right.val)\u00a0always holds. Given such a binary tree, you need to output the second minimum value in the set made of all the nodes' value in the whole tree. If no such second minimum value exists, output -1 instead. ", + "category": [ + "Tree", + "Depth-First Search", + "Binary Tree" + ], + "complexity": "Easy", + "successrate": 43.6, + "totalsubmissions": 314726, + "totalaccepted": 137258, + "likes": 1191, + "dislikes": 1462, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [2,2,5,null,null,5,7]", + "expected_output": "5", + "explanation": "The smallest value is 2, the second smallest value is 5." + }, + { + "example_num": 2, + "expected_input": "root = [2,2,2]", + "expected_output": "-1", + "explanation": "The smallest value is 2, but there isn't any second smallest value." + } + ], + "solution": "/**\n * Definition for a binary tree node.\n * function TreeNode(val) {\n * this.val = val;\n * this.left = this.right = null;\n * }\n */\n/**\n * @param {TreeNode} root\n * @return {number}\n */\nconst findSecondMinimumValue = function(root) {\n if(root == null) return -1\n const q = [root]\n let min = Number.MAX_VALUE\n let min2nd = Number.MAX_VALUE\n while(q.length) {\n const len = q.length\n for(let i = 0; i < len; i++) {\n const cur = q.shift()\n if(cur.val <= min) {\n min = cur.val\n } else if(cur.val > min && cur.val < min2nd) {\n min2nd = cur.val\n }\n if(cur.left) q.push(cur.left)\n if(cur.right) q.push(cur.right)\n }\n }\n return min2nd === Number.MAX_VALUE ? -1 : min2nd\n};\n\n// another\n\n/**\n * Definition for a binary tree node.\n * function TreeNode(val) {\n * this.val = val;\n * this.left = this.right = null;\n * }\n */\n/**\n * @param {TreeNode} root\n * @return {number}\n */\nconst findSecondMinimumValue = function (root) {\n if (root === null) return -1;\n if (root.left === null && root.right === null) return -1;\n let left = root.left.val;\n let right = root.right.val;\n if (left === root.val) {\n left = findSecondMinimumValue(root.left);\n }\n if (right === root.val) {\n right = findSecondMinimumValue(root.right);\n }\n if (right !== -1 && left !== -1) {\n return Math.min(left, right);\n }\n if (right === -1) {\n return left;\n }\n if (left === -1) {\n return right;\n }\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720c1b", + "questionid": 336, + "title": "Number of Longest Increasing Subsequence", + "slug": "number-of-longest-increasing-subsequence", + "description": "Given an integer array\u00a0nums, return the number of longest increasing subsequences. Notice that the sequence has to be strictly increasing. ", + "category": [ + "Array", + "Dynamic Programming", + "Binary Indexed Tree", + "Segment Tree" + ], + "complexity": "Medium", + "successrate": 40.8, + "totalsubmissions": 267095, + "totalaccepted": 108909, + "likes": 3377, + "dislikes": 163, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,3,5,4,7]", + "expected_output": "2", + "explanation": "The two longest increasing subsequences are [1, 3, 4, 7] and [1, 3, 5, 7]." + }, + { + "example_num": 2, + "expected_input": "nums = [2,2,2,2,2]", + "expected_output": "5", + "explanation": "The length of the longest increasing subsequence is 1, and there are 5 increasing subsequences of length 1, so output 5." + } + ], + "solution": "/**\n * @param {number[]} nums\n * @return {number}\n */\nconst findNumberOfLIS = function(nums) {\n if (nums.length === 0) return 0;\n const len = new Array(nums.length);\n const cnt = new Array(nums.length);\n let max = 1;\n let res=1;\n len[0] = 1;\n cnt[0] = 1;\n for (let i = 1; i < nums.length; i++) {\n len[i] = 1;\n cnt[i] = 1;\n for (let j = 0; j < i; j++) {\n if (nums[j] < nums[i]) {\n if (len[j] + 1 > len[i]) {\n cnt[i] = cnt[j];\n len[i] = len[j] + 1;\n } else if (len[j] + 1 === len[i]) {\n cnt[i] += cnt[j];\n }\n }\n }\n if (len[i] > max) {\n max = len[i];\n res = cnt[i];\n } else if (len[i] === max) {\n res += cnt[i];\n }\n }\n return res;\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720c20", + "questionid": 341, + "title": "Longest Univalue Path", + "slug": "longest-univalue-path", + "description": "Given the root of a binary tree, return the length of the longest path, where each node in the path has the same value. This path may or may not pass through the root. The length of the path between two nodes is represented by the number of edges between them. ", + "category": [ + "Tree", + "Depth-First Search", + "Binary Tree" + ], + "complexity": "Medium", + "successrate": 39.3, + "totalsubmissions": 355853, + "totalaccepted": 139892, + "likes": 3041, + "dislikes": 607, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [5,4,5,1,1,null,5]", + "expected_output": "2", + "explanation": "The shown image shows that the longest path of the same value (i.e. 5)." + }, + { + "example_num": 2, + "expected_input": "root = [1,4,5,4,4,null,5]", + "expected_output": "2", + "explanation": "The shown image shows that the longest path of the same value (i.e. 4)." + } + ], + "solution": "\n/**\n * Definition for a binary tree node.\n * function TreeNode(val, left, right) {\n * this.val = (val===undefined ? 0 : val)\n * this.left = (left===undefined ? null : left)\n * this.right = (right===undefined ? null : right)\n * }\n */\n/**\n * @param {TreeNode} root\n * @return {number}\n */\nconst longestUnivaluePath = function(root) {\n let res = 0\n dfs(root)\n return res\n\n function dfs(node) {\n if(node == null) return 0\n let left = dfs(node.left), right = dfs(node.right)\n if(node.left && node.left.val === node.val) left++\n else left = 0\n\n if(node.right && node.right.val === node.val) right++\n else right = 0\n\n res = Math.max(res, left + right)\n return Math.max(left, right)\n }\n};\n\n// another\n\n/**\n * Definition for a binary tree node.\n * function TreeNode(val) {\n * this.val = val;\n * this.left = this.right = null;\n * }\n */\n/**\n * @param {TreeNode} root\n * @return {number}\n */\nconst getCount = function(root, longest) {\n if (!root) {\n return 0;\n }\n let leftCount = getCount(root.left, longest);\n let rightCount = getCount(root.right, longest);\n if (root.left && root.left.val === root.val) {\n leftCount++;\n } else {\n leftCount = 0;\n }\n if (root.right && root.right.val === root.val) {\n rightCount++;\n } else {\n rightCount = 0;\n }\n longest.max = Math.max(longest.max, leftCount + rightCount);\n return Math.max(leftCount, rightCount);\n};\n\nconst longestUnivaluePath = function(root) {\n let longest = { max: 0 };\n getCount(root, longest);\n return longest.max;\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720c24", + "questionid": 345, + "title": "Max Area of Island", + "slug": "max-area-of-island", + "description": "You are given an m x n binary matrix grid. An island is a group of 1's (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water. The area of an island is the number of cells with a value 1 in the island. Return the maximum area of an island in grid. If there is no island, return 0. ", + "category": [ + "Array", + "Depth-First Search", + "Breadth-First Search", + "Union Find", + "Matrix" + ], + "complexity": "Medium", + "successrate": 69.6, + "totalsubmissions": 648302, + "totalaccepted": 450928, + "likes": 5777, + "dislikes": 144, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "grid = [[0,0,1,0,0,0,0,1,0,0,0,0,0],[0,0,0,0,0,0,0,1,1,1,0,0,0],[0,1,1,0,1,0,0,0,0,0,0,0,0],[0,1,0,0,1,1,0,0,1,0,1,0,0],[0,1,0,0,1,1,0,0,1,1,1,0,0],[0,0,0,0,0,0,0,0,0,0,1,0,0],[0,0,0,0,0,0,0,1,1,1,0,0,0],[0,0,0,0,0,0,0,1,1,0,0,0,0]]", + "expected_output": "6", + "explanation": "The answer is not 11, because the island must be connected 4-directionally." + }, + { + "example_num": 2, + "expected_input": "grid = [[0,0,0,0,0,0,0,0]]", + "expected_output": "0", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[][]} grid\n * @return {number}\n */\nconst maxAreaOfIsland = function(grid) {\n let res = 0\n const seen = []\n for(let i = 0; i < grid.length; i++) {\n seen[i] = []\n }\n for(let i = 0; i < grid.length; i++) {\n for(let j = 0; j < grid[0].length; j++) {\n res = Math.max(res, area(i, j, seen, grid))\n }\n }\n return res\n};\n\nfunction area(r, c, seen, grid) {\n console.log(grid)\n if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || seen[r][c] || grid[r][c] == 0) return 0;\n seen[r][c] = true;\n return (1 + area(r+1, c, seen, grid) + area(r-1, c, seen, grid) + area(r, c-1, seen, grid) + area(r, c+1, seen, grid));\n}\n\nconsole.log(maxAreaOfIsland([[1,1,0,0,0],[1,1,0,0,0],[0,0,0,1,1],[0,0,0,1,1]]))\nconsole.log(maxAreaOfIsland([[1,0],[1,1]]))\nconsole.log(maxAreaOfIsland([[1,1],[1,0]]))\n" + }, + { + "_id": "66f925ddfdfb8e1665720c30", + "questionid": 357, + "title": "Count Different Palindromic Subsequences", + "slug": "count-different-palindromic-subsequences", + "description": "Given a string s, return the number of different non-empty palindromic subsequences in s. Since the answer may be very large, return it modulo 109 + 7. A subsequence of a string is obtained by deleting zero or more characters from the string. A sequence is palindromic if it is equal to the sequence reversed. Two sequences a1, a2, ... and b1, b2, ... are different if there is some i for which ai != bi. ", + "category": [ + "String", + "Dynamic Programming" + ], + "complexity": "Hard", + "successrate": 44.3, + "totalsubmissions": 59687, + "totalaccepted": 26437, + "likes": 1270, + "dislikes": 68, + "hints": "Let dp(i, j) be the answer for the string T = S[i:j+1] including the empty sequence. The answer is the number of unique characters in T, plus palindromes of the form \"a_a\", \"b_b\", \"c_c\", and \"d_d\", where \"_\" represents zero or more characters.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "bccb"", + "expected_output": "6", + "explanation": "The 6 different non-empty palindromic subsequences are 'b', 'c', 'bb', 'cc', 'bcb', 'bccb'.\nNote that 'bcb' is counted only once, even though it occurs twice." + }, + { + "example_num": 2, + "expected_input": "s = "abcdabcdabcdabcdabcdabcdabcdabcddcbadcbadcbadcbadcbadcbadcbadcba"", + "expected_output": "104860361", + "explanation": "There are 3104860382 different non-empty palindromic subsequences, which is 104860361 modulo 109 + 7." + } + ], + "solution": "/**\n * @param {string} S\n * @return {number}\n */\nconst countPalindromicSubsequences = function(S) {\n const len = S.length\n const dp = Array.from({ length: len }, () => new Array(len).fill(0))\n const mod = 10 ** 9 + 7\n for (let i = 0; i < len; i++) dp[i][i] = 1\n for (let distance = 1; distance < len; distance++) {\n for (let i = 0; i < len - distance; i++) {\n let j = i + distance\n if (S[i] === S[j]) {\n let low = i + 1\n let high = j - 1\n while (low <= high && S[low] != S[j]) low++\n while (low <= high && S[high] != S[j]) high--\n if (low > high) {\n dp[i][j] = dp[i + 1][j - 1] * 2 + 2\n } else if (low == high) {\n dp[i][j] = dp[i + 1][j - 1] * 2 + 1\n } else {\n dp[i][j] = dp[i + 1][j - 1] * 2 - dp[low + 1][high - 1]\n }\n } else {\n dp[i][j] = dp[i][j - 1] + dp[i + 1][j] - dp[i + 1][j - 1]\n }\n dp[i][j] = dp[i][j] < 0 ? dp[i][j] + mod : dp[i][j] % mod\n }\n }\n return dp[0][len - 1]\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720c31", + "questionid": 358, + "title": "Flood Fill", + "slug": "flood-fill", + "description": "An image is represented by an m x n integer grid image where image[i][j] represents the pixel value of the image. You are also given three integers sr, sc, and newColor. You should perform a flood fill on the image starting from the pixel image[sr][sc]. To perform a flood fill, consider the starting pixel, plus any pixels connected 4-directionally to the starting pixel of the same color as the starting pixel, plus any pixels connected 4-directionally to those pixels (also with the same color), and so on. Replace the color of all of the aforementioned pixels with newColor. Return the modified image after performing the flood fill. ", + "category": [ + "Array", + "Depth-First Search", + "Breadth-First Search", + "Matrix" + ], + "complexity": "Easy", + "successrate": 58.2, + "totalsubmissions": 673313, + "totalaccepted": 391611, + "likes": 3924, + "dislikes": 373, + "hints": "Write a recursive function that paints the pixel if it's the correct color, then recurses on neighboring pixels.", + "deleted": false, + "examples": [], + "solution": "/**\n * @param {number[][]} image\n * @param {number} sr\n * @param {number} sc\n * @param {number} newColor\n * @return {number[][]}\n */\nconst floodFill = function(image, sr, sc, newColor, firstColor = image[sr][sc]) {\n if (\n sr < 0 ||\n sc < 0 ||\n sr >= image.length ||\n sc >= image[sr].length ||\n image[sr][sc] !== firstColor ||\n image[sr][sc] === newColor\n ) {\n return image\n }\n\n image[sr][sc] = newColor\n\n floodFill(image, sr + 1, sc, newColor, firstColor)\n floodFill(image, sr - 1, sc, newColor, firstColor)\n floodFill(image, sr, sc + 1, newColor, firstColor)\n floodFill(image, sr, sc - 1, newColor, firstColor)\n\n return image\n}\n\n// another\n\n/**\n * @param {number[][]} image\n * @param {number} sr\n * @param {number} sc\n * @param {number} newColor\n * @return {number[][]}\n */\nconst floodFill = function (\n image,\n sr,\n sc,\n newColor,\n firstColor = image[sr][sc]\n) {\n const dirs = [0, -1, 0, 1, 0]\n const rows = image.length\n const cols = image[0].length\n const q = [[sr, sc]]\n while (q.length) {\n const len = q.length\n for (let i = 0; i < len; i++) {\n const cur = q.shift()\n image[cur[0]][cur[1]] = newColor\n for (let j = 0; j < 4; j++) {\n const [nr, nc] = [cur[0] + dirs[j], cur[1] + dirs[j + 1]]\n if (\n nr >= 0 &&\n nr < rows &&\n nc >= 0 &&\n nc < cols &&\n image[nr][nc] === firstColor &&\n image[nr][nc] !== newColor\n ) {\n q.push([nr, nc])\n }\n }\n }\n }\n return image\n}\n\n" + }, + { + "_id": "66f925ddfdfb8e1665720c33", + "questionid": 360, + "title": "Parse Lisp Expression", + "slug": "parse-lisp-expression", + "description": "You are given a string expression representing a Lisp-like expression to return the integer value of. The syntax for these expressions is given as follows. ", + "category": [ + "Hash Table", + "String", + "Stack", + "Recursion" + ], + "complexity": "Hard", + "successrate": 51.2, + "totalsubmissions": 35889, + "totalaccepted": 18389, + "likes": 386, + "dislikes": 304, + "hints": "* If the expression starts with a digit or '-', it's an integer: return it.\r\n\r\n* If the expression starts with a letter, it's a variable. Recall it by checking the current scope in reverse order.\r\n\r\n* Otherwise, group the tokens (variables or expressions) within this expression by counting the \"balance\" `bal` of the occurrences of `'('` minus the number of occurrences of `')'`. When the balance is zero, we have ended a token. For example, `(add 1 (add 2 3))` should have tokens `'1'` and `'(add 2 3)'`.\r\n\r\n* For add and mult expressions, evaluate each token and return the addition or multiplication of them.\r\n\r\n* For let expressions, evaluate each expression sequentially and assign it to the variable in the current scope, then return the evaluation of the final expression.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "expression = "(let x 2 (mult x (let x 3 y 4 (add x y))))"", + "expected_output": "14", + "explanation": "In the expression (add x y), when checking for the value of the variable x,\nwe check from the innermost scope to the outermost in the context of the variable we are trying to evaluate.\nSince x = 3 is found first, the value of x is 3." + }, + { + "example_num": 2, + "expected_input": "expression = "(let x 3 x 2 x)"", + "expected_output": "2", + "explanation": "Assignment in let statements is processed sequentially." + }, + { + "example_num": 3, + "expected_input": "expression = "(let x 1 y 2 x (add x y) (add x y))"", + "expected_output": "5", + "explanation": "The first (add x y) evaluates as 3, and is assigned to x.\nThe second (add x y) evaluates as 3+2 = 5." + } + ], + "solution": "/**\n * @param {string} expression\n * @return {number}\n */\nconst evaluate = (x) =>\n e(\n JSON.parse(\n x.replace(/[() ]|([a-z][a-z0-9]*)/g, (m) =>\n m === '(' ? '[' : m === ')' ? ']' : m === ' ' ? ',' : `\"${m}\"`\n )\n )\n )\nconst e = (x, v = []) =>\n ({\n string: () => v.find((y) => y[0] === x)[1],\n number: () => x,\n object: () =>\n ({\n add: () => e(x[1], v) + e(x[2], v),\n mult: () => e(x[1], v) * e(x[2], v),\n let: () =>\n e(\n x[x.length - 1],\n x\n .slice(1, -1)\n .reduce(\n ({ v, t }, z) =>\n t ? { v: [[t, e(z, v)], ...v] } : { v, t: z },\n { v }\n ).v\n ),\n }[x[0]]()),\n }[typeof x]())\n\n// another\n\n/**\n * @param {string} expression\n * @return {number}\n */\nconst evaluate = function (expression) {\n const tokens = tokenizer(expression)\n let i = 0\n function exec(scope) {\n let value = null\n const next = tokens[i++]\n if (next === '(') {\n scope = enter(scope)\n switch (tokens[i++]) {\n case 'add':\n const a = exec(scope)\n const b = exec(scope)\n value = a + b\n break\n case 'mult':\n const x = exec(scope)\n const y = exec(scope)\n value = x * y\n break\n case 'let':\n while (tokens[i] !== '(' && tokens[i + 1] !== ')') {\n scope.variables[tokens[i++]] = exec(scope)\n }\n value = exec(scope)\n break\n }\n scope = exit(scope)\n i++\n } else if (isNumber(next)) {\n value = Number(next)\n } else {\n // Find variable in current scope otherwise go to parent\n let t = scope\n while (t) {\n if (next in t.variables) {\n value = t.variables[next]\n break\n }\n t = t.parent\n }\n }\n return value\n }\n return exec(newScope())\n}\nfunction tokenizer(expression) {\n const tokens = []\n let token = ''\n for (const c of expression) {\n if (c === '(' || c === ')') {\n if (token) tokens.push(token)\n tokens.push(c)\n token = ''\n } else if (c === ' ') {\n if (token) tokens.push(token)\n token = ''\n } else {\n token += c\n }\n }\n if (token) {\n tokens.push(token)\n }\n return tokens\n}\nfunction isNumber(n) {\n return !isNaN(n)\n}\nfunction newScope() {\n return { parent: null, variables: {} }\n}\nfunction enter(scope) {\n const next = newScope()\n next.parent = scope\n return next\n}\nfunction exit(scope) {\n return scope.parent\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720c39", + "questionid": 366, + "title": "Min Cost Climbing Stairs", + "slug": "min-cost-climbing-stairs", + "description": "You are given an integer array cost where cost[i] is the cost of ith step on a staircase. Once you pay the cost, you can either climb one or two steps. You can either start from the step with index 0, or the step with index 1. Return the minimum cost to reach the top of the floor. ", + "category": [ + "Array", + "Dynamic Programming" + ], + "complexity": "Easy", + "successrate": 58.6, + "totalsubmissions": 769739, + "totalaccepted": 450967, + "likes": 5723, + "dislikes": 992, + "hints": "Say f[i] is the final cost to climb to the top from step i. Then f[i] = cost[i] + min(f[i+1], f[i+2]).", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "cost = [10,15,20]", + "expected_output": "15", + "explanation": "You will start at index 1.\n- Pay 15 and climb two steps to reach the top.\nThe total cost is 15." + }, + { + "example_num": 2, + "expected_input": "cost = [1,100,1,1,1,100,1,1,100,1]", + "expected_output": "6", + "explanation": "You will start at index 0.\n- Pay 1 and climb two steps to reach index 2.\n- Pay 1 and climb two steps to reach index 4.\n- Pay 1 and climb two steps to reach index 6.\n- Pay 1 and climb one step to reach index 7.\n- Pay 1 and climb two steps to reach index 9.\n- Pay 1 and climb one step to reach the top.\nThe total cost is 6." + } + ], + "solution": "/**\n * @param {number[]} cost\n * @return {number}\n */\nconst minCostClimbingStairs = function(cost) {\n let f1 = cost[0];\n let f2 = cost[1];\n for (let i = 2; i < cost.length; i++) {\n let f_cur = cost[i] + Math.min(f1, f2);\n f1 = f2;\n f2 = f_cur;\n }\n return Math.min(f1, f2);\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720c48", + "questionid": 381, + "title": "N-ary Tree Postorder Traversal", + "slug": "n-ary-tree-postorder-traversal", + "description": "Given the root of an n-ary tree, return the postorder traversal of its nodes' values. Nary-Tree input serialization is represented in their level order traversal. Each group of children is separated by the null value (See examples) ", + "category": [ + "Stack", + "Tree", + "Depth-First Search" + ], + "complexity": "Easy", + "successrate": 76.1, + "totalsubmissions": 234316, + "totalaccepted": 178336, + "likes": 1553, + "dislikes": 82, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [1,null,3,2,4,null,5,6]", + "expected_output": "[5,6,3,2,4,1]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]", + "expected_output": "[2,6,14,11,7,3,12,8,4,13,9,10,5,1]", + "explanation": "" + } + ], + "solution": "/**\n * // Definition for a Node.\n * function Node(val,children) {\n * this.val = val;\n * this.children = children;\n * };\n */\n/**\n * @param {Node} root\n * @return {number[]}\n */\nconst postorder = function(root) {\n const res = []\n traverse(root, res)\n return res\n};\n\nfunction traverse(node, res) {\n if(node == null) return\n for(let i = 0; i < node.children.length; i++) {\n traverse(node.children[i], res)\n }\n res.push(node.val)\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720c50", + "questionid": 389, + "title": "Sliding Puzzle", + "slug": "sliding-puzzle", + "description": "On an 2 x 3 board, there are five tiles labeled from 1 to 5, and an empty square represented by 0. A move consists of choosing 0 and a 4-directionally adjacent number and swapping it. The state of the board is solved if and only if the board is [[1,2,3],[4,5,0]]. Given the puzzle board board, return the least number of moves required so that the state of the board is solved. If it is impossible for the state of the board to be solved, return -1. ", + "category": [ + "Array", + "Breadth-First Search", + "Matrix" + ], + "complexity": "Hard", + "successrate": 63.1, + "totalsubmissions": 111608, + "totalaccepted": 70414, + "likes": 1461, + "dislikes": 37, + "hints": "Perform a breadth-first-search, where the nodes are the puzzle boards and edges are if two puzzle boards can be transformed into one another with one move.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "board = [[1,2,3],[4,0,5]]", + "expected_output": "1", + "explanation": "Swap the 0 and the 5 in one move." + }, + { + "example_num": 2, + "expected_input": "board = [[1,2,3],[5,4,0]]", + "expected_output": "-1", + "explanation": "No number of moves will make the board solved." + }, + { + "example_num": 3, + "expected_input": "board = [[4,1,2],[5,0,3]]", + "expected_output": "5", + "explanation": "5 is the smallest number of moves that solves the board.\nAn example path:\nAfter move 0: [[4,1,2],[5,0,3]]\nAfter move 1: [[4,1,2],[0,5,3]]\nAfter move 2: [[0,1,2],[4,5,3]]\nAfter move 3: [[1,0,2],[4,5,3]]\nAfter move 4: [[1,2,0],[4,5,3]]\nAfter move 5: [[1,2,3],[4,5,0]]" + } + ], + "solution": "/**\n * @param {number[][]} board\n * @return {number}\n */\nconst slidingPuzzle = function(board) {\n const target = \"123450\";\n let start = \"\";\n for (let i = 0; i < board.length; i++) {\n for (let j = 0; j < board[0].length; j++) {\n start += board[i][j];\n }\n }\n const visited = {};\n // all the positions 0 can be swapped to\n const dirs = [[1, 3], [0, 2, 4], [1, 5], [0, 4], [1, 3, 5], [2, 4]];\n const queue = [];\n queue.push(start);\n visited[start] = true;\n let res = 0;\n while (queue.length !== 0) {\n // level count, has to use size control here, otherwise not needed\n let size = queue.length;\n for (let i = 0; i < size; i++) {\n let cur = queue.shift();\n if (cur === target) {\n return res;\n }\n let zero = cur.indexOf(\"0\");\n // swap if possible\n for (let dir of dirs[zero]) {\n let next = swap(cur, zero, dir);\n if (visited.hasOwnProperty(next)) {\n continue;\n }\n visited[next] = true;\n queue.push(next);\n }\n }\n res++;\n }\n return -1;\n};\n\nfunction swap(str, i, j) {\n const arr = str.split(\"\");\n const ic = str[i];\n const jc = str[j];\n arr.splice(i, 1, jc);\n arr.splice(j, 1, ic);\n return arr.join(\"\");\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720c4c", + "questionid": 385, + "title": "Max Chunks To Make Sorted", + "slug": "max-chunks-to-make-sorted", + "description": "You are given an integer array arr of length n that represents a permutation of the integers in the range [0, n - 1]. We split arr into some number of chunks (i.e., partitions), and individually sort each chunk. After concatenating them, the result should equal the sorted array. Return the largest number of chunks we can make to sort the array. ", + "category": [ + "Array", + "Stack", + "Greedy", + "Sorting", + "Monotonic Stack" + ], + "complexity": "Medium", + "successrate": 57.6, + "totalsubmissions": 122156, + "totalaccepted": 70386, + "likes": 1828, + "dislikes": 182, + "hints": "The first chunk can be found as the smallest k for which A[:k+1] == [0, 1, 2, ...k]; then we repeat this process.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "arr = [4,3,2,1,0]", + "expected_output": "1", + "explanation": "Splitting into two or more chunks will not return the required result.\nFor example, splitting into [4, 3], [2, 1, 0] will result in [3, 4, 0, 1, 2], which isn't sorted." + }, + { + "example_num": 2, + "expected_input": "arr = [1,0,2,3,4]", + "expected_output": "4", + "explanation": "We can split into two chunks, such as [1, 0], [2, 3, 4].\nHowever, splitting into [1, 0], [2], [3], [4] is the highest number of chunks possible." + } + ], + "solution": "/**\n * @param {number[]} arr\n * @return {number}\n */\nconst maxChunksToSorted = function(arr) {\n let res = 0;\n let max = 0;\n for (let i = 0; i < arr.length; i++) {\n max = Math.max(max, arr[i]);\n if (max === i) res += 1;\n }\n return res;\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720c54", + "questionid": 393, + "title": "K-th Symbol in Grammar", + "slug": "k-th-symbol-in-grammar", + "description": "We build a table of n rows (1-indexed). We start by writing 0 in the 1st row. Now in every subsequent row, we look at the previous row and replace each occurrence of 0 with 01, and each occurrence of 1 with 10. Given two integer n and k, return the kth (1-indexed) symbol in the nth row of a table of n rows. ", + "category": [ + "Math", + "Bit Manipulation", + "Recursion" + ], + "complexity": "Medium", + "successrate": 39.9, + "totalsubmissions": 208528, + "totalaccepted": 83191, + "likes": 1671, + "dislikes": 246, + "hints": "Try to represent the current (N, K) in terms of some (N-1, prevK). What is prevK ?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 1, k = 1", + "expected_output": "0", + "explanation": "row 1: 0" + }, + { + "example_num": 2, + "expected_input": "n = 2, k = 1", + "expected_output": "0", + "explanation": "row 1: 0\nrow 2: 01" + }, + { + "example_num": 3, + "expected_input": "n = 2, k = 2", + "expected_output": "1", + "explanation": "row 1: 0\nrow 2: 01" + } + ], + "solution": "/**\n * @param {number} N\n * @param {number} K\n * @return {number}\n */\nconst kthGrammar = function(N, K) {\n\tif (N === 1) return 0;\n\tif (K % 2 === 0) return (kthGrammar(N - 1, K / 2) === 0) ? 1 : 0;\n\telse return (kthGrammar(N - 1, (K + 1) / 2) === 0) ? 0 : 1;\n};\n\n/**\n\n// think of the problem like this\n/* 0\n / \\\n 0 1\n / \\ / \\\n 0 1 1 0\n / \\ / \\ / \\ / \\\n 0 1 1 0 1 0 0 1\n*/\n\n*/\n" + }, + { + "_id": "66f925ddfdfb8e1665720c56", + "questionid": 395, + "title": "Rabbits in Forest", + "slug": "rabbits-in-forest", + "description": "There is a forest with an unknown number of rabbits. We asked n rabbits \"How many rabbits have the same color as you?\" and collected the answers in an integer array answers where answers[i] is the answer of the ith rabbit. Given the array answers, return the minimum number of rabbits that could be in the forest. ", + "category": [ + "Array", + "Hash Table", + "Math", + "Greedy" + ], + "complexity": "Medium", + "successrate": 55.7, + "totalsubmissions": 64908, + "totalaccepted": 36151, + "likes": 709, + "dislikes": 484, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "answers = [1,1,2]", + "expected_output": "5", + "explanation": "The two rabbits that answered "1" could both be the same color, say red.\nThe rabbit that answered "2" can't be red or the answers would be inconsistent.\nSay the rabbit that answered "2" was blue.\nThen there should be 2 other blue rabbits in the forest that didn't answer into the array.\nThe smallest possible number of rabbits in the forest is therefore 5: 3 that answered plus 2 that didn't." + }, + { + "example_num": 2, + "expected_input": "answers = [10,10,10]", + "expected_output": "11", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} answers\n * @return {number}\n */\nconst numRabbits = function(answers) {\n const h = {}\n for(const e of answers) {\n if(h[e] == null) h[e] = 0\n h[e]++\n }\n let res = 0\n for(let [k,v] of Object.entries(h)) {\n k = +k\n if(k >= v ) res += k + 1\n else {\n res += Math.ceil(v / (k + 1) ) * (k + 1)\n }\n }\n \n return res\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720c60", + "questionid": 405, + "title": "Rotate String", + "slug": "rotate-string", + "description": "Given two strings s and goal, return true if and only if s can become goal after some number of shifts on s. A shift on s consists of moving the leftmost character of s to the rightmost position. ", + "category": [ + "String", + "String Matching" + ], + "complexity": "Easy", + "successrate": 52.1, + "totalsubmissions": 277996, + "totalaccepted": 144895, + "likes": 1783, + "dislikes": 84, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = \"abcde\", goal = \"cdeab\"", + "expected_output": "true", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "s = \"abcde\", goal = \"abced\"", + "expected_output": "false", + "explanation": "" + } + ], + "solution": "/**\n * @param {string} A\n * @param {string} B\n * @return {boolean}\n */\nconst rotateString = function(A, B) {\n if (A.length != B.length) return false;\n return A.concat(A).includes(B);\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720c61", + "questionid": 406, + "title": "Smallest Rotation with Highest Score", + "slug": "smallest-rotation-with-highest-score", + "description": "You are given an array nums. You can rotate it by a non-negative integer k so that the array becomes [nums[k], nums[k + 1], ... nums[nums.length - 1], nums[0], nums[1], ..., nums[k-1]]. Afterward, any entries that are less than or equal to their index are worth one point. Return the rotation index k that corresponds to the highest score we can achieve if we rotated nums by it. If there are multiple answers, return the smallest such index k. ", + "category": [ + "Array", + "Prefix Sum" + ], + "complexity": "Hard", + "successrate": 47.4, + "totalsubmissions": 18253, + "totalaccepted": 8659, + "likes": 351, + "dislikes": 21, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [2,3,1,4,0]", + "expected_output": "3", + "explanation": "Scores for each k are listed below: \nk = 0, nums = [2,3,1,4,0], score 2\nk = 1, nums = [3,1,4,0,2], score 3\nk = 2, nums = [1,4,0,2,3], score 3\nk = 3, nums = [4,0,2,3,1], score 4\nk = 4, nums = [0,2,3,1,4], score 3\nSo we should choose k = 3, which has the highest score." + }, + { + "example_num": 2, + "expected_input": "nums = [1,3,0,2,4]", + "expected_output": "0", + "explanation": "nums will always have 3 points no matter how it shifts.\nSo we will choose the smallest k, which is 0." + } + ], + "solution": "/**\n * @param {number[]} A\n * @return {number}\n */\nconst bestRotation = function(A) {\n const N = A.length\n const bad = new Array(N).fill(0)\n for (let i = 0; i < N; ++i) {\n let left = (i - A[i] + 1 + N) % N\n let right = (i + 1) % N\n bad[left]--\n bad[right]++\n if (left > right) bad[0]--\n }\n\n let best = -N\n let ans = 0,\n cur = 0\n for (let i = 0; i < N; ++i) {\n cur += bad[i]\n if (cur > best) {\n best = cur\n ans = i\n }\n }\n return ans\n}\n\n// another\n\n/**\n * @param {number[]} nums\n * @return {number}\n */\nvar bestRotation = function(nums) {\n const n = nums.length\n const arr = Array(n).fill(0)\n for(let i = 0; i < n; i++) {\n arr[(i - nums[i] + 1 + n) % n] -= 1\n }\n let res = 0\n for(let i = 1; i < n; i++) {\n arr[i] += arr[i - 1] + 1\n if(arr[i] > arr[res]) res = i\n }\n return res\n};\n\n\n" + }, + { + "_id": "66f925ddfdfb8e1665720c67", + "questionid": 412, + "title": "Chalkboard XOR Game", + "slug": "chalkboard-xor-game", + "description": "You are given an array of integers nums represents the numbers written on a chalkboard. Alice and Bob take turns erasing exactly one number from the chalkboard, with Alice starting first. If erasing a number causes the bitwise XOR of all the elements of the chalkboard to become 0, then that player loses. The bitwise XOR of one element is that element itself, and the bitwise XOR of no elements is 0. Also, if any player starts their turn with the bitwise XOR of all the elements of the chalkboard equal to 0, then that player wins. Return true if and only if Alice wins the game, assuming both players play optimally. ", + "category": [ + "Array", + "Math", + "Bit Manipulation", + "Brainteaser", + "Game Theory" + ], + "complexity": "Hard", + "successrate": 53.3, + "totalsubmissions": 12094, + "totalaccepted": 6444, + "likes": 126, + "dislikes": 235, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,1,2]", + "expected_output": "false", + "explanation": "Alice has two choices: erase 1 or erase 2. \nIf she erases 1, the nums array becomes [1, 2]. The bitwise XOR of all the elements of the chalkboard is 1 XOR 2 = 3. Now Bob can remove any element he wants, because Alice will be the one to erase the last element and she will lose. \nIf Alice erases 2 first, now nums become [1, 1]. The bitwise XOR of all the elements of the chalkboard is 1 XOR 1 = 0. Alice will lose." + }, + { + "example_num": 2, + "expected_input": "nums = [0,1]", + "expected_output": "true", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "nums = [1,2,3]", + "expected_output": "true", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} nums\n * @return {boolean}\n */\nconst xorGame = function(nums) {\n const xor = nums.reduce((xor,ele) => xor^ele, 0)\n return xor === 0 || (nums.length & 1) === 0\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720c6a", + "questionid": 415, + "title": "Largest Sum of Averages", + "slug": "largest-sum-of-averages", + "description": "You are given an integer array nums and an integer k. You can partition the array into at most k non-empty adjacent subarrays. The score of a partition is the sum of the averages of each subarray. Note that the partition must use every integer in nums, and that the score is not necessarily an integer. Return the maximum score you can achieve of all the possible partitions. Answers within 10-6 of the actual answer will be accepted. ", + "category": [ + "Array", + "Dynamic Programming" + ], + "complexity": "Medium", + "successrate": 52.4, + "totalsubmissions": 75480, + "totalaccepted": 39546, + "likes": 1547, + "dislikes": 76, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [9,1,2,3,9], k = 3", + "expected_output": "20.00000", + "explanation": "The best choice is to partition nums into [9], [1, 2, 3], [9]. The answer is 9 + (1 + 2 + 3) / 3 + 9 = 20.\nWe could have also partitioned nums into [9, 1], [2], [3, 9], for example.\nThat partition would lead to a score of 5 + 2 + 6 = 13, which is worse." + }, + { + "example_num": 2, + "expected_input": "nums = [1,2,3,4,5,6,7], k = 4", + "expected_output": "20.50000", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} A\n * @param {number} K\n * @return {number}\n */\nconst largestSumOfAverages = function(A, K) {\n const len = A.length\n const P = [0]\n for(let i = 0; i < len; i++) {\n P[i+1] = (P[i] || 0) + A[i]\n }\n const dp = []\n for(let j = 0; j < len; j++) {\n dp[j] = (P[len] - P[j]) / (len - j)\n }\n for(let m = 0; m < K - 1; m++) {\n for(let n = 0; n < len; n++) {\n for(let k = n + 1; k < len; k++) {\n dp[n] = Math.max(dp[n], (P[k] - P[n]) / (k - n) + dp[k])\n }\n }\n }\n return dp[0]\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720c6d", + "questionid": 418, + "title": "Ambiguous Coordinates", + "slug": "ambiguous-coordinates", + "description": "We had some 2-dimensional coordinates, like \"(1, 3)\" or \"(2, 0.5)\". Then, we removed all commas, decimal points, and spaces and ended up with the string s. Return a list of strings representing all possibilities for what our original coordinates could have been. Our original representation never had extraneous zeroes, so we never started with numbers like \"00\", \"0.0\", \"0.00\", \"1.0\", \"001\", \"00.01\", or any other number that can be represented with fewer digits. Also, a decimal point within a number never occurs without at least one digit occurring before it, so we never started with numbers like \".1\". The final answer list can be returned in any order. All coordinates in the final answer have exactly one space between them (occurring after the comma.) ", + "category": [ + "String", + "Backtracking" + ], + "complexity": "Medium", + "successrate": 55.9, + "totalsubmissions": 45529, + "totalaccepted": 25467, + "likes": 251, + "dislikes": 588, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "(123)"", + "expected_output": "["(1, 2.3)","(1, 23)","(1.2, 3)","(12, 3)"]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "s = "(0123)"", + "expected_output": "["(0, 1.23)","(0, 12.3)","(0, 123)","(0.1, 2.3)","(0.1, 23)","(0.12, 3)"]", + "explanation": "0.0, 00, 0001 or 00.01 are not allowed." + }, + { + "example_num": 3, + "expected_input": "s = "(00011)"", + "expected_output": "["(0, 0.011)","(0.001, 1)"]", + "explanation": "" + } + ], + "solution": null + }, + { + "_id": "66f925ddfdfb8e1665720c71", + "questionid": 422, + "title": "Card Flipping Game", + "slug": "card-flipping-game", + "description": "You are given n cards, with a positive integer printed on the front and back of each card (possibly different). You can flip any number of cards (possibly zero). After choosing the front and the back of each card, you will pick each card, and if the integer printed on the back of this card is not printed on the front of any other card, then this integer is good. You are given two integer array fronts and backs where fronts[i] and backs[i] are the integers printer on the front and the back of the ith card respectively. Return the smallest good and integer after flipping the cards. If there are no good integers, return 0. Note that a flip swaps the front and back numbers, so the value on the front is now on the back and vice versa. ", + "category": [ + "Array", + "Hash Table" + ], + "complexity": "Medium", + "successrate": 44.6, + "totalsubmissions": 28904, + "totalaccepted": 12902, + "likes": 110, + "dislikes": 628, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "fronts = [1,2,4,4,7], backs = [1,3,4,1,3]", + "expected_output": "2", + "explanation": "If we flip the second card, the face up numbers are [1,3,4,4,7] and the face down are [1,2,4,1,3].\n2 is the minimum good integer as it appears facing down but not facing up.\nIt can be shown that 2 is the minimum possible good integer obtainable after flipping some cards." + }, + { + "example_num": 2, + "expected_input": "fronts = [1], backs = [1]", + "expected_output": "0", + "explanation": "There are no good integers no matter how we flip the cards, so we return 0." + } + ], + "solution": null + }, + { + "_id": "66f925ddfdfb8e1665720c7c", + "questionid": 433, + "title": "Magic Squares In Grid", + "slug": "magic-squares-in-grid", + "description": "A 3 x 3 magic square is a 3 x 3 grid filled with distinct numbers from 1 to 9 such that each row, column, and both diagonals all have the same sum. Given a row x col\u00a0grid\u00a0of integers, how many 3 x 3 \"magic square\" subgrids are there?\u00a0 (Each subgrid is contiguous). ", + "category": [ + "Array", + "Math", + "Matrix" + ], + "complexity": "Medium", + "successrate": 38.3, + "totalsubmissions": 83432, + "totalaccepted": 31992, + "likes": 245, + "dislikes": 1450, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "grid = [[4,3,8,4],[9,5,1,9],[2,7,6,2]]", + "expected_output": "1\nExplanation: \nThe following subgrid is a 3 x 3 magic square:\n\"\"\nwhile this one is not:\n\"\"\nIn total, there is only one magic square inside the given grid.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "grid = [[8]]", + "expected_output": "0", + "explanation": "" + } + ], + "solution": null + }, + { + "_id": "66f925ddfdfb8e1665720c7e", + "questionid": 435, + "title": "Guess the Word", + "slug": "guess-the-word", + "description": "This is an interactive problem. You are given an array of unique strings wordlist where wordlist[i] is 6 letters long, and one word in this list is chosen as secret. You may call Master.guess(word) to guess a word. The guessed word should have type string and must be from the original list with 6 lowercase letters. This function returns an integer type, representing the number of exact matches (value and position) of your guess to the secret word. Also, if your guess is not in the given wordlist, it will return -1 instead. For each test case, you have exactly 10 guesses to guess the word. At the end of any number of calls, if you have made 10 or fewer calls to Master.guess and at least one of these guesses was secret, then you pass the test case. ", + "category": [ + "Array", + "Math", + "String", + "Interactive", + "Game Theory" + ], + "complexity": "Hard", + "successrate": 43.1, + "totalsubmissions": 263498, + "totalaccepted": 113453, + "likes": 1196, + "dislikes": 1331, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "secret = "acckzz", words = ["acckzz","ccbazz","eiowzz","abcczz"], allowedGuesses = 10", + "expected_output": "You guessed the secret word correctly.", + "explanation": "master.guess("aaaaaa") returns -1, because "aaaaaa" is not in wordlist.\nmaster.guess("acckzz") returns 6, because "acckzz" is secret and has all 6 matches.\nmaster.guess("ccbazz") returns 3, because "ccbazz" has 3 matches.\nmaster.guess("eiowzz") returns 2, because "eiowzz" has 2 matches.\nmaster.guess("abcczz") returns 4, because "abcczz" has 4 matches.\nWe made 5 calls to master.guess, and one of them was the secret, so we pass the test case." + }, + { + "example_num": 2, + "expected_input": "secret = "hamada", words = ["hamada","khaled"], allowedGuesses = 10", + "expected_output": "You guessed the secret word correctly.", + "explanation": "Since there are two words, you can guess both." + } + ], + "solution": "/**\n * // This is the master's API interface.\n * // You should not implement it, or speculate about its implementation\n * function Master() {\n *\n * @param {string[]} wordlist\n * @param {Master} master\n * @return {integer}\n * this.guess = function(word) {\n * ...\n * };\n * };\n */\n/**\n * @param {string[]} wordlist\n * @param {Master} master\n * @return {void}\n */\nconst findSecretWord = function (wordlist, master) {\n let group = wordlist\n for (let i = 0; i < 10; i++) {\n let currentGuess = findTheTypical(group)\n let res = master.guess(currentGuess)\n if (res === 6) return\n let tmp = []\n for (let j = 0; j < group.length; j++) {\n if (diff(group[j], currentGuess) === 6 - res) tmp.push(group[j])\n }\n group = tmp\n }\n}\nfunction findTheTypical(wordlist) {\n const count = Array.from({ length: 6 }, (x) => new Object())\n for (let i = 0; i < wordlist.length; i++) {\n for (let j = 0; j < 6; j++) {\n const cur = wordlist[i][j]\n if (count[j][cur] === undefined) count[j][cur] = 1\n else count[j][cur]++\n }\n }\n let maxPos = 0,\n maxCount = 0,\n maxAlp = ''\n for (let i = 0; i < 6; i++) {\n for (let k of Object.keys(count[i])) {\n if (count[i][k] > maxCount) {\n maxCount = count[i][k]\n maxPos = i\n maxAlp = k\n }\n }\n }\n for (let i = 0; i < wordlist.length; i++) {\n if (wordlist[i][maxPos] === maxAlp) return wordlist[i]\n }\n}\nfunction diff(a, b) {\n let count = 0\n for (let i = 0; i < a.length; i++) {\n if (a[i] !== b[i]) count++\n }\n return count\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720c81", + "questionid": 438, + "title": "Shortest Path Visiting All Nodes", + "slug": "shortest-path-visiting-all-nodes", + "description": "You have an undirected, connected graph of n nodes labeled from 0 to n - 1. You are given an array graph where graph[i] is a list of all the nodes connected with node i by an edge. Return the length of the shortest path that visits every node. You may start and stop at any node, you may revisit nodes multiple times, and you may reuse edges. ", + "category": [ + "Dynamic Programming", + "Bit Manipulation", + "Breadth-First Search", + "Graph", + "Bitmask" + ], + "complexity": "Hard", + "successrate": 61.2, + "totalsubmissions": 90353, + "totalaccepted": 55288, + "likes": 2362, + "dislikes": 121, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "graph = [[1,2,3],[0],[0],[0]]", + "expected_output": "4", + "explanation": "One possible path is [1,0,2,0,3]" + }, + { + "example_num": 2, + "expected_input": "graph = [[1],[0,2,4],[1,3,4],[2],[1,2]]", + "expected_output": "4", + "explanation": "One possible path is [0,1,4,2,3]" + } + ], + "solution": "/**\n * @param {number[][]} graph\n * @return {number}\n */\nconst shortestPathLength = function(graph) {\n const N = graph.length\n const dist = Array.from({ length: 1 << N }, () => new Array(N).fill(N * N))\n for (let x = 0; x < N; x++) dist[1 << x][x] = 0\n for (let cover = 0; cover < 1 << N; cover++) {\n let repeat = true\n while (repeat) {\n repeat = false\n for (let head = 0; head < N; head++) {\n let d = dist[cover][head]\n for (let next of graph[head]) {\n let cover2 = cover | (1 << next)\n if (d + 1 < dist[cover2][next]) {\n dist[cover2][next] = d + 1\n if (cover == cover2) repeat = true\n }\n }\n }\n }\n }\n let ans = N * N\n for (let cand of dist[(1 << N) - 1]) ans = Math.min(cand, ans)\n return ans\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720c82", + "questionid": 439, + "title": "Shifting Letters", + "slug": "shifting-letters", + "description": "You are given a string s of lowercase English letters and an integer array shifts of the same length. Call the shift() of a letter, the next letter in the alphabet, (wrapping around so that 'z' becomes 'a'). Now for each shifts[i] = x, we want to shift the first i + 1 letters of s, x times. Return the final string after all such shifts to s are applied. ", + "category": [ + "Array", + "String" + ], + "complexity": "Medium", + "successrate": 45.4, + "totalsubmissions": 157075, + "totalaccepted": 71387, + "likes": 849, + "dislikes": 96, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "abc", shifts = [3,5,9]", + "expected_output": ""rpl"", + "explanation": "We start with "abc".\nAfter shifting the first 1 letters of s by 3, we have "dbc".\nAfter shifting the first 2 letters of s by 5, we have "igc".\nAfter shifting the first 3 letters of s by 9, we have "rpl", the answer." + }, + { + "example_num": 2, + "expected_input": "s = "aaa", shifts = [1,2,3]", + "expected_output": ""gfd"", + "explanation": "" + } + ], + "solution": "/**\n * @param {string} S\n * @param {number[]} shifts\n * @return {string}\n */\nconst shiftingLetters = function(S, shifts) {\n let suffixSum = 0,\n result = \"\";\n for (let i = S.length - 1; i >= 0; i--) {\n suffixSum += shifts[i];\n let ascii = S[i].charCodeAt() - 97;\n result = String.fromCharCode(97 + ((ascii + suffixSum) % 26)) + result;\n }\n return result;\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720c88", + "questionid": 445, + "title": "Mirror Reflection", + "slug": "mirror-reflection", + "description": "There is a special square room with mirrors on each of the four walls. Except for the southwest corner, there are receptors on each of the remaining corners, numbered 0, 1, and 2. The square room has walls of length p\u00a0and a laser ray from the southwest corner first meets the east wall at a distance q from the 0th receptor. Given the two integers p and q, return the number of the receptor that the ray meets first. The test cases are guaranteed so that the ray will meet a receptor eventually. ", + "category": [ + "Math", + "Geometry" + ], + "complexity": "Medium", + "successrate": 59.6, + "totalsubmissions": 44050, + "totalaccepted": 26258, + "likes": 366, + "dislikes": 712, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "p = 2, q = 1", + "expected_output": "2", + "explanation": "The ray meets receptor 2 the first time it gets reflected back to the left wall." + }, + { + "example_num": 2, + "expected_input": "p = 3, q = 1", + "expected_output": "1", + "explanation": "" + } + ], + "solution": "/**\n * @param {number} p\n * @param {number} q\n * @return {number}\n */\nconst mirrorReflection = function(p, q) {\n while (p % 2 === 0 && q % 2 === 0) {\n p /= 2;\n q /= 2;\n }\n\n if (p % 2 === 0) {\n return 2;\n } else if (q % 2 === 0) {\n return 0;\n } else {\n return 1;\n }\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720c4d", + "questionid": 386, + "title": "Jewels and Stones", + "slug": "jewels-and-stones", + "description": "You're given strings jewels representing the types of stones that are jewels, and stones representing the stones you have. Each character in stones is a type of stone you have. You want to know how many of the stones you have are also jewels. Letters are case sensitive, so \"a\" is considered a different type of stone from \"A\". ", + "category": [ + "Hash Table", + "String" + ], + "complexity": "Easy", + "successrate": 87.7, + "totalsubmissions": 832734, + "totalaccepted": 730256, + "likes": 3471, + "dislikes": 484, + "hints": "For each stone, check if it is a jewel.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "jewels = \"aA\", stones = \"aAAbbbb\"", + "expected_output": "3", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "jewels = \"z\", stones = \"ZZ\"", + "expected_output": "0", + "explanation": "" + } + ], + "solution": "/**\n * @param {string} J\n * @param {string} S\n * @return {number}\n */\nconst numJewelsInStones = function(J, S) {\n if(J == null || J === '' || S == null || S === '') return 0\n const m = new Set(J)\n let res = 0\n for(let e of S) {\n if(m.has(e)) res++\n }\n return res\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720c4e", + "questionid": 387, + "title": "Search in a Binary Search Tree", + "slug": "search-in-a-binary-search-tree", + "description": "You are given the root of a binary search tree (BST) and an integer val. Find the node in the BST that the node's value equals val and return the subtree rooted with that node. If such a node does not exist, return null. ", + "category": [ + "Tree", + "Binary Search Tree", + "Binary Tree" + ], + "complexity": "Easy", + "successrate": 76.3, + "totalsubmissions": 614317, + "totalaccepted": 468905, + "likes": 3234, + "dislikes": 150, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [4,2,7,1,3], val = 2", + "expected_output": "[2,1,3]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "root = [4,2,7,1,3], val = 5", + "expected_output": "[]", + "explanation": "" + } + ], + "solution": "/**\n * Definition for a binary tree node.\n * function TreeNode(val, left, right) {\n * this.val = (val===undefined ? 0 : val)\n * this.left = (left===undefined ? null : left)\n * this.right = (right===undefined ? null : right)\n * }\n */\n/**\n * @param {TreeNode} root\n * @param {number} val\n * @return {TreeNode}\n */\nconst searchBST = function (root, val) {\n if (!root || root.val === val) {\n return root\n }\n return root.val < val ? searchBST(root.right, val) : searchBST(root.left, val)\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720c4f", + "questionid": 388, + "title": "Insert into a Binary Search Tree", + "slug": "insert-into-a-binary-search-tree", + "description": "You are given the root node of a binary search tree (BST) and a value to insert into the tree. Return the root node of the BST after the insertion. It is guaranteed that the new value does not exist in the original BST. Notice\u00a0that there may exist\u00a0multiple valid ways for the\u00a0insertion, as long as the tree remains a BST after insertion. You can return any of them. ", + "category": [ + "Tree", + "Binary Search Tree", + "Binary Tree" + ], + "complexity": "Medium", + "successrate": 74.9, + "totalsubmissions": 398561, + "totalaccepted": 298712, + "likes": 3244, + "dislikes": 141, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [4,2,7,1,3], val = 5", + "expected_output": "[4,2,7,1,3,5]", + "explanation": "Another accepted tree is:\n\"\"" + }, + { + "example_num": 2, + "expected_input": "root = [40,20,60,10,30,50,70], val = 25", + "expected_output": "[40,20,60,10,30,50,70,null,null,25]", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "root = [4,2,7,1,3,null,null,null,null,null,null], val = 5", + "expected_output": "[4,2,7,1,3,5]", + "explanation": "" + } + ], + "solution": "/**\n * Definition for a binary tree node.\n * function TreeNode(val) {\n * this.val = val;\n * this.left = this.right = null;\n * }\n */\n/**\n * @param {TreeNode} root\n * @param {number} val\n * @return {TreeNode}\n */\nconst insertIntoBST = function(root, val) {\n if(root == null) return new TreeNode(val);\n let cur = root;\n while(true) {\n if(cur.val <= val) {\n if(cur.right != null) cur = cur.right;\n else {\n cur.right = new TreeNode(val);\n break;\n }\n } else {\n if(cur.left != null) cur = cur.left;\n else {\n cur.left = new TreeNode(val);\n break;\n }\n }\n }\n return root;\n}; \n\n// another\n\nconst insertIntoBST = function(root, val) {\n if (root == null) {\n return new TreeNode(val);\n }\n if (root.val > val) {\n root.left = insertIntoBST(root.left, val);\n } else {\n root.right = insertIntoBST(root.right, val);\n }\n return root;\n}; \n\n// another\n\n/**\n * Definition for a binary tree node.\n * function TreeNode(val, left, right) {\n * this.val = (val===undefined ? 0 : val)\n * this.left = (left===undefined ? null : left)\n * this.right = (right===undefined ? null : right)\n * }\n */\n/**\n * @param {TreeNode} root\n * @param {number} val\n * @return {TreeNode}\n */\nconst insertIntoBST = function(root, val) {\n if(root == null) return new TreeNode(val)\n if(val < root.val) root.left = insertIntoBST(root.left, val)\n else if(val > root.val) root.right = insertIntoBST(root.right, val)\n return root\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720c5c", + "questionid": 401, + "title": "Custom Sort String", + "slug": "custom-sort-string", + "description": "You are given two strings order and s. All the words of order are unique and were sorted in some custom order previously. Permute the characters of s so that they match the order that order was sorted. More specifically, if a character x occurs before a character y in order, then x should occur before y in the permuted string. Return any permutation of s that satisfies this property. ", + "category": [ + "Hash Table", + "String", + "Sorting" + ], + "complexity": "Medium", + "successrate": 69, + "totalsubmissions": 253659, + "totalaccepted": 175117, + "likes": 1969, + "dislikes": 285, + "hints": "", + "deleted": false, + "examples": [], + "solution": "/**\n * @param {string} S\n * @param {string} T\n * @return {string}\n */\nconst customSortString = function(S, T) {\n const arr = [];\n const remaining = [];\n const hash = {};\n for (let i = 0; i < S.length; i++) {\n if (T.indexOf(S.charAt(i)) !== -1) {\n arr.push(S.charAt(i));\n }\n }\n let char;\n for (let j = 0; j < T.length; j++) {\n char = T.charAt(j);\n if (arr.indexOf(char) === -1 && remaining.indexOf(char) === -1) {\n remaining.push(char);\n }\n hash[char] = hash.hasOwnProperty(char) ? hash[char] + 1 : 1;\n }\n return `${genPart(arr, hash)}${genPart(remaining, hash)}`;\n};\n\nfunction constructStr(char, num) {\n let str = \"\";\n for (let i = 0; i < num; i++) {\n str += char;\n }\n return str;\n}\n\nfunction genPart(arr, hash) {\n return arr.reduce((ac, el) => {\n return ac + constructStr(el, hash[el]);\n }, \"\");\n}\n\nconsole.log(customSortString(\"kqep\", \"pekeq\"));\nconsole.log(\n customSortString(\n \"hucw\",\n \"utzoampdgkalexslxoqfkdjoczajxtuhqyxvlfatmptqdsochtdzgypsfkgqwbgqbcamdqnqztaqhqanirikahtmalzqjjxtqfnh\"\n )\n);\n" + }, + { + "_id": "66f925ddfdfb8e1665720c5e", + "questionid": 403, + "title": "Preimage Size of Factorial Zeroes Function", + "slug": "preimage-size-of-factorial-zeroes-function", + "description": "Let f(x) be the number of zeroes at the end of x!. Recall that x! = 1 * 2 * 3 * ... * x and by convention, 0! = 1. Given an integer k, return the number of non-negative integers x have the property that f(x) = k. ", + "category": [ + "Math", + "Binary Search" + ], + "complexity": "Hard", + "successrate": 41.6, + "totalsubmissions": 28933, + "totalaccepted": 12050, + "likes": 298, + "dislikes": 68, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "k = 0", + "expected_output": "5", + "explanation": "0!, 1!, 2!, 3!, and 4! end with k = 0 zeroes." + }, + { + "example_num": 2, + "expected_input": "k = 5", + "expected_output": "0", + "explanation": "There is no x such that x! ends in k = 5 zeroes." + }, + { + "example_num": 3, + "expected_input": "k = 3", + "expected_output": "5", + "explanation": "" + } + ], + "solution": "/**\n * @param {number} K\n * @return {number}\n */\nconst preimageSizeFZF = function(K) {\n let last = 1\n while (last < K) last = last * 5 + 1\n while (last > 1) {\n K %= last\n if (last - 1 == K) return 0\n last = ((last - 1) / 5) >> 0\n }\n return 5\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720c62", + "questionid": 407, + "title": "Champagne Tower", + "slug": "champagne-tower", + "description": "We stack glasses in a pyramid, where the first row has 1 glass, the second row has 2 glasses, and so on until the 100th row.\u00a0 Each glass holds one cup\u00a0of champagne. Then, some champagne is poured into the first glass at the top.\u00a0 When the topmost glass is full, any excess liquid poured will fall equally to the glass immediately to the left and right of it.\u00a0 When those glasses become full, any excess champagne will fall equally to the left and right of those glasses, and so on.\u00a0 (A glass at the bottom row has its excess champagne fall on the floor.) For example, after one cup of champagne is poured, the top most glass is full.\u00a0 After two cups of champagne are poured, the two glasses on the second row are half full.\u00a0 After three cups of champagne are poured, those two cups become full - there are 3 full glasses total now.\u00a0 After four cups of champagne are poured, the third row has the middle glass half full, and the two outside glasses are a quarter full, as pictured below. Now after pouring some non-negative integer cups of champagne, return how full the jth glass in the ith row is (both i and j are 0-indexed.) ", + "category": [ + "Dynamic Programming" + ], + "complexity": "Medium", + "successrate": 51.2, + "totalsubmissions": 146739, + "totalaccepted": 75161, + "likes": 2315, + "dislikes": 128, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "poured = 1, query_row = 1, query_glass = 1", + "expected_output": "0.00000", + "explanation": "We poured 1 cup of champange to the top glass of the tower (which is indexed as (0, 0)). There will be no excess liquid so all the glasses under the top glass will remain empty." + }, + { + "example_num": 2, + "expected_input": "poured = 2, query_row = 1, query_glass = 1", + "expected_output": "0.50000", + "explanation": "We poured 2 cups of champange to the top glass of the tower (which is indexed as (0, 0)). There is one cup of excess liquid. The glass indexed as (1, 0) and the glass indexed as (1, 1) will share the excess liquid equally, and each will get half cup of champange." + }, + { + "example_num": 3, + "expected_input": "poured = 100000009, query_row = 33, query_glass = 17", + "expected_output": "1.00000", + "explanation": "" + } + ], + "solution": "/**\n * @param {number} poured\n * @param {number} query_row\n * @param {number} query_glass\n * @return {number}\n */\nconst champagneTower = function(poured, query_row, query_glass) {\n let curRow = [poured]\n for(let i = 0; i <= query_row; i++) {\n const nxtRow = Array(i + 2).fill(0)\n for(let j = 0; j <= i; j++) {\n if(curRow[j] > 1) {\n nxtRow[j] += (curRow[j] - 1) / 2\n nxtRow[j + 1] += (curRow[j] - 1) / 2\n curRow[j] = 1\n }\n }\n if(i !== query_row) curRow = nxtRow\n }\n \n return curRow[query_glass]\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720c63", + "questionid": 408, + "title": "Minimum Swaps To Make Sequences Increasing", + "slug": "minimum-swaps-to-make-sequences-increasing", + "description": "You are given two integer arrays of the same length nums1 and nums2. In one operation, you are allowed to swap nums1[i] with nums2[i]. Return the minimum number of needed operations to make nums1 and nums2 strictly increasing. The test cases are generated so that the given input always makes it possible. An array arr is strictly increasing if and only if arr[0] < arr[1] < arr[2] < ... < arr[arr.length - 1]. ", + "category": [ + "Array", + "Dynamic Programming" + ], + "complexity": "Hard", + "successrate": 39.2, + "totalsubmissions": 133894, + "totalaccepted": 52429, + "likes": 1974, + "dislikes": 123, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums1 = [1,3,5,4], nums2 = [1,2,3,7]", + "expected_output": "1", + "explanation": "Swap nums1[3] and nums2[3]. Then the sequences are:\nnums1 = [1, 3, 5, 7] and nums2 = [1, 2, 3, 4]\nwhich are both strictly increasing." + }, + { + "example_num": 2, + "expected_input": "nums1 = [0,3,5,8,9], nums2 = [2,1,4,6,9]", + "expected_output": "1", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} A\n * @param {number[]} B\n * @return {number}\n */\nconst minSwap = function(A, B) {\n let swapRecord = 1, fixRecord = 0;\n for (let i = 1; i < A.length; i++) {\n if (A[i - 1] >= B[i] || B[i - 1] >= A[i]) {\n // In this case, the ith manipulation should be same as the i-1th manipulation\n // fixRecord = fixRecord;\n swapRecord++;\n } else if (A[i - 1] >= A[i] || B[i - 1] >= B[i]) {\n // In this case, the ith manipulation should be the opposite of the i-1th manipulation\n let temp = swapRecord;\n swapRecord = fixRecord + 1;\n fixRecord = temp;\n } else {\n // Either swap or fix is OK. Let's keep the minimum one\n let min = Math.min(swapRecord, fixRecord);\n swapRecord = min + 1;\n fixRecord = min;\n }\n }\n return Math.min(swapRecord, fixRecord);\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720c65", + "questionid": 410, + "title": "Split Array With Same Average", + "slug": "split-array-with-same-average", + "description": "You are given an integer array nums. You should move each element of nums into one of the two arrays A and B such that A and B are non-empty, and average(A) == average(B). Return true if it is possible to achieve that and false otherwise. Note that for an array arr, average(arr) is the sum of all the elements of arr over the length of arr. ", + "category": [ + "Array", + "Math", + "Dynamic Programming", + "Bit Manipulation", + "Bitmask" + ], + "complexity": "Hard", + "successrate": 26.5, + "totalsubmissions": 95370, + "totalaccepted": 25304, + "likes": 804, + "dislikes": 115, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,2,3,4,5,6,7,8]", + "expected_output": "true", + "explanation": "We can split the array into [1,4,5,8] and [2,3,6,7], and both of them have an average of 4.5." + }, + { + "example_num": 2, + "expected_input": "nums = [3,1]", + "expected_output": "false", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} A\n * @return {boolean}\n */\nconst splitArraySameAverage = function(A) {\n const totalSum = A.reduce((ac, el) => ac + el, 0)\n const len = A.length\n const mid = Math.floor(len / 2)\n A.sort((a, b) => b - a)\n for (let i = 1; i <= mid; i++) {\n if ((totalSum * i) % len === 0 && combinationSum(A, 0, i, (totalSum * i) / len)) return true\n }\n return false\n}\n\nfunction combinationSum(nums, idx, k, target) {\n if (target > k * nums[idx]) return false\n if (k === 0) return target === 0\n for (let i = idx; i < nums.length - k; i++) {\n if (nums[i] <= target && combinationSum(nums, i + 1, k - 1, target - nums[i])) return true\n }\n return false\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720c69", + "questionid": 414, + "title": "Largest Triangle Area", + "slug": "largest-triangle-area", + "description": "Given an array of points on the X-Y plane points where points[i] = [xi, yi], return the area of the largest triangle that can be formed by any three different points. Answers within 10-5 of the actual answer will be accepted. ", + "category": [ + "Array", + "Math", + "Geometry" + ], + "complexity": "Easy", + "successrate": 59.6, + "totalsubmissions": 54067, + "totalaccepted": 32240, + "likes": 332, + "dislikes": 1318, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "points = [[0,0],[0,1],[1,0],[0,2],[2,0]]", + "expected_output": "2.00000", + "explanation": "The five points are shown in the above figure. The red triangle is the largest." + }, + { + "example_num": 2, + "expected_input": "points = [[1,0],[0,0],[0,1]]", + "expected_output": "0.50000", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[][]} points\n * @return {number}\n */\nconst largestTriangleArea = function(points) {\n const N = points.length\n let ans = 0\n for(let i = 0; i < N; i++) {\n for(let j = i + 1; j < N; j++) {\n for(let k = j + 1; k < N; k++) {\n ans = Math.max(ans, area(points[i], points[j], points[k]))\n }\n }\n }\n return ans\n};\n\nfunction area(P,Q,R) {\n return 0.5 * Math.abs(P[0]*Q[1] + Q[0]*R[1] + R[0]*P[1] -P[1]*Q[0] - Q[1]*R[0] - R[1]*P[0])\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720c6b", + "questionid": 416, + "title": "Binary Tree Pruning", + "slug": "binary-tree-pruning", + "description": "Given the root of a binary tree, return the same tree where every subtree (of the given tree) not containing a 1 has been removed. A subtree of a node node is node plus every node that is a descendant of node. ", + "category": [ + "Tree", + "Depth-First Search", + "Binary Tree" + ], + "complexity": "Medium", + "successrate": 71, + "totalsubmissions": 196440, + "totalaccepted": 139432, + "likes": 2373, + "dislikes": 66, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [1,null,0,0,1]", + "expected_output": "[1,null,0,null,1]", + "explanation": "Only the red nodes satisfy the property "every subtree not containing a 1".\nThe diagram on the right represents the answer." + }, + { + "example_num": 2, + "expected_input": "root = [1,0,1,0,0,0,1]", + "expected_output": "[1,null,1,null,1]", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "root = [1,1,0,1,1,0,1,0]", + "expected_output": "[1,1,0,1,1,null,1]", + "explanation": "" + } + ], + "solution": null + }, + { + "_id": "66f925ddfdfb8e1665720c6f", + "questionid": 420, + "title": "Most Common Word", + "slug": "most-common-word", + "description": "Given a string paragraph and a string array of the banned words banned, return the most frequent word that is not banned. It is guaranteed there is at least one word that is not banned, and that the answer is unique. The words in paragraph are case-insensitive and the answer should be returned in lowercase. ", + "category": [ + "Hash Table", + "String", + "Counting" + ], + "complexity": "Easy", + "successrate": 45.2, + "totalsubmissions": 626728, + "totalaccepted": 283564, + "likes": 1245, + "dislikes": 2543, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "paragraph = "Bob hit a ball, the hit BALL flew far after it was hit.", banned = ["hit"]", + "expected_output": ""ball"", + "explanation": ""hit" occurs 3 times, but it is a banned word.\n"ball" occurs twice (and no other word does), so it is the most frequent non-banned word in the paragraph. \nNote that words in the paragraph are not case sensitive,\nthat punctuation is ignored (even if adjacent to words, such as "ball,"), \nand that "hit" isn't the answer even though it occurs more because it is banned." + }, + { + "example_num": 2, + "expected_input": "paragraph = "a.", banned = []", + "expected_output": ""a"", + "explanation": "" + } + ], + "solution": "/**\n * @param {string} paragraph\n * @param {string[]} banned\n * @return {string}\n */\nconst mostCommonWord = function(paragraph, banned) {\n const str = paragraph.toLowerCase()\n const arr = str.replace(/\\W+/g, ' ').trim().split(' ')\n const hash = {}\n for(let el of arr) {\n if(banned.indexOf(el) !== -1) {\n\n } else {\n if(hash.hasOwnProperty(el)) {\n hash[el] += 1\n } else {\n hash[el] = 1\n }\n }\n }\n const res = Object.entries(hash).sort((a, b) => b[1] - a[1])\n return res[0][0]\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720c72", + "questionid": 423, + "title": "Binary Trees With Factors", + "slug": "binary-trees-with-factors", + "description": "Given an array of unique integers, arr, where each integer arr[i] is strictly greater than 1. We make a binary tree using these integers, and each number may be used for any number of times. Each non-leaf node's value should be equal to the product of the values of its children. Return the number of binary trees we can make. The answer may be too large so return the answer modulo 109 + 7. ", + "category": [ + "Array", + "Hash Table", + "Dynamic Programming" + ], + "complexity": "Medium", + "successrate": 43.7, + "totalsubmissions": 83583, + "totalaccepted": 36507, + "likes": 834, + "dislikes": 101, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "arr = [2,4]", + "expected_output": "3", + "explanation": "We can make these trees: [2], [4], [4, 2, 2]" + }, + { + "example_num": 2, + "expected_input": "arr = [2,4,5,10]", + "expected_output": "7", + "explanation": "We can make these trees: [2], [4], [5], [10], [4, 2, 2], [10, 2, 5], [10, 5, 2]." + } + ], + "solution": "/**\n * @param {number[]} A\n * @return {number}\n */\nconst numFactoredBinaryTrees = function(A) {\n const mod = 10 ** 9 + 7\n let res = 0\n A.sort((a, b) => a - b)\n const dp = {}\n for(let i = 0; i < A.length; i++) {\n dp[A[i]] = 1\n for(let j = 0; j < i; j++) {\n if(A[i] % A[j] === 0 && dp.hasOwnProperty(Math.floor( A[i] / A[j]))) {\n dp[A[i]] = (dp[A[i]] + dp[A[j]] * dp[Math.floor(A[i] / A[j])]) % mod\n }\n }\n }\n for(let el of Object.values(dp)) res = (res + el) % mod\n return res\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720c74", + "questionid": 425, + "title": "Count Unique Characters of All Substrings of a Given String", + "slug": "count-unique-characters-of-all-substrings-of-a-given-string", + "description": "Let's define a function countUniqueChars(s) that returns the number of unique characters on s. Given a string s, return the sum of countUniqueChars(t) where t is a substring of s. Notice that some substrings can be repeated so in this case you have to count the repeated ones too. ", + "category": [ + "String", + "Dynamic Programming" + ], + "complexity": "Hard", + "successrate": 49.7, + "totalsubmissions": 78320, + "totalaccepted": 38959, + "likes": 1243, + "dislikes": 169, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "ABC"", + "expected_output": "10\nExplanation: All possible substrings are: "A","B","C","AB","BC" and "ABC".\nEvery substring is composed with only unique letters.\nSum of lengths of all substring is 1 + 1 + 1 + 2 + 2 + 3 = 10", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "s = "ABA"", + "expected_output": "8\nExplanation: The same as example 1, except countUniqueChars("ABA") = 1.", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "s = "LEETCODE"", + "expected_output": "92", + "explanation": "" + } + ], + "solution": null + }, + { + "_id": "66f925ddfdfb8e1665720c75", + "questionid": 426, + "title": "Consecutive Numbers Sum", + "slug": "consecutive-numbers-sum", + "description": "Given an integer n, return the number of ways you can write n as the sum of consecutive positive integers. ", + "category": [ + "Math", + "Enumeration" + ], + "complexity": "Hard", + "successrate": 41, + "totalsubmissions": 164713, + "totalaccepted": 67555, + "likes": 998, + "dislikes": 1209, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 5", + "expected_output": "2", + "explanation": "5 = 2 + 3" + }, + { + "example_num": 2, + "expected_input": "n = 9", + "expected_output": "3", + "explanation": "9 = 4 + 5 = 2 + 3 + 4" + }, + { + "example_num": 3, + "expected_input": "n = 15", + "expected_output": "4", + "explanation": "15 = 8 + 7 = 4 + 5 + 6 = 1 + 2 + 3 + 4 + 5" + } + ], + "solution": "/**\n * @param {number} N\n * @return {number}\n */\nconst consecutiveNumbersSum = function (N) {\n let count = 1\n for (let k = 2; k < Math.sqrt(2 * N); k++) {\n if ((N - (k * (k - 1)) / 2) % k === 0) count++\n }\n return count\n}\n\n// another\n\n/**\n * @param {number} N\n * @return {number}\n */\nconst consecutiveNumbersSum = function(N) {\n let res = 0\n for(let i = 1; i <= N; i++) {\n const diff = i * (i - 1) / 2\n const nd = N - diff\n if(nd <= 0) break\n if(nd % i === 0) res++\n }\n \n return res\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720c79", + "questionid": 430, + "title": "Image Overlap", + "slug": "image-overlap", + "description": "You are given two images, img1 and img2, represented as binary, square matrices of size n x n. A binary matrix has only 0s and 1s as values. We translate one image however we choose by sliding all the 1 bits left, right, up, and/or down any number of units. We then place it on top of the other image. We can then calculate the overlap by counting the number of positions that have a 1 in both images. Note also that a translation does not include any kind of rotation. Any 1 bits that are translated outside of the matrix borders are erased. Return the largest possible overlap. ", + "category": [ + "Array", + "Matrix" + ], + "complexity": "Medium", + "successrate": 61.3, + "totalsubmissions": 77230, + "totalaccepted": 47304, + "likes": 100, + "dislikes": 29, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "img1 = [[1,1,0],[0,1,0],[0,1,0]], img2 = [[0,0,0],[0,1,1],[0,0,1]]", + "expected_output": "3", + "explanation": "We translate img1 to right by 1 unit and down by 1 unit.\n\"\"\nThe number of positions that have a 1 in both images is 3 (shown in red).\n\"\"" + }, + { + "example_num": 2, + "expected_input": "img1 = [[1]], img2 = [[1]]", + "expected_output": "1", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "img1 = [[0]], img2 = [[0]]", + "expected_output": "0", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[][]} A\n * @param {number[][]} B\n * @return {number}\n */\nconst largestOverlap = function(A, B) {\n const N = A.length\n const count = constructMatrix(2*N, 2*N, 0)\n for (let i = 0; i < N; i++) {\n for (let j = 0; j < N; j++) {\n if (A[i][j] === 1) {\n for(let ii = 0; ii < N; ii++) {\n for(let jj = 0; jj < N; jj++) {\n if(B[ii][jj] === 1) {\n count[i-ii+N][j-jj+N] += 1\n }\n }\n }\n }\n }\n }\n let ans = 0\n\n for(let row of count) {\n for(let v of row) {\n ans = Math.max(ans, v)\n }\n }\n return ans\n};\n\nfunction constructMatrix(row, col, init = 0) {\n const matrix = []\n for(let i = 0; i < row; i++) {\n matrix[i] = []\n for(let j = 0; j < col; j++) {\n matrix[i][j] = init\n }\n }\n return matrix\n}\n\nconsole.log(largestOverlap([[1,1,0],\n [0,1,0],\n [0,1,0]],[[0,0,0],\n [0,1,1],\n [0,0,1]]))" + }, + { + "_id": "66f925ddfdfb8e1665720c7b", + "questionid": 432, + "title": "New 21 Game", + "slug": "new-21-game", + "description": "Alice plays the following game, loosely based on the card game \"21\". Alice starts with 0 points and draws numbers while she has less than k points. During each draw, she gains an integer number of points randomly from the range [1, maxPts], where maxPts is an integer. Each draw is independent and the outcomes have equal probabilities. Alice stops drawing numbers when she gets k or more points. Return the probability that Alice has n or fewer points. Answers within 10-5 of the actual answer are considered accepted. ", + "category": [ + "Math", + "Dynamic Programming", + "Sliding Window", + "Probability and Statistics" + ], + "complexity": "Medium", + "successrate": 36, + "totalsubmissions": 86086, + "totalaccepted": 31029, + "likes": 942, + "dislikes": 629, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 10, k = 1, maxPts = 10", + "expected_output": "1.00000", + "explanation": "Alice gets a single card, then stops." + }, + { + "example_num": 2, + "expected_input": "n = 6, k = 1, maxPts = 10", + "expected_output": "0.60000", + "explanation": "Alice gets a single card, then stops.\nIn 6 out of 10 possibilities, she is at or below 6 points." + }, + { + "example_num": 3, + "expected_input": "n = 21, k = 17, maxPts = 10", + "expected_output": "0.73278", + "explanation": "" + } + ], + "solution": "/**\n * @param {number} N\n * @param {number} K\n * @param {number} W\n * @return {number}\n */\nconst new21Game = function(N, K, W) {\n if (K === 0 || N >= K + W) {\n return 1;\n }\n const dp = [];\n let Wsum = 1;\n let res = 0;\n dp[0] = 1;\n for (let i = 1; i <= N; i++) {\n dp[i] = Wsum / W;\n if (i < K) {\n Wsum += dp[i];\n } else {\n res += dp[i];\n }\n if (i - W >= 0) {\n Wsum -= dp[i - W];\n }\n }\n return res;\n};\n\nconsole.log(new21Game(6, 1, 10));\nconsole.log(new21Game(10, 1, 10));\nconsole.log(new21Game(21, 17, 10));\n" + }, + { + "_id": "66f925ddfdfb8e1665720c8b", + "questionid": 448, + "title": "Score After Flipping Matrix", + "slug": "score-after-flipping-matrix", + "description": "You are given an m x n binary matrix grid. A move consists of choosing any row or column and toggling each value in that row or column (i.e., changing all 0's to 1's, and all 1's to 0's). Every row of the matrix is interpreted as a binary number, and the score of the matrix is the sum of these numbers. Return the highest possible score after making any number of moves (including zero moves). ", + "category": [ + "Array", + "Greedy", + "Bit Manipulation", + "Matrix" + ], + "complexity": "Medium", + "successrate": 74.8, + "totalsubmissions": 45815, + "totalaccepted": 34267, + "likes": 1024, + "dislikes": 162, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "grid = [[0,0,1,1],[1,0,1,0],[1,1,0,0]]", + "expected_output": "39", + "explanation": "0b1111 + 0b1001 + 0b1111 = 15 + 9 + 15 = 39" + }, + { + "example_num": 2, + "expected_input": "grid = [[0]]", + "expected_output": "1", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[][]} grid\n * @return {number}\n */\nconst matrixScore = function(grid) {\n const m = grid.length, n = grid[0].length\n let res = 0\n res += m * (1 << (n - 1))\n for(let j = 1; j < n; j++) {\n let same = 0\n for(let i = 0; i < m; i++) {\n if(grid[i][0] === grid[i][j]) same++\n }\n res += Math.max(same, m - same) * (1 << (n - 1 - j))\n }\n \n return res\n};\n\n// another\n\n/**\n * @param {number[][]} grid\n * @return {number}\n */\nconst matrixScore = function(grid) {\n const m = grid.length, n = grid[0].length\n for(let i = 0; i < m; i++) {\n if(grid[i][0] === 0) flipRow(i)\n }\n \n for(let i = 0; i < n; i++) {\n if(cntCol(i, 0) > cntCol(i, 1)) flipCol(i)\n }\n \n let res = 0\n // console.log(grid)\n for(const row of grid) {\n res += parseInt(row.join(''), 2)\n }\n \n return res\n \n \n function flipRow(idx) {\n for(let i = 0; i < n; i++) {\n if(grid[idx][i] === 0) grid[idx][i] = 1\n else grid[idx][i] = 0\n }\n }\n \n function cntCol(idx, target) {\n let res = 0\n for(let i = 0; i < m; i++) {\n if(grid[i][idx] === target) res++\n }\n // console.log(res)\n return res\n }\n \n function flipCol(idx) {\n for(let i = 0; i < m; i++) {\n if(grid[i][idx] === 0) grid[i][idx] = 1\n else grid[i][idx] = 0\n }\n }\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720c51", + "questionid": 390, + "title": "Binary Search", + "slug": "binary-search", + "description": "Given an array of integers nums which is sorted in ascending order, and an integer target, write a function to search target in nums. If target exists, then return its index. Otherwise, return -1. You must write an algorithm with O(log n) runtime complexity. ", + "category": [ + "Array", + "Binary Search" + ], + "complexity": "Easy", + "successrate": 55.3, + "totalsubmissions": 1475426, + "totalaccepted": 816061, + "likes": 4525, + "dislikes": 106, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [-1,0,3,5,9,12], target = 9", + "expected_output": "4", + "explanation": "9 exists in nums and its index is 4" + }, + { + "example_num": 2, + "expected_input": "nums = [-1,0,3,5,9,12], target = 2", + "expected_output": "-1", + "explanation": "2 does not exist in nums so return -1" + } + ], + "solution": "/**\n * @param {number[]} nums\n * @param {number} target\n * @return {number}\n */\nconst search = function(nums, target) {\n let start = 0;\n let end = nums.length - 1;\n \n while(start <= end){\n let mid = parseInt((start + end) / 2);\n if(nums[mid] === target) return mid;\n if(nums[mid] > target) end = mid -1;\n if(nums[mid] < target) start = mid + 1;\n }\n return -1;\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720c53", + "questionid": 392, + "title": "Swim in Rising Water", + "slug": "swim-in-rising-water", + "description": "You are given an n x n integer matrix grid where each value grid[i][j] represents the elevation at that point (i, j). The rain starts to fall. At time t, the depth of the water everywhere is t. You can swim from a square to another 4-directionally adjacent square if and only if the elevation of both squares individually are at most t. You can swim infinite distances in zero time. Of course, you must stay within the boundaries of the grid during your swim. Return the least time until you can reach the bottom right square (n - 1, n - 1) if you start at the top left square (0, 0). ", + "category": [ + "Array", + "Binary Search", + "Depth-First Search", + "Breadth-First Search", + "Union Find", + "Heap (Priority Queue)", + "Matrix" + ], + "complexity": "Hard", + "successrate": 58.7, + "totalsubmissions": 126837, + "totalaccepted": 74390, + "likes": 1876, + "dislikes": 133, + "hints": "Use either Dijkstra's, or binary search for the best time T for which you can reach the end if you only step on squares at most T.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "grid = [[0,2],[1,3]]", + "expected_output": "3\nExplanation:\nAt time 0, you are in grid location (0, 0).\nYou cannot go anywhere else because 4-directionally adjacent neighbors have a higher elevation than t = 0.\nYou cannot reach point (1, 1) until time 3.\nWhen the depth of water is 3, we can swim anywhere inside the grid.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "grid = [[0,1,2,3,4],[24,23,22,21,5],[12,13,14,15,16],[11,17,18,19,20],[10,9,8,7,6]]", + "expected_output": "16", + "explanation": "The final route is shown.\nWe need to wait until time 16 so that (0, 0) and (4, 4) are connected." + } + ], + "solution": "/**\n * @param {number[][]} grid\n * @return {number}\n */\nconst swimInWater = function(grid) {\n const n = grid.length\n const limit = n * n, { floor } = Math\n let l = 0, r = limit - 1\n \n while(l < r) {\n const mid = l + floor((r - l) / 2)\n if(valid(mid)) r = mid\n else l = mid + 1\n }\n \n return l\n \n \n function valid(h) {\n const visited = Array.from({ length: n }, () => Array(n).fill(0))\n if(grid[0][0] > h) return false\n return dfs(h, 0, 0, visited)\n }\n \n function dfs(h, i, j, visited) {\n if(i === n - 1 && j === n - 1) return true\n const dirs = [[1, 0], [-1, 0], [0, 1], [0, -1]]\n visited[i][j] = 1\n for(const [dx, dy] of dirs) {\n const nx = i + dx, ny = j + dy\n if(nx >= 0 && nx < n && ny >= 0 && ny < n && visited[nx][ny] === 0 && grid[nx][ny] <= h) {\n if(dfs(h, nx, ny, visited)) return true\n }\n \n }\n \n return false\n }\n};\n\n// another\n\n\n/**\n * @param {number[][]} grid\n * @return {number}\n */\nconst swimInWater = function(grid) {\n let n = grid.length;\n let low = grid[0][0],\n hi = n * n - 1;\n while (low < hi) {\n let mid = low + Math.floor((hi - low) / 2);\n if (valid(grid, mid)) hi = mid;\n else low = mid + 1;\n }\n return low;\n};\n\nfunction valid(grid, waterHeight) {\n let n = grid.length;\n const visited = Array.from(new Array(n), el => new Array(n).fill(0));\n const dir = [-1, 0, 1, 0, -1];\n return dfs(grid, visited, dir, waterHeight, 0, 0, n);\n}\nfunction dfs(grid, visited, dir, waterHeight, row, col, n) {\n visited[row][col] = 1;\n for (let i = 0; i < 4; ++i) {\n let r = row + dir[i],\n c = col + dir[i + 1];\n if (\n r >= 0 &&\n r < n &&\n c >= 0 &&\n c < n &&\n visited[r][c] == 0 &&\n grid[r][c] <= waterHeight\n ) {\n if (r == n - 1 && c == n - 1) return true;\n if (dfs(grid, visited, dir, waterHeight, r, c, n)) return true;\n }\n }\n return false;\n}\n\n// another\n\n/**\n * @param {number[][]} grid\n * @return {number}\n */\nconst dirs = [[-1, 0], [1, 0], [0, 1], [0, -1]];\nconst swimInWater = grid => {\n let time = 0;\n let N = grid.length;\n const visited = new Set();\n while (!visited.has(N * N - 1)) {\n visited.clear();\n dfs(grid, 0, 0, time, visited);\n time++;\n }\n return time - 1;\n};\n\nfunction dfs(grid, i, j, time, visited) {\n if (\n i < 0 ||\n i > grid.length - 1 ||\n j < 0 ||\n j > grid[0].length - 1 ||\n grid[i][j] > time ||\n visited.has(i * grid.length + j)\n )\n return;\n visited.add(i * grid.length + j);\n for (let dir of dirs) {\n dfs(grid, i + dir[0], j + dir[1], time, visited);\n }\n}\n\n\n// another\n\n/**\n * @param {number[][]} grid\n * @return {number}\n */\nclass UnionFind {\n constructor(N) {\n this.id = [];\n for (let i = 0; i < N; i++) {\n this.id[i] = i;\n }\n }\n\n root(i) {\n while (i != this.id[i]) {\n this.id[i] = this.id[this.id[i]];\n i = this.id[i];\n }\n return i;\n }\n isConnected(p, q) {\n return this.root(p) === this.root(q);\n }\n union(p, q) {\n if (this.isConnected(p, q)) return;\n this.id[this.root(p)] = this.root(q);\n }\n}\nconst swimInWater = grid => {\n const N = grid.length;\n const uf = new UnionFind(N * N);\n let time = 0;\n while (!uf.isConnected(0, N * N - 1)) {\n for (let i = 0; i < N; i++) {\n for (let j = 0; j < N; j++) {\n if (grid[i][j] > time) continue;\n if (i < N - 1 && grid[i + 1][j] <= time)\n uf.union(i * N + j, i * N + j + N);\n if (j < N - 1 && grid[i][j + 1] <= time)\n uf.union(i * N + j, i * N + j + 1);\n }\n }\n time++;\n }\n return time - 1;\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720c52", + "questionid": 391, + "title": "Swap Adjacent in LR String", + "slug": "swap-adjacent-in-lr-string", + "description": "In a string composed of 'L', 'R', and 'X' characters, like \"RXXLRXRXL\", a move consists of either replacing one occurrence of \"XL\" with \"LX\", or replacing one occurrence of \"RX\" with \"XR\". Given the starting string start and the ending string end, return True if and only if there exists a sequence of moves to transform one string to the other. ", + "category": [ + "Two Pointers", + "String" + ], + "complexity": "Medium", + "successrate": 36.3, + "totalsubmissions": 144772, + "totalaccepted": 52578, + "likes": 782, + "dislikes": 682, + "hints": "Think of the L and R's as people on a horizontal line, where X is a space. The people can't cross each other, and also you can't go from XRX to RXX.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "start = "RXXLRXRXL", end = "XRLXXRRLX"", + "expected_output": "true", + "explanation": "We can transform start to end following these steps:\nRXXLRXRXL ->\nXRXLRXRXL ->\nXRLXRXRXL ->\nXRLXXRRXL ->\nXRLXXRRLX" + }, + { + "example_num": 2, + "expected_input": "start = "X", end = "L"", + "expected_output": "false", + "explanation": "" + } + ], + "solution": "/**\n * @param {string} start\n * @param {string} end\n * @return {boolean}\n */\nconst canTransform = function(start, end) {\n let r = 0, l = 0;\n for (let i = 0; i < start.length; i++){\n if (start.charAt(i) === 'R'){ r++; l = 0;}\n if (end.charAt(i) === 'R') { r--; l = 0;}\n if (end.charAt(i) === 'L') { l++; r = 0;}\n if (start.charAt(i) === 'L') { l--; r = 0;}\n if (l < 0 || r < 0) return false;\n }\n\n if (l != 0 || r != 0) return false;\n return true; \n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720c57", + "questionid": 396, + "title": "Transform to Chessboard", + "slug": "transform-to-chessboard", + "description": "You are given an n x n binary grid board. In each move, you can swap any two rows with each other, or any two columns with each other. Return the minimum number of moves to transform the board into a chessboard board. If the task is impossible, return -1. A chessboard board is a board where no 0's and no 1's are 4-directionally adjacent. ", + "category": [ + "Array", + "Math", + "Bit Manipulation", + "Matrix" + ], + "complexity": "Hard", + "successrate": 52, + "totalsubmissions": 28761, + "totalaccepted": 14953, + "likes": 287, + "dislikes": 282, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "board = [[0,1,1,0],[0,1,1,0],[1,0,0,1],[1,0,0,1]]", + "expected_output": "2", + "explanation": "One potential sequence of moves is shown.\nThe first move swaps the first and second column.\nThe second move swaps the second and third row." + }, + { + "example_num": 2, + "expected_input": "board = [[0,1],[1,0]]", + "expected_output": "0", + "explanation": "Also note that the board with 0 in the top left corner, is also a valid chessboard." + }, + { + "example_num": 3, + "expected_input": "board = [[1,0],[1,0]]", + "expected_output": "-1", + "explanation": "No matter what sequence of moves you make, you cannot end with a valid chessboard." + } + ], + "solution": "/**\n * @param {number[][]} b\n * @return {number}\n */\nconst movesToChessboard = function (b) {\n let N = b.length,\n rowSum = 0,\n colSum = 0,\n rowSwap = 0,\n colSwap = 0;\n for (let i = 0; i < N; ++i)\n for (let j = 0; j < N; ++j)\n if ((b[0][0] ^ b[i][0] ^ b[0][j] ^ b[i][j]) === 1) return -1;\n for (let i = 0; i < N; ++i) {\n rowSum += b[0][i];\n colSum += b[i][0];\n if (b[i][0] === i % 2) rowSwap++;\n if (b[0][i] === i % 2) colSwap++;\n }\n if (rowSum !== ((N / 2) >> 0) && rowSum !== ((N + 1) / 2)>>0 ) return -1;\n if (colSum !== ((N / 2) >> 0) && colSum !== ((N + 1) / 2)>>0 ) return -1;\n if (N % 2 === 1) {\n if (colSwap % 2 === 1) colSwap = N - colSwap;\n if (rowSwap % 2 === 1) rowSwap = N - rowSwap;\n } else {\n colSwap = Math.min(N - colSwap, colSwap);\n rowSwap = Math.min(N - rowSwap, rowSwap);\n }\n return (colSwap + rowSwap) / 2;\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720c58", + "questionid": 397, + "title": "Minimum Distance Between BST Nodes", + "slug": "minimum-distance-between-bst-nodes", + "description": "Given the root of a Binary Search Tree (BST), return the minimum difference between the values of any two different nodes in the tree. ", + "category": [ + "Tree", + "Depth-First Search", + "Breadth-First Search", + "Binary Search Tree", + "Binary Tree" + ], + "complexity": "Easy", + "successrate": 56, + "totalsubmissions": 212326, + "totalaccepted": 118984, + "likes": 1591, + "dislikes": 311, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [4,2,6,1,3]", + "expected_output": "1", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "root = [1,0,48,null,null,12,49]", + "expected_output": "1", + "explanation": "" + } + ], + "solution": null + }, + { + "_id": "66f925ddfdfb8e1665720c5d", + "questionid": 402, + "title": "Number of Matching Subsequences", + "slug": "number-of-matching-subsequences", + "description": "Given a string s and an array of strings words, return the number of words[i] that is a subsequence of s. A subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters. ", + "category": [ + "Hash Table", + "String", + "Trie", + "Sorting" + ], + "complexity": "Medium", + "successrate": 50.5, + "totalsubmissions": 253208, + "totalaccepted": 127852, + "likes": 2889, + "dislikes": 148, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "abcde", words = ["a","bb","acd","ace"]", + "expected_output": "3", + "explanation": "There are three strings in words that are a subsequence of s: "a", "acd", "ace"." + }, + { + "example_num": 2, + "expected_input": "s = "dsahjpjauf", words = ["ahjpjau","ja","ahbwzgqnuk","tnmlanowax"]", + "expected_output": "2", + "explanation": "" + } + ], + "solution": "/**\n * @param {string} s\n * @param {string[]} words\n * @return {number}\n */\nconst numMatchingSubseq = function(s, words) {\n const hash = {}\n for(let w of words) {\n if(hash[w[0]] == null) hash[w[0]] = []\n const it = w[Symbol.iterator]()\n hash[w[0]].push( it )\n it.next()\n }\n let res = 0\n for(let ch of s) {\n const advance = hash[ch] || []\n hash[ch] = []\n for(let it of advance) {\n const obj = it.next()\n if(obj.done === false) {\n if(hash[obj.value] == null) hash[obj.value] = []\n hash[obj.value].push(it)\n } else {\n res++\n }\n }\n }\n\n return res\n};\n\n// another\n\n/**\n * @param {string} S\n * @param {string[]} words\n * @return {number}\n */\nconst numMatchingSubseq = function(S, words) {\n let res=0;\n for(let i=0;i right) {\n prev = i\n dp = 0\n } else {\n dp = i - prev\n }\n\n res += dp\n }\n \n return res\n};\n\n// another\n\n/**\n * @param {number[]} A\n * @param {number} L\n * @param {number} R\n * @return {number}\n */\nconst numSubarrayBoundedMax = function(A, L, R) {\n let res = 0;\n let j = 0;\n let count = 0;\n for(let i = 0; i < A.length; i++) {\n if(A[i] >= L && A[i] <= R) {\n res += i - j + 1\n count = i - j + 1\n } else if(A[i] < L) {\n res += count\n } else {\n j = i + 1\n count = 0\n }\n }\n return res\n};\n\n// another\n\n/**\n * @param {number[]} nums\n * @param {number} left\n * @param {number} right\n * @return {number}\n */\nconst numSubarrayBoundedMax = function(nums, left, right) {\n let prev = -1, dp = 0, res = 0\n for(let i = 0, n = nums.length; i < n; i++) {\n const cur = nums[i]\n if(cur < left) res += dp\n else if(cur > right) {\n dp = 0\n prev = i\n } else {\n dp = i - prev\n res += dp\n }\n }\n return res\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720c64", + "questionid": 409, + "title": "Find Eventual Safe States", + "slug": "find-eventual-safe-states", + "description": "There is a directed graph of n nodes with each node labeled from 0 to n - 1. The graph is represented by a 0-indexed 2D integer array graph where graph[i] is an integer array of nodes adjacent to node i, meaning there is an edge from node i to each node in graph[i]. A node is a terminal node if there are no outgoing edges. A node is a safe node if every possible path starting from that node leads to a terminal node. Return an array containing all the safe nodes of the graph. The answer should be sorted in ascending order. ", + "category": [ + "Depth-First Search", + "Breadth-First Search", + "Graph", + "Topological Sort" + ], + "complexity": "Medium", + "successrate": 52.5, + "totalsubmissions": 145782, + "totalaccepted": 76472, + "likes": 2014, + "dislikes": 313, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "graph = [[1,2],[2,3],[5],[0],[5],[],[]]", + "expected_output": "[2,4,5,6]", + "explanation": "The given graph is shown above.\nNodes 5 and 6 are terminal nodes as there are no outgoing edges from either of them.\nEvery path starting at nodes 2, 4, 5, and 6 all lead to either node 5 or 6." + }, + { + "example_num": 2, + "expected_input": "graph = [[1,2,3,4],[1,2],[3,4],[0,4],[]]", + "expected_output": "[4]", + "explanation": "Only node 4 is a terminal node, and every path starting at node 4 leads to node 4." + } + ], + "solution": "/**\n * @param {number[][]} graph\n * @return {number[]}\n */\nconst eventualSafeNodes = function (graph) {\n const ing = {},\n n = graph.length\n const outDegree = Array(n).fill(0)\n let q = []\n for (let i = 0; i < n; i++) {\n outDegree[i] = graph[i].length\n if (outDegree[i] === 0) {\n q.push(i)\n }\n for (const e of graph[i]) {\n if (ing[e] == null) ing[e] = []\n ing[e].push(i)\n }\n }\n\n for (const term of q) {\n for (const come of ing[term] || []) {\n outDegree[come]--\n if (outDegree[come] === 0) q.push(come)\n }\n }\n q.sort((a, b) => a - b)\n return q\n}\n\n// another\n\n\n/**\n * @param {number[][]} graph\n * @return {number[]}\n */\nconst eventualSafeNodes = function(graph) {\n const n = graph.length, memo = {}, visited = new Set(), res = []\n for(let i = 0; i < n; i++) {\n if(!dfs(graph, i, memo, visited)) res.push(i)\n }\n return res\n};\n\nfunction dfs(graph, node, memo, visited) {\n if(memo[node] != null) return memo[node]\n let hasCycle = false\n visited.add(node)\n for(let e of graph[node]) {\n if(visited.has(e) || dfs(graph, e, memo, visited)) {\n hasCycle = true\n break\n }\n }\n visited.delete(node)\n memo[node] = hasCycle\n return hasCycle\n}\n\n// another\n\n/**\n * @param {number[][]} graph\n * @return {number[]}\n */\nconst eventualSafeNodes = function(graph) {\n const res = []\n if(graph == null || graph.length === 0) return res\n const n = graph.length\n const color = Array(n).fill(0)\n for(let i = 0; i < n; i++) {\n if(bt(graph, i, color)) res.push(i)\n }\n return res\n\n function bt(graph, start, color) {\n if(color[start] !== 0) return color[start] === 1\n color[start] = 2\n for(let next of graph[start]) {\n if(!bt(graph, next, color)) return false\n }\n color[start] = 1\n return true\n }\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720c66", + "questionid": 411, + "title": "Max Increase to Keep City Skyline", + "slug": "max-increase-to-keep-city-skyline", + "description": "There is a city composed of n x n blocks, where each block contains a single building shaped like a vertical square prism. You are given a 0-indexed n x n integer matrix grid where grid[r][c] represents the height of the building located in the block at row r and column c. A city's skyline is the the outer contour formed by all the building when viewing the side of the city from a distance. The skyline from each cardinal direction north, east, south, and west may be different. We are allowed to increase the height of any number of buildings by any amount (the amount can be different per building). The height of a 0-height building can also be increased. However, increasing the height of a building should not affect the city's skyline from any cardinal direction. Return the maximum total sum that the height of the buildings can be increased by without changing the city's skyline from any cardinal direction. ", + "category": [ + "Array", + "Greedy", + "Matrix" + ], + "complexity": "Medium", + "successrate": 85.5, + "totalsubmissions": 143254, + "totalaccepted": 122448, + "likes": 1688, + "dislikes": 413, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "grid = [[3,0,8,4],[2,4,5,7],[9,2,6,3],[0,3,1,0]]", + "expected_output": "35", + "explanation": "The building heights are shown in the center of the above image.\nThe skylines when viewed from each cardinal direction are drawn in red.\nThe grid after increasing the height of buildings without affecting skylines is:\ngridNew = [ [8, 4, 8, 7],\n [7, 4, 7, 7],\n [9, 4, 8, 7],\n [3, 3, 3, 3] ]" + }, + { + "example_num": 2, + "expected_input": "grid = [[0,0,0],[0,0,0],[0,0,0]]", + "expected_output": "0", + "explanation": "Increasing the height of any building will result in the skyline changing." + } + ], + "solution": null + }, + { + "_id": "66f925ddfdfb8e1665720c68", + "questionid": 413, + "title": "Subdomain Visit Count", + "slug": "subdomain-visit-count", + "description": "A website domain \"discuss.leetcode.com\" consists of various subdomains. At the top level, we have \"com\", at the next level, we have \"leetcode.com\"\u00a0and at the lowest level, \"discuss.leetcode.com\". When we visit a domain like \"discuss.leetcode.com\", we will also visit the parent domains \"leetcode.com\" and \"com\" implicitly. A count-paired domain is a domain that has one of the two formats \"rep d1.d2.d3\" or \"rep d1.d2\" where rep is the number of visits to the domain and d1.d2.d3 is the domain itself. Given an array of count-paired domains cpdomains, return an array of the count-paired domains of each subdomain in the input. You may return the answer in any order. ", + "category": [ + "Array", + "Hash Table", + "String", + "Counting" + ], + "complexity": "Medium", + "successrate": 74.2, + "totalsubmissions": 228000, + "totalaccepted": 169116, + "likes": 1050, + "dislikes": 1109, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "cpdomains = ["9001 discuss.leetcode.com"]", + "expected_output": "["9001 leetcode.com","9001 discuss.leetcode.com","9001 com"]", + "explanation": "We only have one website domain: "discuss.leetcode.com".\nAs discussed above, the subdomain "leetcode.com" and "com" will also be visited. So they will all be visited 9001 times." + }, + { + "example_num": 2, + "expected_input": "cpdomains = ["900 google.mail.com", "50 yahoo.com", "1 intel.mail.com", "5 wiki.org"]", + "expected_output": "["901 mail.com","50 yahoo.com","900 google.mail.com","5 wiki.org","5 org","1 intel.mail.com","951 com"]", + "explanation": "We will visit "google.mail.com" 900 times, "yahoo.com" 50 times, "intel.mail.com" once and "wiki.org" 5 times.\nFor the subdomains, we will visit "mail.com" 900 + 1 = 901 times, "com" 900 + 50 + 1 = 951 times, and "org" 5 times." + } + ], + "solution": null + }, + { + "_id": "66f925ddfdfb8e1665720c70", + "questionid": 421, + "title": "Shortest Distance to a Character", + "slug": "shortest-distance-to-a-character", + "description": "Given a string s and a character c that occurs in s, return an array of integers answer where answer.length == s.length and answer[i] is the distance from index i to the closest occurrence of character c in s. The distance between two indices i and j is abs(i - j), where abs is the absolute value function. ", + "category": [ + "Array", + "Two Pointers", + "String" + ], + "complexity": "Easy", + "successrate": 70.9, + "totalsubmissions": 184202, + "totalaccepted": 130681, + "likes": 2162, + "dislikes": 120, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "loveleetcode", c = "e"", + "expected_output": "[3,2,1,0,1,0,0,1,2,2,1,0]", + "explanation": "The character 'e' appears at indices 3, 5, 6, and 11 (0-indexed).\nThe closest occurrence of 'e' for index 0 is at index 3, so the distance is abs(0 - 3) = 3.\nThe closest occurrence of 'e' for index 1 is at index 3, so the distance is abs(1 - 3) = 2.\nFor index 4, there is a tie between the 'e' at index 3 and the 'e' at index 5, but the distance is still the same: abs(4 - 3) == abs(4 - 5) = 1.\nThe closest occurrence of 'e' for index 8 is at index 6, so the distance is abs(8 - 6) = 2." + }, + { + "example_num": 2, + "expected_input": "s = "aaab", c = "b"", + "expected_output": "[3,2,1,0]", + "explanation": "" + } + ], + "solution": "/**\n * @param {string} S\n * @param {character} C\n * @return {number[]}\n */\nconst shortestToChar = function(S, C) {\n const res = [];\n const idxArr = [];\n for (let i = 0; i < S.length; i++) {\n S.charAt(i) === C ? idxArr.push(i) : null;\n }\n let coordIdx = 0;\n let nextCoordIdx = 1;\n let val;\n for (let idx = 0; idx < S.length; idx++) {\n if (S.charAt(idx) === C) {\n val = 0;\n nextCoordIdx = idxArr[coordIdx + 1] == null ? coordIdx : coordIdx + 1;\n if (\n Math.abs(idxArr[coordIdx] - idx) >= Math.abs(idxArr[nextCoordIdx] - idx)\n ) {\n coordIdx = idxArr[coordIdx + 1] == null ? coordIdx : coordIdx + 1;\n }\n } else {\n nextCoordIdx = idxArr[coordIdx + 1] == null ? coordIdx : coordIdx + 1;\n if (\n Math.abs(idxArr[coordIdx] - idx) < Math.abs(idxArr[nextCoordIdx] - idx)\n ) {\n val = Math.abs(idxArr[coordIdx] - idx);\n } else {\n val = Math.abs(idxArr[nextCoordIdx] - idx);\n coordIdx = idxArr[coordIdx + 1] == null ? coordIdx : coordIdx + 1;\n }\n }\n res[idx] = val;\n }\n return res;\n};\n\nconsole.log(shortestToChar(\"aaab\", \"b\"));\nconsole.log(shortestToChar(\"bbba\", \"b\"));\n" + }, + { + "_id": "66f925ddfdfb8e1665720c76", + "questionid": 427, + "title": "Positions of Large Groups", + "slug": "positions-of-large-groups", + "description": "In a string s\u00a0of lowercase letters, these letters form consecutive groups of the same character. For example, a string like s = \"abbxxxxzyy\" has the groups \"a\", \"bb\", \"xxxx\", \"z\", and\u00a0\"yy\". A group is identified by an interval\u00a0[start, end], where\u00a0start\u00a0and\u00a0end\u00a0denote the start and end\u00a0indices (inclusive) of the group. In the above example,\u00a0\"xxxx\"\u00a0has the interval\u00a0[3,6]. A group is considered\u00a0large\u00a0if it has 3 or more characters. Return\u00a0the intervals of every large group sorted in\u00a0increasing order by start index. ", + "category": [ + "String" + ], + "complexity": "Easy", + "successrate": 51.4, + "totalsubmissions": 137434, + "totalaccepted": 70621, + "likes": 619, + "dislikes": 111, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "abbxxxxzzy"", + "expected_output": "[[3,6]]", + "explanation": ""xxxx" is the only large group with start index 3 and end index 6." + }, + { + "example_num": 2, + "expected_input": "s = "abc"", + "expected_output": "[]", + "explanation": "We have groups "a", "b", and "c", none of which are large groups." + }, + { + "example_num": 3, + "expected_input": "s = "abcdddeeeeaabbbcd"", + "expected_output": "[[3,5],[6,9],[12,14]]", + "explanation": "The large groups are "ddd", "eeee", and "bbb"." + } + ], + "solution": "/**\n * @param {string} S\n * @return {number[][]}\n */\nconst largeGroupPositions = function(S) {\n if (S.length === 0) return [];\n let prevChar = S[0];\n let curChar = S[0];\n let curStartIdx = 0;\n let curCount = 1;\n const res = [];\n let tmpChar;\n for (let i = 1; i < S.length; i++) {\n tmpChar = S[i];\n if (tmpChar === prevChar) {\n curCount += 1;\n } else {\n if (curCount >= 3) {\n res.push([curStartIdx, curStartIdx + curCount - 1]);\n }\n\n prevChar = S[i];\n curStartIdx = i;\n curCount = 1;\n }\n }\n\n if (curCount >= 3) {\n res.push([curStartIdx, curStartIdx + curCount - 1]);\n }\n\n return res;\n};\n\nconsole.log(largeGroupPositions(\"aaa\"));\nconsole.log(largeGroupPositions(\"abbxxxxzzy\"));\nconsole.log(largeGroupPositions(\"abcdddeeeeaabbbcd\"));\n" + }, + { + "_id": "66f925ddfdfb8e1665720c77", + "questionid": 428, + "title": "Flipping an Image", + "slug": "flipping-an-image", + "description": "Given an n x n binary matrix image, flip the image horizontally, then invert it, and return the resulting image. To flip an image horizontally means that each row of the image is reversed. To invert an image means that each 0 is replaced by 1, and each 1 is replaced by 0. ", + "category": [ + "Array", + "Two Pointers", + "Matrix", + "Simulation" + ], + "complexity": "Easy", + "successrate": 79.7, + "totalsubmissions": 365811, + "totalaccepted": 291381, + "likes": 2060, + "dislikes": 201, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "image = [[1,1,0],[1,0,1],[0,0,0]]", + "expected_output": "[[1,0,0],[0,1,0],[1,1,1]]", + "explanation": "First reverse each row: [[0,1,1],[1,0,1],[0,0,0]].\nThen, invert the image: [[1,0,0],[0,1,0],[1,1,1]]" + }, + { + "example_num": 2, + "expected_input": "image = [[1,1,0,0],[1,0,0,1],[0,1,1,1],[1,0,1,0]]", + "expected_output": "[[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]]", + "explanation": "First reverse each row: [[0,0,1,1],[1,0,0,1],[1,1,1,0],[0,1,0,1]].\nThen invert the image: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]]" + } + ], + "solution": null + }, + { + "_id": "66f925ddfdfb8e1665720c78", + "questionid": 429, + "title": "Sum of Distances in Tree", + "slug": "sum-of-distances-in-tree", + "description": "There is an undirected connected tree with n nodes labeled from 0 to n - 1 and n - 1 edges. You are given the integer n and the array edges where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the tree. Return an array answer of length n where answer[i] is the sum of the distances between the ith node in the tree and all other nodes. ", + "category": [ + "Dynamic Programming", + "Tree", + "Depth-First Search", + "Graph" + ], + "complexity": "Hard", + "successrate": 52.9, + "totalsubmissions": 76967, + "totalaccepted": 40727, + "likes": 2472, + "dislikes": 58, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 6, edges = [[0,1],[0,2],[2,3],[2,4],[2,5]]", + "expected_output": "[8,12,6,10,10,10]", + "explanation": "The tree is shown above.\nWe can see that dist(0,1) + dist(0,2) + dist(0,3) + dist(0,4) + dist(0,5)\nequals 1 + 1 + 2 + 2 + 2 = 8.\nHence, answer[0] = 8, and so on." + }, + { + "example_num": 2, + "expected_input": "n = 1, edges = []", + "expected_output": "[0]", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "n = 2, edges = [[1,0]]", + "expected_output": "[1,1]", + "explanation": "" + } + ], + "solution": "/**\n * @param {number} n\n * @param {number[][]} edges\n * @return {number[]}\n */\nvar sumOfDistancesInTree = function(n, edges) {\n const res = new Array(n).fill(0);\n const count = new Array(n).fill(1);\n const graph = Array.from({ length: n }, () => []);\n for (const [u, v] of edges) {\n graph[u].push(v);\n graph[v].push(u);\n }\n dfs1(0, -1);\n dfs2(0, -1);\n\n return res\n\n function dfs1(node, parent) {\n for (const child of graph[node]) {\n if (child === parent) {\n continue;\n }\n dfs1(child, node);\n count[node] += count[child];\n res[node] += res[child] + count[child];\n }\n }\n function dfs2(node, parent) {\n for (const child of graph[node]) {\n if (child === parent) {\n continue;\n }\n res[child] = res[node] - count[child] + n - count[child];\n dfs2(child, node);\n }\n }\n};\n\n// another\n\n/**\n * @param {number} N\n * @param {number[][]} edges\n * @return {number[]}\n */\nconst sumOfDistancesInTree = function (N, edges) {\n const graph = createGraph(N, edges)\n const counts = new Array(N).fill(0)\n const dists = new Array(N).fill(0)\n dists[0] = getCount(graph, 0, -1, counts).sum\n return transferDist(N, graph, 0, -1, counts, dists)\n}\n\nfunction transferDist(N, graph, u, pre, counts, dists) {\n if (pre >= 0) {\n const nRight = counts[u]\n const nLeft = N - nRight\n dists[u] = dists[pre] - nRight + nLeft\n }\n for (const v of graph[u]) {\n if (v !== pre) {\n transferDist(N, graph, v, u, counts, dists)\n }\n }\n return dists\n}\n\nfunction getCount(graph, u, pre, counts) {\n const output = { nNodes: 0, sum: 0 }\n for (const v of graph[u]) {\n if (v !== pre) {\n const result = getCount(graph, v, u, counts)\n output.nNodes += result.nNodes\n output.sum += result.nNodes + result.sum\n }\n }\n output.nNodes += 1\n counts[u] = output.nNodes\n return output\n}\n\nfunction createGraph(N, edges) {\n const graph = new Array(N).fill(null).map(() => [])\n for (const [u, v] of edges) {\n graph[u].push(v)\n graph[v].push(u)\n }\n return graph\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720c7d", + "questionid": 434, + "title": "Keys and Rooms", + "slug": "keys-and-rooms", + "description": "There are n rooms labeled from 0 to n - 1\u00a0and all the rooms are locked except for room 0. Your goal is to visit all the rooms. However, you cannot enter a locked room without having its key. When you visit a room, you may find a set of distinct keys in it. Each key has a number on it, denoting which room it unlocks, and you can take all of them with you to unlock the other rooms. Given an array rooms where rooms[i] is the set of keys that you can obtain if you visited room i, return true if you can visit all the rooms, or false otherwise. ", + "category": [ + "Depth-First Search", + "Breadth-First Search", + "Graph" + ], + "complexity": "Medium", + "successrate": 68.9, + "totalsubmissions": 274493, + "totalaccepted": 189061, + "likes": 2954, + "dislikes": 172, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "rooms = [[1],[2],[3],[]]", + "expected_output": "true", + "explanation": "We visit room 0 and pick up key 1.\nWe then visit room 1 and pick up key 2.\nWe then visit room 2 and pick up key 3.\nWe then visit room 3.\nSince we were able to visit every room, we return true." + }, + { + "example_num": 2, + "expected_input": "rooms = [[1,3],[3,0,1],[2],[0]]", + "expected_output": "false", + "explanation": "We can not enter room number 2 since the only key that unlocks it is in that room." + } + ], + "solution": "/**\n * @param {number[][]} rooms\n * @return {boolean}\n */\nconst canVisitAllRooms = function(rooms) {\n const stack = [];\n const seen = [];\n for (let i = 0; i < rooms.length; i++) {\n seen[i] = false;\n }\n seen[0] = true;\n stack.push(0);\n while (stack.length) {\n let node = stack.pop();\n for (let el of rooms[node]) {\n if (!seen[el]) {\n seen[el] = true;\n stack.push(el);\n }\n }\n }\n for (let el of seen) {\n if (!el) return false;\n }\n return true;\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720c85", + "questionid": 442, + "title": "Loud and Rich", + "slug": "loud-and-rich", + "description": "There is a group of n people labeled from 0 to n - 1 where each person has a different amount of money and a different level of quietness. You are given an array richer where richer[i] = [ai, bi] indicates that ai has more money than bi and an integer array quiet where quiet[i] is the quietness of the ith person. All the given data in richer are logically correct (i.e., the data will not lead you to a situation where x is richer than y and y is richer than x at the same time). Return an integer array answer where answer[x] = y if y is the least quiet person (that is, the person y with the smallest value of quiet[y]) among all people who definitely have equal to or more money than the person x. ", + "category": [ + "Array", + "Depth-First Search", + "Graph", + "Topological Sort" + ], + "complexity": "Medium", + "successrate": 56.6, + "totalsubmissions": 41245, + "totalaccepted": 23326, + "likes": 616, + "dislikes": 544, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "richer = [[1,0],[2,1],[3,1],[3,7],[4,3],[5,3],[6,3]], quiet = [3,2,5,4,6,1,7,0]", + "expected_output": "[5,5,2,5,4,5,6,7]", + "explanation": "answer[0] = 5.\nPerson 5 has more money than 3, which has more money than 1, which has more money than 0.\nThe only person who is quieter (has lower quiet[x]) is person 7, but it is not clear if they have more money than person 0.\nanswer[7] = 7.\nAmong all people that definitely have equal to or more money than person 7 (which could be persons 3, 4, 5, 6, or 7), the person who is the quietest (has lower quiet[x]) is person 7.\nThe other answers can be filled out with similar reasoning." + }, + { + "example_num": 2, + "expected_input": "richer = [], quiet = [0]", + "expected_output": "[0]", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[][]} richer\n * @param {number[]} quiet\n * @return {number[]}\n */\nconst loudAndRich = function(richer, quiet) {\n const hash = {}\n for(const [a, b] of richer) {\n if(hash[b] == null) hash[b] = []\n hash[b].push(a)\n }\n const n = quiet.length\n \n const res = []\n for(let i = 0; i < n; i++) {\n dfs(i)\n }\n \n return res\n \n function dfs(i) {\n if(res[i] != null) return res[i]\n res[i] = i\n \n const nxt = hash[i] || []\n for(const e of nxt) {\n if(quiet[dfs(e)] < quiet[res[i]]) res[i] = res[e]\n \n }\n return res[i]\n }\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720c55", + "questionid": 394, + "title": "Reaching Points", + "slug": "reaching-points", + "description": "Given four integers sx, sy, tx, and ty, return true if it is possible to convert the point (sx, sy) to the point (tx, ty) through some operations, or false otherwise. The allowed operation on some point (x, y) is to convert it to either (x, x + y) or (x + y, y). ", + "category": [ + "Math" + ], + "complexity": "Hard", + "successrate": 31.6, + "totalsubmissions": 131046, + "totalaccepted": 41397, + "likes": 936, + "dislikes": 161, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "sx = 1, sy = 1, tx = 3, ty = 5", + "expected_output": "true", + "explanation": "One series of moves that transforms the starting point to the target is:\n(1, 1) -> (1, 2)\n(1, 2) -> (3, 2)\n(3, 2) -> (3, 5)" + }, + { + "example_num": 2, + "expected_input": "sx = 1, sy = 1, tx = 2, ty = 2", + "expected_output": "false", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "sx = 1, sy = 1, tx = 1, ty = 1", + "expected_output": "true", + "explanation": "" + } + ], + "solution": "/**\n * @param {number} sx\n * @param {number} sy\n * @param {number} tx\n * @param {number} ty\n * @return {boolean}\n */\nconst reachingPoints = function(sx, sy, tx, ty) {\n while (tx >= sx && ty >= sy) {\n if (tx === ty) break;\n if (tx > ty) {\n if (ty > sy) tx %= ty;\n else return (tx - sx) % ty === 0;\n } else {\n if (tx > sx) ty %= tx;\n else return (ty - sy) % tx === 0;\n }\n }\n return tx === sx && ty === sy;\n};\n\n" + }, + { + "_id": "66f925ddfdfb8e1665720c59", + "questionid": 398, + "title": "Letter Case Permutation", + "slug": "letter-case-permutation", + "description": "Given a string s, you\u00a0can transform every letter individually to be lowercase or uppercase to create another string. Return a list of all possible strings we could create. Return the output in any order. ", + "category": [ + "String", + "Backtracking", + "Bit Manipulation" + ], + "complexity": "Medium", + "successrate": 72.3, + "totalsubmissions": 288601, + "totalaccepted": 208542, + "likes": 3215, + "dislikes": 142, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "a1b2"", + "expected_output": "["a1b2","a1B2","A1b2","A1B2"]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "s = "3z4"", + "expected_output": "["3z4","3Z4"]", + "explanation": "" + } + ], + "solution": "/**\n * @param {string} S\n * @return {string[]}\n */\nconst letterCasePermutation = function(S) {\n let res = []\n backtrack(res, \"\", 0, S)\n return res\n};\n\nconst backtrack = (res, sol, depth, S) => {\n if (depth == S.length) {\n res.push(sol)\n return\n }\n const c = S[depth]\n if (\"1234567890\".indexOf(c) != - 1) {\n backtrack(res, sol+c, depth + 1, S)\n } else {\n backtrack(res, sol+c.toLowerCase(), depth + 1, S)\n backtrack(res, sol+c.toUpperCase(), depth + 1, S)\n }\n}\n\nconsole.log(letterCasePermutation(\"a1b2\")) \nconsole.log(letterCasePermutation(\"3z4\")) \nconsole.log(letterCasePermutation(\"12345\")) " + }, + { + "_id": "66f925ddfdfb8e1665720c5a", + "questionid": 399, + "title": "K-th Smallest Prime Fraction", + "slug": "k-th-smallest-prime-fraction", + "description": "You are given a sorted integer array arr containing 1 and prime numbers, where all the integers of arr are unique. You are also given an integer k. For every i and j where 0 <= i < j < arr.length, we consider the fraction arr[i] / arr[j]. Return the kth smallest fraction considered. Return your answer as an array of integers of size 2, where answer[0] == arr[i] and answer[1] == arr[j]. ", + "category": [ + "Array", + "Binary Search", + "Heap (Priority Queue)" + ], + "complexity": "Hard", + "successrate": 48.4, + "totalsubmissions": 53283, + "totalaccepted": 25777, + "likes": 741, + "dislikes": 37, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "arr = [1,2,3,5], k = 3", + "expected_output": "[2,5]", + "explanation": "The fractions to be considered in sorted order are:\n1/5, 1/3, 2/5, 1/2, 3/5, and 2/3.\nThe third fraction is 2/5." + }, + { + "example_num": 2, + "expected_input": "arr = [1,7], k = 1", + "expected_output": "[1,7]", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} arr\n * @param {number} k\n * @return {number[]}\n */\nvar kthSmallestPrimeFraction = function(arr, k) {\n const A = arr, K = k\n let ans = []\n let left = 0.0\n let right = 1.0\n while (right - left > 1e-9) {\n const mid = left + (right - left) / 2\n const { count, p, q } = maxUnder(mid, A)\n if (count >= K) {\n ans = [p, q]\n right = mid\n } else {\n left = mid\n }\n }\n return ans\n\n function maxUnder(x, primes) {\n let [p, q] = [0, 1]\n let count = 0\n let l = -1\n for (let r = 1; r < primes.length; r++) {\n while (primes[l + 1] < primes[r] * x) {\n l += 1\n }\n count += l + 1\n if (l >= 0 && p * primes[r] < q * primes[l]) {\n ;[p, q] = [primes[l], primes[r]]\n }\n }\n return { count, p, q }\n }\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720c5b", + "questionid": 400, + "title": "Cheapest Flights Within K Stops", + "slug": "cheapest-flights-within-k-stops", + "description": "There are n cities connected by some number of flights. You are given an array flights where flights[i] = [fromi, toi, pricei] indicates that there is a flight from city fromi to city toi with cost pricei. You are also given three integers src, dst, and k, return the cheapest price from src to dst with at most k stops. If there is no such route, return -1. ", + "category": [ + "Dynamic Programming", + "Depth-First Search", + "Breadth-First Search", + "Graph", + "Heap (Priority Queue)", + "Shortest Path" + ], + "complexity": "Medium", + "successrate": 36.1, + "totalsubmissions": 631258, + "totalaccepted": 227605, + "likes": 4765, + "dislikes": 212, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 4, flights = [[0,1,100],[1,2,100],[2,0,100],[1,3,600],[2,3,200]], src = 0, dst = 3, k = 1", + "expected_output": "700", + "explanation": "The graph is shown above.\nThe optimal path with at most 1 stop from city 0 to 3 is marked in red and has cost 100 + 600 = 700.\nNote that the path through cities [0,1,2,3] is cheaper but is invalid because it uses 2 stops." + }, + { + "example_num": 2, + "expected_input": "n = 3, flights = [[0,1,100],[1,2,100],[0,2,500]], src = 0, dst = 2, k = 1", + "expected_output": "200", + "explanation": "The graph is shown above.\nThe optimal path with at most 1 stop from city 0 to 2 is marked in red and has cost 100 + 100 = 200." + }, + { + "example_num": 3, + "expected_input": "n = 3, flights = [[0,1,100],[1,2,100],[0,2,500]], src = 0, dst = 2, k = 0", + "expected_output": "500", + "explanation": "The graph is shown above.\nThe optimal path with no stops from city 0 to 2 is marked in red and has cost 500." + } + ], + "solution": "/**\n * @param {number} n\n * @param {number[][]} flights\n * @param {number} src\n * @param {number} dst\n * @param {number} K\n * @return {number}\n */\nconst findCheapestPrice = function(n, flights, src, dst, K) {\n const arr = Array(n).fill(Infinity)\n arr[src] = 0\n const g = {}\n for(const [u,v,p] of flights) {\n if(g[u] == null) g[u] = []\n g[u].push([v, p])\n }\n\n let step = 0\n let q = [[src,0]]\n while(step < K + 1 && q.length) {\n const len = q.length\n const row = []\n for(let i = 0; i < len; i++) {\n const el = q[i]\n const [s, dis] = el\n for(const e of (g[s] || [])) {\n const [nxt, p] = e\n if(arr[nxt] > p + dis) {\n arr[nxt] = p + dis\n row.push([nxt, arr[nxt]])\n }\n \n } \n }\n q = row\n step++\n }\n \n return arr[dst] === Infinity ? -1 : arr[dst]\n}\n\n// another\n\n/**\n * @param {number} n\n * @param {number[][]} flights\n * @param {number} src\n * @param {number} dst\n * @param {number} K\n * @return {number}\n */\n\nconst findCheapestPrice = function(n, flights, src, dst, K) {\n let mn = new Array(n + 1).fill(Infinity);\n mn[src] = 0;\n for(let k = 0; k < K + 1; k++){\n let newmn = [].concat(mn);\n for(let i = 0; i < flights.length; i++){\n let f = flights[i], a = f[0], b = f[1], c = f[2];\n newmn[b] = Math.min(newmn[b], mn[a] + c);\n }\n mn = [].concat(newmn);\n }\n return mn[dst] != Infinity ? mn[dst] : -1\n}\n\n// another\nconst findCheapestPrice = function(n, flights, src, dst, K) {\n const map = [];\n flights.forEach(([s, d, p]) => {\n map[s] = map[s] || [];\n map[s][d] = p;\n });\n let min = Infinity;\n const p = find(src, 0, 0);\n return p === Infinity ? -1 : p;\n \n function find(s, p, c) {\n if (s === dst) {\n return p;\n }\n const l = map[s];\n if (c > K || p > min || !l) {\n return Infinity;\n }\n l.forEach((p1, d) => {\n min = Math.min(min, find(d, p + p1, c + 1));\n });\n return min;\n }\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720c6c", + "questionid": 417, + "title": "Bus Routes", + "slug": "bus-routes", + "description": "You are given an array routes representing bus routes where routes[i] is a bus route that the ith bus repeats forever. You will start at the bus stop source (You are not on any bus initially), and you want to go to the bus stop target. You can travel between bus stops by buses only. Return the least number of buses you must take to travel from source to target. Return -1 if it is not possible. ", + "category": [ + "Array", + "Hash Table", + "Breadth-First Search" + ], + "complexity": "Hard", + "successrate": 45.3, + "totalsubmissions": 183370, + "totalaccepted": 83037, + "likes": 1992, + "dislikes": 51, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "routes = [[1,2,7],[3,6,7]], source = 1, target = 6", + "expected_output": "2", + "explanation": "The best strategy is take the first bus to the bus stop 7, then take the second bus to the bus stop 6." + }, + { + "example_num": 2, + "expected_input": "routes = [[7,12],[4,5,15],[6],[15,19],[9,12,13]], source = 15, target = 12", + "expected_output": "-1", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[][]} routes\n * @param {number} S\n * @param {number} T\n * @return {number}\n */\nconst numBusesToDestination = function (routes, S, T) {\n if (S === T) return 0\n const map = {}\n const visited = new Array(routes.length).fill(false),\n queue = [S]\n let rides = 0\n for (let i = 0; i < routes.length; i++) {\n for (const stop of routes[i]) {\n if (map[stop] === undefined) {\n map[stop] = []\n }\n map[stop].push(i)\n }\n }\n while (queue.length > 0) {\n let size = queue.length\n rides += 1\n while (size > 0) {\n const currStop = queue.shift()\n size -= 1\n for (const bus of map[currStop]) {\n if (visited[bus]) continue\n visited[bus] = true\n for (const stop of routes[bus]) {\n if (stop === T) return rides\n queue.push(stop)\n }\n }\n }\n }\n return -1\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720c6e", + "questionid": 419, + "title": "Linked List Components", + "slug": "linked-list-components", + "description": "You are given the head of a linked list containing unique integer values and an integer array nums that is a subset of the linked list values. Return the number of connected components in nums where two values are connected if they appear consecutively in the linked list. ", + "category": [ + "Hash Table", + "Linked List" + ], + "complexity": "Medium", + "successrate": 58, + "totalsubmissions": 117314, + "totalaccepted": 68083, + "likes": 696, + "dislikes": 1743, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "head = [0,1,2,3], nums = [0,1,3]", + "expected_output": "2", + "explanation": "0 and 1 are connected, so [0, 1] and [3] are the two connected components." + }, + { + "example_num": 2, + "expected_input": "head = [0,1,2,3,4], nums = [0,3,1,4]", + "expected_output": "2", + "explanation": "0 and 1 are connected, 3 and 4 are connected, so [0, 1] and [3, 4] are the two connected components." + } + ], + "solution": null + }, + { + "_id": "66f925ddfdfb8e1665720c73", + "questionid": 424, + "title": "Making A Large Island", + "slug": "making-a-large-island", + "description": "You are given an n x n binary matrix grid. You are allowed to change at most one 0 to be 1. Return the size of the largest island in grid after applying this operation. An island is a 4-directionally connected group of 1s. ", + "category": [ + "Array", + "Depth-First Search", + "Breadth-First Search", + "Union Find", + "Matrix" + ], + "complexity": "Hard", + "successrate": 44.7, + "totalsubmissions": 236442, + "totalaccepted": 105794, + "likes": 2242, + "dislikes": 48, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "grid = [[1,0],[0,1]]", + "expected_output": "3", + "explanation": "Change one 0 to 1 and connect two 1s, then we get an island with area = 3." + }, + { + "example_num": 2, + "expected_input": "grid = [[1,1],[1,0]]", + "expected_output": "4\nExplanation: Change the 0 to 1 and make the island bigger, only one island with area = 4.", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "grid = [[1,1],[1,1]]", + "expected_output": "4", + "explanation": "Can't change any 0 to 1, only one island with area = 4." + } + ], + "solution": "/**\n * @param {number[][]} grid\n * @return {number}\n */\nfunction largestIsland(grid) {\n const map = new Map() //Key: color, Val: size of island painted of that color\n map.set(0, 0) //We won't paint island 0, hence make its size 0, we will use this value later\n let n = grid.length\n let colorIndex = 2 //0 and 1 is already used in grid, hence we start colorIndex from 2\n for (let i = 0; i < n; i++) {\n for (let j = 0; j < n; j++) {\n if (grid[i][j] == 1) {\n let size = paint(grid, i, j, colorIndex)\n map.set(colorIndex, size)\n colorIndex++\n }\n }\n }\n\n //If there is no island 0 from grid, res should be the size of islands of first color\n //If there is no island 1 from grid, res should be 0\n let res = map.get(2) || 0\n for (let i = 0; i < n; i++) {\n for (let j = 0; j < n; j++) {\n if (grid[i][j] === 0) {\n //We use a set to avoid repeatly adding islands with the same color\n const set = new Set()\n //If current island is at the boundary, we add 0 to the set, whose value is 0 in the map\n set.add(i > 0 ? grid[i - 1][j] : 0)\n set.add(i < n - 1 ? grid[i + 1][j] : 0)\n set.add(j > 0 ? grid[i][j - 1] : 0)\n set.add(j < n - 1 ? grid[i][j + 1] : 0)\n\n let newSize = 1 //We need to count current island as well, hence we init newSize with 1\n for (let color of set) newSize += map.get(color)\n res = Math.max(res, newSize)\n }\n }\n }\n return res\n}\n\n//Helper method to paint current island and all its connected neighbors\n//Return the size of all painted islands at the end\nfunction paint(grid, i, j, color) {\n if (i < 0 || j < 0 || i >= grid.length || j >= grid[0].length || grid[i][j] != 1) return 0\n grid[i][j] = color\n return (\n 1 +\n paint(grid, i + 1, j, color) +\n paint(grid, i - 1, j, color) +\n paint(grid, i, j + 1, color) +\n paint(grid, i, j - 1, color)\n )\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720c7a", + "questionid": 431, + "title": "Rectangle Overlap", + "slug": "rectangle-overlap", + "description": "An axis-aligned rectangle is represented as a list [x1, y1, x2, y2], where (x1, y1) is the coordinate of its bottom-left corner, and (x2, y2) is the coordinate of its top-right corner. Its top and bottom edges are parallel to the X-axis, and its left and right edges are parallel to the Y-axis. Two rectangles overlap if the area of their intersection is positive. To be clear, two rectangles that only touch at the corner or edges do not overlap. Given two axis-aligned rectangles rec1 and rec2, return true if they overlap, otherwise return false. ", + "category": [ + "Math", + "Geometry" + ], + "complexity": "Easy", + "successrate": 43.1, + "totalsubmissions": 232372, + "totalaccepted": 100219, + "likes": 1385, + "dislikes": 383, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "rec1 = [0,0,2,2], rec2 = [1,1,3,3]", + "expected_output": "true", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "rec1 = [0,0,1,1], rec2 = [1,0,2,1]", + "expected_output": "false", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "rec1 = [0,0,1,1], rec2 = [2,2,3,3]", + "expected_output": "false", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} rec1\n * @param {number[]} rec2\n * @return {boolean}\n */\nconst isRectangleOverlap = function(rec1, rec2) {\n return !(\n chkOverlap(rec1, rec2) === false || chkOverlap(rec2, rec1) === false\n );\n};\nfunction chkOverlap(r1, r2) {\n if (r1[2] <= r2[0] || r1[3] <= r2[1]) {\n return false;\n } else {\n return true;\n }\n}\n\nconsole.log(isRectangleOverlap([0, 0, 2, 2], [1, 1, 3, 3]));\nconsole.log(isRectangleOverlap([0, 0, 1, 1], [1, 0, 2, 1]));\n" + }, + { + "_id": "66f925ddfdfb8e1665720c7f", + "questionid": 436, + "title": "Backspace String Compare", + "slug": "backspace-string-compare", + "description": "Given two strings s and t, return true if they are equal when both are typed into empty text editors. '#' means a backspace character. Note that after backspacing an empty text, the text will continue empty. ", + "category": [ + "Two Pointers", + "String", + "Stack", + "Simulation" + ], + "complexity": "Easy", + "successrate": 47.3, + "totalsubmissions": 860272, + "totalaccepted": 406718, + "likes": 3801, + "dislikes": 185, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "ab#c", t = "ad#c"", + "expected_output": "true", + "explanation": "Both s and t become "ac"." + }, + { + "example_num": 2, + "expected_input": "s = "ab##", t = "c#d#"", + "expected_output": "true", + "explanation": "Both s and t become ""." + }, + { + "example_num": 3, + "expected_input": "s = "a#c", t = "b"", + "expected_output": "false", + "explanation": "s becomes "c" while t becomes "b"." + } + ], + "solution": "/**\n * @param {string} S\n * @param {string} T\n * @return {boolean}\n */\nconst backspaceCompare = function(S, T) {\n return chk(S) === chk(T)\n};\n\nfunction chk(str) {\n const s = []\n for(let i = 0, len = str.length; i < len; i++) {\n if(str[i] === '#') s.pop()\n else s.push(str[i])\n }\n return s.join('')\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720c80", + "questionid": 437, + "title": "Hand of Straights", + "slug": "hand-of-straights", + "description": "Alice has some number of cards and she wants to rearrange the cards into groups so that each group is of size groupSize, and consists of groupSize consecutive cards. Given an integer array hand where hand[i] is the value written on the ith card and an integer groupSize, return true if she can rearrange the cards, or false otherwise. ", + "category": [ + "Array", + "Hash Table", + "Greedy", + "Sorting" + ], + "complexity": "Medium", + "successrate": 56.2, + "totalsubmissions": 153110, + "totalaccepted": 86064, + "likes": 1322, + "dislikes": 113, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "hand = [1,2,3,6,2,3,4,7,8], groupSize = 3", + "expected_output": "true", + "explanation": "Alice's hand can be rearranged as [1,2,3],[2,3,4],[6,7,8]" + }, + { + "example_num": 2, + "expected_input": "hand = [1,2,3,4,5], groupSize = 4", + "expected_output": "false", + "explanation": "Alice's hand can not be rearranged into groups of 4." + } + ], + "solution": null + }, + { + "_id": "66f925ddfdfb8e1665720c83", + "questionid": 440, + "title": "Maximize Distance to Closest Person", + "slug": "maximize-distance-to-closest-person", + "description": "You are given an array representing a row of seats where seats[i] = 1 represents a person sitting in the ith seat, and seats[i] = 0 represents that the ith seat is empty (0-indexed). There is at least one empty seat, and at least one person sitting. Alex wants to sit in the seat such that the distance between him and the closest person to him is maximized. Return that maximum distance to the closest person. ", + "category": [ + "Array" + ], + "complexity": "Medium", + "successrate": 47.4, + "totalsubmissions": 359728, + "totalaccepted": 170547, + "likes": 2552, + "dislikes": 163, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "seats = [1,0,0,0,1,0,1]", + "expected_output": "2\nExplanation: \nIf Alex sits in the second open seat (i.e. seats[2]), then the closest person has distance 2.\nIf Alex sits in any other open seat, the closest person has distance 1.\nThus, the maximum distance to the closest person is 2.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "seats = [1,0,0,0]", + "expected_output": "3\nExplanation: \nIf Alex sits in the last seat (i.e. seats[3]), the closest person is 3 seats away.\nThis is the maximum distance possible, so the answer is 3.", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "seats = [0,1]", + "expected_output": "1", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} seats\n * @return {number}\n */\nconst maxDistToClosest = function(seats) {\n let left, right, res = 0, n = seats.length;\n for (left = right = 0; right < n; ++right)\n if (seats[right] === 1) {\n if (left === 0) res = Math.max(res, right - left);\n else res = Math.max(res, Math.floor((right - left + 1) / 2));\n left = right + 1;\n }\n res = Math.max(res, n - left);\n return res;\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720c84", + "questionid": 441, + "title": "Rectangle Area II", + "slug": "rectangle-area-ii", + "description": "You are given a 2D array of axis-aligned rectangles. Each rectangle[i] = [xi1, yi1, xi2, yi2] denotes the ith rectangle where (xi1, yi1) are the coordinates of the bottom-left corner, and (xi2, yi2) are the coordinates of the top-right corner. Calculate the total area covered by all rectangles in the plane. Any area covered by two or more rectangles should only be counted once. Return the total area. Since the answer may be too large, return it modulo 109 + 7. ", + "category": [ + "Array", + "Segment Tree", + "Line Sweep", + "Ordered Set" + ], + "complexity": "Hard", + "successrate": 53.3, + "totalsubmissions": 54704, + "totalaccepted": 29148, + "likes": 772, + "dislikes": 51, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "rectangles = [[0,0,2,2],[1,0,2,3],[1,0,3,1]]", + "expected_output": "6", + "explanation": "A total area of 6 is covered by all three rectangles, as illustrated in the picture.\nFrom (1,1) to (2,2), the green and red rectangles overlap.\nFrom (1,0) to (2,3), all three rectangles overlap." + }, + { + "example_num": 2, + "expected_input": "rectangles = [[0,0,1000000000,1000000000]]", + "expected_output": "49", + "explanation": "The answer is 1018 modulo (109 + 7), which is 49." + } + ], + "solution": "/**\n * @param {number[][]} rectangles\n * @return {number}\n */\nconst rectangleArea = function(rectangles) {\n let xnodes = rectangles.reduce((arr, rect) => {\n arr.push(rect[0], rect[2])\n return arr\n }, [])\n xnodes = [...new Set(xnodes)].sort((a, b) => a - b)\n let res = 0n\n let overlay\n let ynodes\n let ysum\n for (let i = 1; i < xnodes.length; i++) {\n overlay = []\n rectangles.forEach(rect => {\n if (rect[0] <= xnodes[i - 1] && rect[2] >= xnodes[i]) overlay.push(rect)\n })\n ynodes = overlay.reduce((set, rect) => {\n set.add(rect[1])\n set.add(rect[3])\n return set\n }, new Set())\n ynodes = [...ynodes].sort((a, b) => a - b)\n ysum = 0n\n for (let i = 1; i < ynodes.length; i++) {\n for (let j = 0; j < overlay.length; j++) {\n if (overlay[j][1] <= ynodes[i - 1] && overlay[j][3] >= ynodes[i]) {\n ysum += BigInt(ynodes[i] - ynodes[i - 1])\n break\n }\n }\n }\n res += ysum * BigInt(xnodes[i] - xnodes[i - 1])\n }\n return Number(res % BigInt(Math.pow(10, 9) + 7))\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720c86", + "questionid": 443, + "title": "Car Fleet", + "slug": "car-fleet", + "description": "There are n cars going to the same destination along a one-lane road. The destination is target miles away. You are given two integer array position and speed, both of length n, where position[i] is the position of the ith car and speed[i] is the speed of the ith car (in miles per hour). A car can never pass another car ahead of it, but it can catch up to it\u00a0and drive bumper to bumper at the same speed. The faster car will slow down to match the slower car's speed. The distance between these two cars is ignored (i.e., they are assumed to have the same position). A car fleet is some non-empty set of cars driving at the same position and same speed. Note that a single car is also a car fleet. If a car catches up to a car fleet right at the destination point, it will still be considered as one car fleet. Return the number of car fleets that will arrive at the destination. ", + "category": [ + "Array", + "Stack", + "Sorting", + "Monotonic Stack" + ], + "complexity": "Medium", + "successrate": 48, + "totalsubmissions": 160651, + "totalaccepted": 77114, + "likes": 1333, + "dislikes": 397, + "hints": "", + "deleted": false, + "examples": [], + "solution": null + }, + { + "_id": "66f925ddfdfb8e1665720c87", + "questionid": 444, + "title": "K-Similar Strings", + "slug": "k-similar-strings", + "description": "Strings s1 and s2 are k-similar (for some non-negative integer k) if we can swap the positions of two letters in s1 exactly k times so that the resulting string equals s2. Given two anagrams s1 and s2, return the smallest k for which s1 and s2 are k-similar. ", + "category": [ + "String", + "Breadth-First Search" + ], + "complexity": "Hard", + "successrate": 39.3, + "totalsubmissions": 81593, + "totalaccepted": 32042, + "likes": 801, + "dislikes": 48, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s1 = "ab", s2 = "ba"", + "expected_output": "1", + "explanation": "The two string are 1-similar because we can use one swap to change s1 to s2: "ab" --> "ba"." + }, + { + "example_num": 2, + "expected_input": "s1 = "abc", s2 = "bca"", + "expected_output": "2", + "explanation": "The two strings are 2-similar because we can use two swaps to change s1 to s2: "abc" --> "bac" --> "bca"." + } + ], + "solution": "/**\n * @param {string} A\n * @param {string} B\n * @return {number}\n */\nconst kSimilarity = function(A, B) {\n if (A === B) return 0\n let arr = [[B, 0]]\n while (arr.length > 0) {\n let len = arr.length\n for (let i = 0; i < len; i++) {\n let [cur, step] = arr.shift()\n for (let i = 0; i < cur.length; i++) {\n if (cur[i] === A[i]) continue\n for (let j = i + 1; j < cur.length; j++) {\n if (cur[j] !== A[i]) continue\n let newStr =\n cur.substring(0, i) +\n cur[j] +\n cur.substring(i + 1, j) +\n cur[i] +\n cur.substring(j + 1)\n if (newStr === A) return step + 1\n if (cur[i] === A[j]) arr.unshift([newStr, step + 1])\n else arr.push([newStr, step + 1])\n }\n break\n }\n }\n }\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720c89", + "questionid": 446, + "title": "Buddy Strings", + "slug": "buddy-strings", + "description": "Given two strings s and goal, return true if you can swap two letters in s so the result is equal to goal, otherwise, return false. Swapping letters is defined as taking two indices i and j (0-indexed) such that i != j and swapping the characters at s[i] and s[j]. ", + "category": [ + "Hash Table", + "String" + ], + "complexity": "Easy", + "successrate": 28.8, + "totalsubmissions": 408704, + "totalaccepted": 117591, + "likes": 1384, + "dislikes": 879, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "ab", goal = "ba"", + "expected_output": "true", + "explanation": "You can swap s[0] = 'a' and s[1] = 'b' to get "ba", which is equal to goal." + }, + { + "example_num": 2, + "expected_input": "s = "ab", goal = "ab"", + "expected_output": "false", + "explanation": "The only letters you can swap are s[0] = 'a' and s[1] = 'b', which results in "ba" != goal." + }, + { + "example_num": 3, + "expected_input": "s = "aa", goal = "aa"", + "expected_output": "true", + "explanation": "You can swap s[0] = 'a' and s[1] = 'a' to get "aa", which is equal to goal." + } + ], + "solution": "/**\n * @param {string} A\n * @param {string} B\n * @return {boolean}\n */\nconst buddyStrings = function(A, B) {\n if(A.length !== B.length) return false\n const aCode = ('a').charCodeAt(0)\n if(A === B) {\n const count = new Array(26).fill(0)\n for(let i = 0; i < A.length; i++) {\n count[A.charCodeAt(i) - aCode]++\n }\n for(let el of count) {\n if(el > 1) return true\n }\n return false\n } else {\n const arr = []\n for(let i = 0; i < A.length; i++) {\n if(A[i] !== B[i]) {\n arr.push(i)\n if(arr.length > 2) return false\n }\n }\n if(arr.length !== 2) return false\n return A[arr[0]] === B[arr[1]] && A[arr[1]] === B[arr[0]]\n }\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720c8a", + "questionid": 447, + "title": "Lemonade Change", + "slug": "lemonade-change", + "description": "At a lemonade stand, each lemonade costs $5. Customers are standing in a queue to buy from you and order one at a time (in the order specified by bills). Each customer will only buy one lemonade and pay with either a $5, $10, or $20 bill. You must provide the correct change to each customer so that the net transaction is that the customer pays $5. Note that you do not have any change in hand at first. Given an integer array bills where bills[i] is the bill the ith customer pays, return true if you can provide every customer with the correct change, or false otherwise. ", + "category": [ + "Array", + "Greedy" + ], + "complexity": "Easy", + "successrate": 52.4, + "totalsubmissions": 180709, + "totalaccepted": 94723, + "likes": 1206, + "dislikes": 120, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "bills = [5,5,5,10,20]", + "expected_output": "true", + "explanation": "From the first 3 customers, we collect three $5 bills in order.\nFrom the fourth customer, we collect a $10 bill and give back a $5.\nFrom the fifth customer, we give a $10 bill and a $5 bill.\nSince all customers got correct change, we output true." + }, + { + "example_num": 2, + "expected_input": "bills = [5,5,10,10,20]", + "expected_output": "false", + "explanation": "From the first two customers in order, we collect two $5 bills.\nFor the next two customers in order, we collect a $10 bill and give back a $5 bill.\nFor the last customer, we can not give the change of $15 back because we only have two $10 bills.\nSince not every customer received the correct change, the answer is false." + } + ], + "solution": "/**\n * @param {number[]} bills\n * @return {boolean}\n */\nconst lemonadeChange = function(bills) {\n let five = 0;\n let ten = 0;\n for (let el of bills) {\n if (el === 5) {\n five += 1;\n } else if (el === 10) {\n if (five < 1) return false;\n five -= 1;\n ten += 1;\n } else {\n if (five > 0 && ten > 0) {\n five -= 1;\n ten -= 1;\n } else if (five >= 3) {\n five -= 3;\n } else {\n return false;\n }\n }\n }\n\n return true;\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720c8f", + "questionid": 452, + "title": "Transpose Matrix", + "slug": "transpose-matrix", + "description": "Given a 2D integer array matrix, return the transpose of matrix. The transpose of a matrix is the matrix flipped over its main diagonal, switching the matrix's row and column indices. ", + "category": [ + "Array", + "Matrix", + "Simulation" + ], + "complexity": "Easy", + "successrate": 61.1, + "totalsubmissions": 213787, + "totalaccepted": 130561, + "likes": 1139, + "dislikes": 371, + "hints": "We don't need any special algorithms to do this. You just need to know what the transpose of a matrix looks like. Rows become columns and vice versa!", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "matrix = [[1,2,3],[4,5,6],[7,8,9]]", + "expected_output": "[[1,4,7],[2,5,8],[3,6,9]]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "matrix = [[1,2,3],[4,5,6]]", + "expected_output": "[[1,4],[2,5],[3,6]]", + "explanation": "" + } + ], + "solution": null + }, + { + "_id": "66f925ddfdfb8e1665720c8d", + "questionid": 450, + "title": "All Nodes Distance K in Binary Tree", + "slug": "all-nodes-distance-k-in-binary-tree", + "description": "Given the root of a binary tree, the value of a target node target, and an integer k, return an array of the values of all nodes that have a distance k from the target node. You can return the answer in any order. ", + "category": [ + "Tree", + "Depth-First Search", + "Breadth-First Search", + "Binary Tree" + ], + "complexity": "Medium", + "successrate": 61, + "totalsubmissions": 369754, + "totalaccepted": 225513, + "likes": 6051, + "dislikes": 125, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [3,5,1,6,2,0,8,null,null,7,4], target = 5, k = 2", + "expected_output": "[7,4,1]\nExplanation: The nodes that are a distance 2 from the target node (with value 5) have values 7, 4, and 1.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "root = [1], target = 1, k = 3", + "expected_output": "[]", + "explanation": "" + } + ], + "solution": "/**\n * Definition for a binary tree node.\n * function TreeNode(val) {\n * this.val = val;\n * this.left = this.right = null;\n * }\n */\n/**\n * @param {TreeNode} root\n * @param {TreeNode} target\n * @param {number} K\n * @return {number[]}\n */\nconst distanceK = function(root, target, K) {\n const map = new Map();\n const res = [];\n if (target == null || K < 0 || root == null) return res;\n buildGraph(root, null);\n const visited = new Set();\n const q = [];\n visited.add(target);\n q.push(target);\n while (q.length) {\n const len = q.length;\n if (K === 0) {\n for (let i = 0; i < len; i++) res.push(q.shift().val);\n return res;\n }\n for (let i = 0; i < len; i++) {\n const el = q.shift();\n for (let e of map.get(el)) {\n if (visited.has(e)) continue;\n visited.add(e);\n q.push(e);\n }\n }\n K--;\n }\n return res;\n\n function buildGraph(node, parent) {\n if (node === null) return;\n if (!map.has(node)) {\n map.set(node, []);\n if (parent !== null) {\n map.get(node).push(parent);\n if (!map.has(parent)) map.set(parent, []);\n map.get(parent).push(node);\n }\n buildGraph(node.left, node);\n buildGraph(node.right, node);\n }\n }\n};\n\n// another\n\n/**\n * Definition for a binary tree node.\n * function TreeNode(val) {\n * this.val = val;\n * this.left = this.right = null;\n * }\n */\n/**\n * @param {TreeNode} root\n * @param {TreeNode} target\n * @param {number} K\n * @return {number[]}\n */\nconst distanceK = function(root, target, K) {\n let res = []\n dfs(root, target, K, res)\n return res\n}\n\nfunction dfs(node, target, k, res) {\n if (node === null) return -1\n if (node === target) {\n getRes(node, 0, k, res)\n return 1\n }\n let left = dfs(node.left, target, k, res)\n let right = dfs(node.right, target, k, res)\n if (left !== -1) {\n if (left === k) res.push(node.val)\n getRes(node.right, left + 1, k, res)\n return left + 1\n }\n if (right !== -1) {\n if (right === k) res.push(node.val)\n getRes(node.left, right + 1, k, res)\n return right + 1\n }\n return -1\n}\n\nfunction getRes(node, dist, k, res) {\n if (node === null) return\n if (dist === k) return res.push(node.val)\n getRes(node.left, dist + 1, k, res)\n getRes(node.right, dist + 1, k, res)\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720c91", + "questionid": 454, + "title": "Reordered Power of 2", + "slug": "reordered-power-of-2", + "description": "You are given an integer n. We reorder the digits in any order (including the original order) such that the leading digit is not zero. Return true if and only if we can do this so that the resulting number is a power of two. ", + "category": [ + "Math", + "Sorting", + "Counting", + "Enumeration" + ], + "complexity": "Medium", + "successrate": 61.3, + "totalsubmissions": 66480, + "totalaccepted": 40760, + "likes": 577, + "dislikes": 170, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 1", + "expected_output": "true", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "n = 10", + "expected_output": "false", + "explanation": "" + } + ], + "solution": "/**\n * @param {number} N\n * @return {boolean}\n */\nconst reorderedPowerOf2 = function(N) {\n const A = count(N);\n for (let i = 0; i < 31; i++) {\n if (arrayEqual(A, count(1 << i))) return true;\n }\n return false;\n};\n\nfunction count(num) {\n const res = [];\n while (num > 0) {\n addOne(res, num % 10);\n num = parseInt(num / 10);\n }\n return res;\n}\nfunction addOne(arr, idx) {\n if (arr[idx]) {\n arr[idx] += 1;\n return;\n }\n arr[idx] = 1;\n}\nfunction arrayEqual(a1, a2) {\n return JSON.stringify(a1) === JSON.stringify(a2);\n}\n\nconsole.log(reorderedPowerOf2(1));\nconsole.log(reorderedPowerOf2(10));\nconsole.log(reorderedPowerOf2(16));\nconsole.log(reorderedPowerOf2(24));\nconsole.log(reorderedPowerOf2(46));\n" + }, + { + "_id": "66f925ddfdfb8e1665720c93", + "questionid": 456, + "title": "Minimum Number of Refueling Stops", + "slug": "minimum-number-of-refueling-stops", + "description": "A car travels from a starting position to a destination which is target miles east of the starting position. There are gas stations along the way. The gas stations are represented as an array stations where stations[i] = [positioni, fueli] indicates that the ith gas station is positioni miles east of the starting position and has fueli liters of gas. The car starts with an infinite tank of gas, which initially has startFuel liters of fuel in it. It uses one liter of gas per one mile that it drives. When the car reaches a gas station, it may stop and refuel, transferring all the gas from the station into the car. Return the minimum number of refueling stops the car must make in order to reach its destination. If it cannot reach the destination, return -1. Note that if the car reaches a gas station with 0 fuel left, the car can still refuel there. If the car reaches the destination with 0 fuel left, it is still considered to have arrived. ", + "category": [ + "Array", + "Dynamic Programming", + "Greedy", + "Heap (Priority Queue)" + ], + "complexity": "Hard", + "successrate": 35.7, + "totalsubmissions": 195665, + "totalaccepted": 69794, + "likes": 2436, + "dislikes": 48, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "target = 1, startFuel = 1, stations = []", + "expected_output": "0", + "explanation": "We can reach the target without refueling." + }, + { + "example_num": 2, + "expected_input": "target = 100, startFuel = 1, stations = [[10,100]]", + "expected_output": "-1", + "explanation": "We can not reach the target (or even the first gas station)." + }, + { + "example_num": 3, + "expected_input": "target = 100, startFuel = 10, stations = [[10,60],[20,30],[30,30],[60,40]]", + "expected_output": "2", + "explanation": "We start with 10 liters of fuel.\nWe drive to position 10, expending 10 liters of fuel. We refuel from 0 liters to 60 liters of gas.\nThen, we drive from position 10 to position 60 (expending 50 liters of fuel),\nand refuel from 10 liters to 50 liters of gas. We then drive to and reach the target.\nWe made 2 refueling stops along the way, so we return 2." + } + ], + "solution": "/**\n * @param {number} target\n * @param {number} startFuel\n * @param {number[][]} stations\n * @return {number}\n */\nconst minRefuelStops = function (target, startFuel, stations) {\n const dp = Array(stations.length + 1).fill(0)\n dp[0] = startFuel\n for (let i = 0; i < stations.length; ++i) {\n for (let t = i; t >= 0 && dp[t] >= stations[i][0]; --t) {\n dp[t + 1] = Math.max(dp[t + 1], dp[t] + stations[i][1])\n }\n }\n for (let t = 0; t <= stations.length; ++t) {\n if (dp[t] >= target) return t\n }\n return -1\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720c98", + "questionid": 461, + "title": "Stone Game", + "slug": "stone-game", + "description": "Alice and Bob play a game with piles of stones. There are an even number of piles arranged in a row, and each pile has a positive integer number of stones piles[i]. The objective of the game is to end with the most stones. The total number of stones across all the piles is odd, so there are no ties. Alice and Bob take turns, with Alice starting first. Each turn, a player takes the entire pile of stones either from the beginning or from the end of the row. This continues until there are no more piles left, at which point the person with the most stones wins. Assuming Alice and Bob play optimally, return true if Alice wins the game, or false if Bob wins. ", + "category": [ + "Array", + "Math", + "Dynamic Programming", + "Game Theory" + ], + "complexity": "Medium", + "successrate": 69.1, + "totalsubmissions": 221144, + "totalaccepted": 152873, + "likes": 1943, + "dislikes": 1996, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "piles = [5,3,4,5]", + "expected_output": "true", + "explanation": "Alice starts first, and can only take the first 5 or the last 5.\nSay she takes the first 5, so that the row becomes [3, 4, 5].\nIf Bob takes 3, then the board is [4, 5], and Alice takes 5 to win with 10 points.\nIf Bob takes the last 5, then the board is [3, 4], and Alice takes 4 to win with 9 points.\nThis demonstrated that taking the first 5 was a winning move for Alice, so we return true." + }, + { + "example_num": 2, + "expected_input": "piles = [3,7,2,3]", + "expected_output": "true", + "explanation": "" + } + ], + "solution": null + }, + { + "_id": "66f925ddfdfb8e1665720c9a", + "questionid": 463, + "title": "Profitable Schemes", + "slug": "profitable-schemes", + "description": "There is a group of n members, and a list of various crimes they could commit. The ith crime generates a profit[i] and requires group[i] members to participate in it. If a member participates in one crime, that member can't participate in another crime. Let's call a profitable scheme any subset of these crimes that generates at least minProfit profit, and the total number of members participating in that subset of crimes is at most n. Return the number of schemes that can be chosen. Since the answer may be very large, return it modulo 109 + 7. ", + "category": [ + "Array", + "Dynamic Programming" + ], + "complexity": "Hard", + "successrate": 40.7, + "totalsubmissions": 36113, + "totalaccepted": 14689, + "likes": 443, + "dislikes": 40, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 5, minProfit = 3, group = [2,2], profit = [2,3]", + "expected_output": "2", + "explanation": "To make a profit of at least 3, the group could either commit crimes 0 and 1, or just crime 1.\nIn total, there are 2 schemes." + }, + { + "example_num": 2, + "expected_input": "n = 10, minProfit = 5, group = [2,3,5], profit = [6,7,8]", + "expected_output": "7", + "explanation": "To make a profit of at least 5, the group could commit any crimes, as long as they commit one.\nThere are 7 possible schemes: (0), (1), (2), (0,1), (0,2), (1,2), and (0,1,2)." + } + ], + "solution": "/**\n * @param {number} n\n * @param {number} minProfit\n * @param {number[]} group\n * @param {number[]} profit\n * @return {number}\n */\nconst profitableSchemes = function (n, minProfit, group, profit) {\n const m = group.length\n const dp = buildMatrix([m + 1, n + 1, minProfit + 1], 0)\n const mod = 1e9 + 7\n group.unshift(0)\n profit.unshift(0)\n dp[0][0][0] = 1\n console.log(group, profit)\n for (let i = 0; i < m; i++) {\n const g = group[i + 1],\n p = profit[i + 1]\n for (let j = 0; j <= n; j++) {\n for (let k = 0; k <= minProfit; k++) {\n dp[i + 1][j][k] += dp[i][j][k]\n dp[i + 1][j][k] = dp[i + 1][j][k] % mod\n if (j + g <= n) {\n const pp = Math.min(minProfit, k + p)\n dp[i + 1][j + g][pp] += dp[i][j][k]\n dp[i + 1][j + g][pp] = dp[i + 1][j + g][pp] % mod\n }\n }\n }\n }\n let res = 0\n for (let j = 0; j <= n; j++) {\n res = (res + dp[m][j][minProfit]) % mod\n }\n\n return res\n}\n\nfunction buildMatrix(dimensions, defaultVal) {\n if (dimensions.length === 1) return Array(dimensions[0]).fill(defaultVal)\n const res = []\n const [len, ...rest] = dimensions\n\n for (let i = 0; i < len; i++) {\n res.push(buildMatrix(rest, defaultVal))\n }\n\n return res\n}\n\n// another\n\n\n/**\n * @param {number} G\n * @param {number} P\n * @param {number[]} group\n * @param {number[]} profit\n * @return {number}\n */\nconst profitableSchemes = function(G, P, group, profit) {\n const dp = Array.from({ length: P + 1 }, () => new Array(G + 1).fill(0))\n dp[0][0] = 1\n let res = 0,\n mod = 10 ** 9 + 7\n for (let k = 0; k < group.length; k++) {\n let g = group[k],\n p = profit[k]\n for (let i = P; i >= 0; i--)\n for (let j = G - g; j >= 0; j--)\n dp[Math.min(i + p, P)][j + g] =\n (dp[Math.min(i + p, P)][j + g] + dp[i][j]) % mod\n }\n for (let x of dp[P]) res = (res + x) % mod\n return res\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720c9b", + "questionid": 464, + "title": "Random Pick with Weight", + "slug": "random-pick-with-weight", + "description": "You are given a 0-indexed array of positive integers w where w[i] describes the weight of the ith index. You need to implement the function pickIndex(), which randomly picks an index in the range [0, w.length - 1] (inclusive) and returns it. The probability of picking an index i is w[i] / sum(w). ", + "category": [ + "Math", + "Binary Search", + "Prefix Sum", + "Randomized" + ], + "complexity": "Medium", + "successrate": 46.1, + "totalsubmissions": 625439, + "totalaccepted": 288036, + "likes": 679, + "dislikes": 241, + "hints": "", + "deleted": false, + "examples": [], + "solution": "/**\n * @param {number[]} w\n */\nconst Solution = function(w) {\n this.a = []\n let sum = 0\n for (let i = 0, len = w.length; i < len; i++) {\n sum += w[i]\n this.a[i] = sum\n }\n}\n\n/**\n * @return {number}\n */\nSolution.prototype.pickIndex = function() {\n const len = this.a.length\n const sum = this.a[len - 1]\n const rand = ((Math.random() * sum) >> 0) + 1\n let l = 0,\n h = len - 1\n while (l < h) {\n const mid = (l + h) >> 1\n if (this.a[mid] === rand) return mid\n else if (this.a[mid] < rand) l = mid + 1\n else h = mid\n }\n return l\n}\n\n/**\n * Your Solution object will be instantiated and called as such:\n * var obj = new Solution(w)\n * var param_1 = obj.pickIndex()\n */\n\n// another\n\n/**\n * @param {number[]} w\n */\nconst Solution = function(w) {\n this.a = []\n let sum = 0\n for(let i = 0, len = w.length; i < len; i++) {\n sum += w[i]\n this.a[i] = sum\n }\n};\n\n/**\n * @return {number}\n */\nSolution.prototype.pickIndex = function() {\n const len = this.a.length\n const sum = this.a[len - 1]\n const rand = ((Math.random() * sum) >> 0) + 1\n let l = 0, h = len - 1\n while(l <= h) {\n const mid = (l + h) >> 1\n if(this.a[mid] === rand) return mid\n else if(this.a[mid] < rand) l = mid + 1\n else h = mid - 1\n }\n return l\n};\n\n/** \n * Your Solution object will be instantiated and called as such:\n * var obj = new Solution(w)\n * var param_1 = obj.pickIndex()\n */\n\n// another\n\n/**\n * @param {number[]} w\n */\nconst Solution = function(w) {\n this.a = []\n let sum = 0\n for(let i = 0, len = w.length; i < len; i++) {\n sum += w[i]\n this.a[i] = sum\n }\n};\n\n/**\n * @return {number}\n */\nSolution.prototype.pickIndex = function() {\n const len = this.a.length\n const sum = this.a[len - 1]\n const rand = ((Math.random() * sum) >> 0) + 1\n let l = 0, h = len - 1\n while(l < h) {\n const mid = (l + h) >> 1\n if(this.a[mid] < rand) l = mid + 1\n else h = mid\n }\n return l\n};\n\n/** \n * Your Solution object will be instantiated and called as such:\n * var obj = new Solution(w)\n * var param_1 = obj.pickIndex()\n */\n" + }, + { + "_id": "66f925ddfdfb8e1665720ca6", + "questionid": 475, + "title": "All Possible Full Binary Trees", + "slug": "all-possible-full-binary-trees", + "description": "Given an integer n, return a list of all possible full binary trees with n nodes. Each node of each tree in the answer must have Node.val == 0. Each element of the answer is the root node of one possible tree. You may return the final list of trees in any order. A full binary tree is a binary tree where each node has exactly 0 or 2 children. ", + "category": [ + "Dynamic Programming", + "Tree", + "Recursion", + "Memoization", + "Binary Tree" + ], + "complexity": "Medium", + "successrate": 79.4, + "totalsubmissions": 104069, + "totalaccepted": 82629, + "likes": 2544, + "dislikes": 187, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 7", + "expected_output": "[[0,0,0,null,null,0,0,null,null,0,0],[0,0,0,null,null,0,0,0,0],[0,0,0,0,0,0,0],[0,0,0,0,0,null,null,null,null,0,0],[0,0,0,0,0,null,null,0,0]]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "n = 3", + "expected_output": "[[0,0,0]]", + "explanation": "" + } + ], + "solution": "/**\n * Definition for a binary tree node.\n * function TreeNode(val) {\n * this.val = val;\n * this.left = this.right = null;\n * }\n */\n/**\n * @param {number} N\n * @return {TreeNode[]}\n */\nconst allPossibleFBT = function(N) {\n if (N <= 0) return []\n const dp = Array.from({ length: N + 1 }, () => [])\n dp[1].push(new TreeNode(0))\n\n for (let numNode = 1; numNode <= N; numNode += 2) {\n for (let leftNode = 1; leftNode < numNode; leftNode += 2) {\n for (let left of dp[leftNode]) {\n for (let right of dp[numNode - 1 - leftNode]) {\n let root = new TreeNode(0)\n root.left = left\n root.right = right\n dp[numNode].push(root)\n }\n }\n }\n }\n return dp[N]\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720cab", + "questionid": 480, + "title": "Numbers At Most N Given Digit Set", + "slug": "numbers-at-most-n-given-digit-set", + "description": "Given an array of digits which is sorted in non-decreasing order. You can write numbers using each digits[i] as many times as we want. For example, if digits = ['1','3','5'], we may write numbers such as '13', '551', and '1351315'. Return the number of positive integers that can be generated that are less than or equal to a given integer n. ", + "category": [ + "Array", + "Math", + "Binary Search", + "Dynamic Programming" + ], + "complexity": "Hard", + "successrate": 40.9, + "totalsubmissions": 86168, + "totalaccepted": 35238, + "likes": 1041, + "dislikes": 88, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "digits = ["1","3","5","7"], n = 100", + "expected_output": "20\nExplanation: \nThe 20 numbers that can be written are:\n1, 3, 5, 7, 11, 13, 15, 17, 31, 33, 35, 37, 51, 53, 55, 57, 71, 73, 75, 77.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "digits = ["1","4","9"], n = 1000000000", + "expected_output": "29523\nExplanation: \nWe can write 3 one digit numbers, 9 two digit numbers, 27 three digit numbers,\n81 four digit numbers, 243 five digit numbers, 729 six digit numbers,\n2187 seven digit numbers, 6561 eight digit numbers, and 19683 nine digit numbers.\nIn total, this is 29523 integers that can be written using the digits array.", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "digits = ["7"], n = 8", + "expected_output": "1", + "explanation": "" + } + ], + "solution": "/**\n * @param {string[]} digits\n * @param {number} n\n * @return {number}\n */\nconst atMostNGivenDigitSet = function(digits, n) {\n let res = 0\n const str = `${n}`, len = str.length\n const { pow } = Math, base = digits.length\n for(let i = 1; i < len; i++) {\n res += pow(base, i)\n }\n \n dfs(0)\n \n return res\n \n function dfs(pos) {\n if(pos === len) {\n res++\n return\n }\n for(const ch of digits) {\n if(str[pos] > ch) {\n res += pow(base, len - 1 - pos)\n } else if(str[pos] === ch) {\n dfs(pos + 1)\n } else break\n }\n }\n};\n\n// another\n\n\n/**\n * @param {string[]} digits\n * @param {number} n\n * @return {number}\n */\nconst atMostNGivenDigitSet = function(digits, n) {\n const str = '' + n, { pow } = Math\n const len = str.length, dsize = digits.length\n let res = 0\n \n for(let i = 1; i < len; i++) {\n res += pow(dsize, i)\n }\n \n for(let i = 0; i < len; i++) {\n let sameNum = false\n for(const d of digits) {\n if(+d < +str[i]) {\n res += pow(dsize, len - i - 1)\n } else if(+d === +str[i]) sameNum = true\n }\n if(sameNum === false) return res\n }\n \n return res + 1\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720cad", + "questionid": 482, + "title": "Super Palindromes", + "slug": "super-palindromes", + "description": "Let's say a positive integer is a super-palindrome if it is a palindrome, and it is also the square of a palindrome. Given two positive integers left and right represented as strings, return the number of super-palindromes integers in the inclusive range [left, right]. ", + "category": [ + "Math", + "Enumeration" + ], + "complexity": "Hard", + "successrate": 39.4, + "totalsubmissions": 54331, + "totalaccepted": 21385, + "likes": 301, + "dislikes": 377, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "left = "4", right = "1000"", + "expected_output": "4\nExplanation: 4, 9, 121, and 484 are superpalindromes.\nNote that 676 is not a superpalindrome: 26 * 26 = 676, but 26 is not a palindrome.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "left = "1", right = "2"", + "expected_output": "1", + "explanation": "" + } + ], + "solution": "/**\n * @param {string} L\n * @param {string} R\n * @return {number}\n */\nconst superpalindromesInRange = function (L, R) {\n // My idea was to take the root of L and R and then generate all palindromes between those numbers,\n // and then put those palindromes to power 2 and check if those are palindrome as well.\n\n // The generation of palindromes is done like this:\n // Lets say i want all palindromes of length 4, then i take all numbers of length 2.\n // I reverse the length 2 numbers and concatenate them with themselves.\n // So \"19\" becomes \"19\" + \"91\". For odd length I do the same,\n //\tbut put a for loop around them that puts nrs 0 - 9 inside them.\n // So \"19\" + \"0\" + \"91\", then \"19\" + \"1\" + \"91\", etc.\n\n // Next I loop through the generated palindromes and just check whether they are\n // inside sqrt(L) and sqrt(R). (sqrt(L) < palin < sqrt(R))\n // For every palin within sqrt(L) and sqrt(R), i put the palin to power 2\n // (with BigInt!) and then check if that is a palindrome. If so, then count++;\n\n const sqL = Math.sqrt(L)\n const sqR = Math.sqrt(R)\n const sqR_Length = parseInt(sqR).toString(10).length\n // counting the valid super-palindromes\n let palins = 0\n // L is a superpalindrome\n if (\n isPalindrome(L) &&\n sqL === parseInt(sqL) &&\n isPalindrome(sqL.toString(10))\n )\n palins++\n // R is a superpalindrome\n if (\n isPalindrome(R) &&\n sqR === parseInt(sqR) &&\n isPalindrome(sqR.toString(10))\n )\n palins++\n\n let end\n if (sqR === parseInt(sqR)) {\n // or else the loop will possibly add R as well\n end = parseInt(sqR) - 1\n } else {\n end = parseInt(Math.floor(sqR))\n }\n\n let begin\n if (sqL === parseInt(sqL)) {\n // or else the loop will possibly add R as well\n begin = parseInt(sqL) + 1\n } else {\n begin = parseInt(Math.ceil(sqL))\n }\n\n // account for superpalins with for single digit 'sub-palins'\n if (begin <= 1 && end >= 1) palins++ // 1\n if (begin <= 2 && end >= 2) palins++ // 4\n if (begin <= 3 && end >= 3) palins++ // 9\n const length = sqR_Length\n const even = length % 2 === 0\n const half = Math.floor(length / 2)\n const pow10Half = Math.pow(10, half) // 10 or 100 or 1000, etc\n const pow10HalfMinOne = Math.pow(10, half - 1)\n let pal = '' // init\n let palinStr = '' // init\n let palin = -1 // init\n for (let i = 1, leni = pow10Half; i < leni; i++) {\n pal = i.toString(10)\n pal.padStart(half - pal.length, '0')\n palReverse = reverseStr(pal)\n // generate even length palindrome\n palinStr = pal + palReverse\n palin = parseInt(palinStr)\n if (palin >= begin && palin <= end) {\n if (isPalindromeInt(BigInt(palin) * BigInt(palin))) {\n palins++\n }\n }\n // If I generate all palindromes up until some even length,\n // lets say 4, then last step is to do length 2 + length 2 (19 + 91),\n // and not the 19 + 0 + 91 step that generates odd length palindromes.\n if (even && i >= pow10HalfMinOne) {\n continue\n }\n for (let j = 0, lenj = 10; j < lenj; j++) {\n // generate odd length palindrome\n palinStr = pal + j + palReverse\n palin = parseInt(palinStr)\n if (palin >= begin && palin <= end) {\n if (isPalindromeInt(BigInt(palin) * BigInt(palin))) {\n palins++\n }\n }\n }\n }\n return palins\n}\n\nconst reverseStr = function (str) {\n return str.split('').reverse().join('')\n}\n\nconst isPalindromeInt = function (nr) {\n nr = nr.toString(10)\n return nr === nr.split('').reverse().join('')\n}\nconst isPalindrome = function (nr) {\n return nr === nr.split('').reverse().join('')\n}\n\n// another\n\n/**\n * @param {string} left\n * @param {string} right\n * @return {number}\n */\n const superpalindromesInRange = function(left, right) {\n const palindromes = []\n let res = 0\n for(let i = 1; i < 10; i++) {\n palindromes.push(`${i}`)\n }\n for(let i = 1; i < 1e4; i++) {\n let l = `${i}`, r = l.split('').reverse().join('')\n palindromes.push(`${l}${r}`)\n for(let j = 0; j < 10; j++) {\n palindromes.push(`${l}${j}${r}`)\n }\n }\n\n for(let p of palindromes) {\n const square = BigInt(p) * BigInt(p)\n if(!isPalindrome(`${square}`)) continue\n if(BigInt(left) <= square && square <= BigInt(right)) res++ \n }\n\n return res\n\n function isPalindrome(str) {\n let i = 0;\n let j = str.length - 1;\n while (i < j) {\n if (str.charAt(i) !== str.charAt(j)) {\n return false;\n }\n i++;\n j--;\n }\n return true;\n }\n};\n\n// another\n\n/**\n * @param {string} left\n * @param {string} right\n * @return {number}\n */\nconst superpalindromesInRange = function (left, right) {\n let ans = 9 >= left && 9 <= right ? 1 : 0\n\n const isPal = (str) => {\n for (let i = 0, j = str.length - 1; i < j; i++, j--)\n if (str.charAt(i) !== str.charAt(j)) return false\n return true\n }\n\n for (let dig = 1; dig < 10; dig++) {\n let isOdd = dig % 2 && dig !== 1,\n innerLen = (dig >> 1) - 1,\n innerLim = Math.max(1, 2 ** innerLen),\n midPos = dig >> 1,\n midLim = isOdd ? 3 : 1\n for (let edge = 1; edge < 3; edge++) {\n let pal = new Uint8Array(dig)\n ;(pal[0] = edge), (pal[dig - 1] = edge)\n if (edge === 2) (innerLim = 1), (midLim = Math.min(midLim, 2))\n for (let inner = 0; inner < innerLim; inner++) {\n if (inner > 0) {\n let innerStr = inner.toString(2).padStart(innerLen, '0')\n for (let i = 0; i < innerLen; i++)\n (pal[1 + i] = innerStr[i]), (pal[dig - 2 - i] = innerStr[i])\n }\n for (let mid = 0; mid < midLim; mid++) {\n if (isOdd) pal[midPos] = mid\n let palin = ~~pal.join(''),\n square = BigInt(palin) * BigInt(palin)\n if (square > right) return ans\n if (square >= left && isPal(square.toString())) ans++\n }\n }\n }\n }\n return ans\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720caf", + "questionid": 484, + "title": "Smallest Range I", + "slug": "smallest-range-i", + "description": "You are given an integer array nums and an integer k. In one operation, you can choose any index i where 0 <= i < nums.length and change nums[i] to nums[i] + x where x is an integer from the range [-k, k]. You can apply this operation at most once for each index i. The score of nums is the difference between the maximum and minimum elements in nums. Return the minimum score of nums after applying the mentioned operation at most once for each index in it. ", + "category": [ + "Array", + "Math" + ], + "complexity": "Easy", + "successrate": 67.2, + "totalsubmissions": 88513, + "totalaccepted": 59504, + "likes": 422, + "dislikes": 1601, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1], k = 0", + "expected_output": "0", + "explanation": "The score is max(nums) - min(nums) = 1 - 1 = 0." + }, + { + "example_num": 2, + "expected_input": "nums = [0,10], k = 2", + "expected_output": "6", + "explanation": "Change nums to be [2, 8]. The score is max(nums) - min(nums) = 8 - 2 = 6." + }, + { + "example_num": 3, + "expected_input": "nums = [1,3,6], k = 3", + "expected_output": "0", + "explanation": "Change nums to be [4, 4, 4]. The score is max(nums) - min(nums) = 4 - 4 = 0." + } + ], + "solution": "/**\n * @param {number[]} nums\n * @param {number} k\n * @return {number}\n */\nconst smallestRangeI = function(nums, k) {\n let min = Infinity, max = -Infinity\n for(let e of nums) {\n min = Math.min(min, e)\n max = Math.max(max, e)\n }\n return max - k >= min + k ? max - k - (min + k) : 0\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720cb3", + "questionid": 488, + "title": "Maximum Sum Circular Subarray", + "slug": "maximum-sum-circular-subarray", + "description": "Given a circular integer array nums of length n, return the maximum possible sum of a non-empty subarray of nums. A circular array means the end of the array connects to the beginning of the array. Formally, the next element of nums[i] is nums[(i + 1) % n] and the previous element of nums[i] is nums[(i - 1 + n) % n]. A subarray may only include each element of the fixed buffer nums at most once. Formally, for a subarray nums[i], nums[i + 1], ..., nums[j], there does not exist i <= k1, k2 <= j with k1 % n == k2 % n. ", + "category": [ + "Array", + "Divide and Conquer", + "Dynamic Programming", + "Queue", + "Monotonic Queue" + ], + "complexity": "Medium", + "successrate": 37.1, + "totalsubmissions": 306473, + "totalaccepted": 113682, + "likes": 3034, + "dislikes": 139, + "hints": "For those of you who are familiar with the Kadane's algorithm, think in terms of that. For the newbies, Kadane's algorithm is used to finding the maximum sum subarray from a given array. This problem is a twist on that idea and it is advisable to read up on that algorithm first before starting this problem. Unless you already have a great algorithm brewing up in your mind in which case, go right ahead! What is an alternate way of representing a circular array so that it appears to be a straight array?\r\nEssentially, there are two cases of this problem that we need to take care of. Let's look at the figure below to understand those two cases: The first case can be handled by the good old Kadane's algorithm. However, is there a smarter way of going about handling the second case as well?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,-2,3,-2]", + "expected_output": "3", + "explanation": "Subarray [3] has maximum sum 3." + }, + { + "example_num": 2, + "expected_input": "nums = [5,-3,5]", + "expected_output": "10", + "explanation": "Subarray [5,5] has maximum sum 5 + 5 = 10." + }, + { + "example_num": 3, + "expected_input": "nums = [-3,-2,-3]", + "expected_output": "-2", + "explanation": "Subarray [-2] has maximum sum -2." + } + ], + "solution": "/**\n * @param {number[]} A\n * @return {number}\n */\nconst maxSubarraySumCircular = function(A) {\n let minSum = Infinity, sum = 0, maxSum = -Infinity, curMax = 0, curMin = 0\n for(let a of A) {\n sum += a\n curMax = Math.max(curMax + a, a);\n maxSum = Math.max(maxSum, curMax);\n curMin = Math.min(curMin + a, a);\n minSum = Math.min(minSum, curMin);\n }\n return maxSum > 0 ? Math.max(maxSum, sum - minSum) : maxSum;\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720cb8", + "questionid": 493, + "title": "Flip String to Monotone Increasing", + "slug": "flip-string-to-monotone-increasing", + "description": "A binary string is monotone increasing if it consists of some number of 0's (possibly none), followed by some number of 1's (also possibly none). You are given a binary string s. You can flip s[i] changing it from 0 to 1 or from 1 to 0. Return the minimum number of flips to make s monotone increasing. ", + "category": [ + "String", + "Dynamic Programming" + ], + "complexity": "Medium", + "successrate": 58.7, + "totalsubmissions": 150284, + "totalaccepted": 88180, + "likes": 1907, + "dislikes": 82, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "00110"", + "expected_output": "1", + "explanation": "We flip the last digit to get 00111." + }, + { + "example_num": 2, + "expected_input": "s = "010110"", + "expected_output": "2", + "explanation": "We flip to get 011111, or alternatively 000111." + }, + { + "example_num": 3, + "expected_input": "s = "00011000"", + "expected_output": "2", + "explanation": "We flip to get 00000000." + } + ], + "solution": "/**\n * @param {string} s\n * @return {number}\n */\nconst minFlipsMonoIncr = function(s) {\n const n = s.length\n let res = 0, oneCnt = 0\n for(const e of s) {\n if(e === '1') oneCnt++\n else {\n const stayZero = oneCnt\n const flipToOne = res + 1\n res = Math.min(stayZero, flipToOne)\n }\n }\n \n return res\n};\n\n// another\n\n\n/**\n * @param {string} s\n * @return {number}\n */\nconst minFlipsMonoIncr = function(s) {\n const n = s.length\n const arr = Array(n).fill(0)\n let oneCnt = 0\n for(let i = 0; i < n; i++) {\n if(s[i] === '1') oneCnt++\n arr[i] = oneCnt\n }\n const zeroCnt = n - oneCnt\n let res = Infinity\n \n for(let i = 0; i < n; i++) {\n const cnt = arr[i]\n const tmp = cnt + (zeroCnt - (i + 1 - cnt))\n res = Math.min(res, tmp)\n }\n res = Math.min(res, oneCnt, zeroCnt)\n return res\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720cba", + "questionid": 495, + "title": "Unique Email Addresses", + "slug": "unique-email-addresses", + "description": "Every valid email consists of a local name and a domain name, separated by the '@' sign. Besides lowercase letters, the email may contain one or more '.' or '+'. If you add periods '.' between some characters in the local name part of an email address, mail sent there will be forwarded to the same address without dots in the local name. Note that this rule does not apply to domain names. If you add a plus '+' in the local name, everything after the first plus sign will be ignored. This allows certain emails to be filtered. Note that this rule does not apply to domain names. It is possible to use both of these rules at the same time. Given an array of strings emails where we send one email to each emails[i], return the number of different addresses that actually receive mails. ", + "category": [ + "Array", + "Hash Table", + "String" + ], + "complexity": "Easy", + "successrate": 67.4, + "totalsubmissions": 518797, + "totalaccepted": 349584, + "likes": 1749, + "dislikes": 244, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "emails = ["test.email+alex@leetcode.com","test.e.mail+bob.cathy@leetcode.com","testemail+david@lee.tcode.com"]", + "expected_output": "2", + "explanation": ""testemail@leetcode.com" and "testemail@lee.tcode.com" actually receive mails." + }, + { + "example_num": 2, + "expected_input": "emails = ["a@leetcode.com","b@leetcode.com","c@leetcode.com"]", + "expected_output": "3", + "explanation": "" + } + ], + "solution": "/**\n * @param {string[]} emails\n * @return {number}\n */\nconst numUniqueEmails = function(emails) {\n const res = new Set()\n emails.forEach(el => helper(el, res))\n return res.size\n};\n\nfunction helper(str, s) {\n const arr = str.split('@')\n const p = arr[0]\n const d = arr[1]\n let res = ''\n for(let i = 0, len = p.length; i < len; i++) {\n if(p[i] === '.') {\n continue\n } else if(p[i] === '+') {\n break\n } else {\n res += p[i]\n }\n }\n s.add(`${res}@${d}`)\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720cbb", + "questionid": 496, + "title": "Binary Subarrays With Sum", + "slug": "binary-subarrays-with-sum", + "description": "Given a binary array nums and an integer goal, return the number of non-empty subarrays with a sum goal. A subarray is a contiguous part of the array. ", + "category": [ + "Array", + "Hash Table", + "Sliding Window", + "Prefix Sum" + ], + "complexity": "Medium", + "successrate": 48.7, + "totalsubmissions": 92313, + "totalaccepted": 44969, + "likes": 1303, + "dislikes": 44, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,0,1,0,1], goal = 2", + "expected_output": "4", + "explanation": "The 4 subarrays are bolded and underlined below:\n[1,0,1,0,1]\n[1,0,1,0,1]\n[1,0,1,0,1]\n[1,0,1,0,1]" + }, + { + "example_num": 2, + "expected_input": "nums = [0,0,0,0,0], goal = 0", + "expected_output": "15", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} A\n * @param {number} S\n * @return {number}\n */\nconst numSubarraysWithSum = function(A, S) {\n if(A === null || A.length == 0) return 0;\n const freq = new Array(A.length + 1).fill(0)\n let ans = 0;\n let sum = 0;\n for(let i = 0; i < A.length; i++) {\n sum += A[i];\n let index = sum - S;\n if(index >= 0) ans += freq[index];\n if(sum == S) ans++;\n freq[sum]++;\n }\n return ans;\n};\n\n// another\n\n/**\n * @param {number[]} nums\n * @param {number} goal\n * @return {number}\n */\nconst numSubarraysWithSum = function(nums, goal) {\n const hash = {}\n const n = nums.length\n let res = 0, sum = 0\n for(let i = 0; i < n; i++) {\n const cur = nums[i]\n sum += cur\n const pre = sum - goal\n if(hash[sum] == null) hash[sum] = 0\n if(hash[pre] != null) res += hash[pre]\n if(sum === goal) res++\n hash[sum]++ \n }\n \n return res\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720cbc", + "questionid": 497, + "title": "Minimum Falling Path Sum", + "slug": "minimum-falling-path-sum", + "description": "Given an n x n array of integers matrix, return the minimum sum of any falling path through matrix. A falling path starts at any element in the first row and chooses the element in the next row that is either directly below or diagonally left/right. Specifically, the next element from position (row, col) will be (row + 1, col - 1), (row + 1, col), or (row + 1, col + 1). ", + "category": [ + "Array", + "Dynamic Programming", + "Matrix" + ], + "complexity": "Medium", + "successrate": 67.3, + "totalsubmissions": 180018, + "totalaccepted": 121207, + "likes": 2215, + "dislikes": 92, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "matrix = [[2,1,3],[6,5,4],[7,8,9]]", + "expected_output": "13", + "explanation": "There are two falling paths with a minimum sum as shown." + }, + { + "example_num": 2, + "expected_input": "matrix = [[-19,57],[-40,-5]]", + "expected_output": "-59", + "explanation": "The falling path with a minimum sum is shown." + } + ], + "solution": "/**\n * @param {number[][]} A\n * @return {number}\n */\nconst minFallingPathSum = function(A) {\n for (let i = 1, rows = A.length; i < rows; i++) {\n for (let j = 0, cols = A[0].length; j < cols; j++) {\n A[i][j] += Math.min(\n getValueOrMax(A, i - 1, j - 1),\n getValueOrMax(A, i - 1, j),\n getValueOrMax(A, i - 1, j + 1)\n );\n }\n }\n return Math.min(...A[A.length - 1]);\n};\n\nfunction getValueOrMax(A, i, j) {\n return A[i][j] !== undefined ? A[i][j] : Number.MAX_VALUE;\n}\n\n// another\n\n/**\n * @param {number[][]} A\n * @return {number}\n */\nconst minFallingPathSum = function(A) {\n for (let i = A.length - 2; i >= 0; i -= 1) {\n for (let j = 0; j < A[i].length; j += 1) {\n A[i][j] += Math.min(\n getValueOrMax(A, i + 1, j - 1),\n getValueOrMax(A, i + 1, j),\n getValueOrMax(A, i + 1, j + 1)\n )\n }\n }\n return Math.min(...A[0])\n }\n \n function getValueOrMax(A, i, j) {\n return A[i][j] !== undefined ? A[i][j] : Number.MAX_VALUE\n }\n \n" + }, + { + "_id": "66f925ddfdfb8e1665720cc5", + "questionid": 506, + "title": "Most Stones Removed with Same Row or Column", + "slug": "most-stones-removed-with-same-row-or-column", + "description": "On a 2D plane, we place n stones at some integer coordinate points. Each coordinate point may have at most one stone. A stone can be removed if it shares either the same row or the same column as another stone that has not been removed. Given an array stones of length n where stones[i] = [xi, yi] represents the location of the ith stone, return the largest possible number of stones that can be removed. ", + "category": [ + "Depth-First Search", + "Union Find", + "Graph" + ], + "complexity": "Medium", + "successrate": 56.3, + "totalsubmissions": 177705, + "totalaccepted": 100011, + "likes": 2367, + "dislikes": 504, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "stones = [[0,0],[0,1],[1,0],[1,2],[2,1],[2,2]]", + "expected_output": "5", + "explanation": "One way to remove 5 stones is as follows:\n1. Remove stone [2,2] because it shares the same row as [2,1].\n2. Remove stone [2,1] because it shares the same column as [0,1].\n3. Remove stone [1,2] because it shares the same row as [1,0].\n4. Remove stone [1,0] because it shares the same column as [0,0].\n5. Remove stone [0,1] because it shares the same row as [0,0].\nStone [0,0] cannot be removed since it does not share a row/column with another stone still on the plane." + }, + { + "example_num": 2, + "expected_input": "stones = [[0,0],[0,2],[1,1],[2,0],[2,2]]", + "expected_output": "3", + "explanation": "One way to make 3 moves is as follows:\n1. Remove stone [2,2] because it shares the same row as [2,0].\n2. Remove stone [2,0] because it shares the same column as [0,0].\n3. Remove stone [0,2] because it shares the same row as [0,0].\nStones [0,0] and [1,1] cannot be removed since they do not share a row/column with another stone still on the plane." + }, + { + "example_num": 3, + "expected_input": "stones = [[0,0]]", + "expected_output": "0", + "explanation": "[0,0] is the only stone on the plane, so you cannot remove it." + } + ], + "solution": "/**\n * @param {number[][]} stones\n * @return {number}\n */\nconst removeStones = function(stones) {\n const f = new Map()\n let islands = 0\n for (let i = 0; i < stones.length; i++) {\n union(stones[i][0], ~stones[i][1]) // row, col\n }\n return stones.length - islands\n\n function find(x) {\n if (!f.has(x)) {\n islands++\n f.set(x, x)\n }\n if (x != f.get(x)) {\n f.set(x, find(f.get(x)))\n }\n return f.get(x)\n }\n\n function union(x, y) {\n x = find(x)\n y = find(y)\n if (x !== y) {\n f.set(x, y)\n islands--\n }\n }\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720cca", + "questionid": 511, + "title": "Check Completeness of a Binary Tree", + "slug": "check-completeness-of-a-binary-tree", + "description": "Given the root of a binary tree, determine if it is a complete binary tree. In a complete binary tree, every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h. ", + "category": [ + "Tree", + "Breadth-First Search", + "Binary Tree" + ], + "complexity": "Medium", + "successrate": 53.6, + "totalsubmissions": 213148, + "totalaccepted": 114298, + "likes": 1891, + "dislikes": 28, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [1,2,3,4,5,6]", + "expected_output": "true", + "explanation": "Every level before the last is full (ie. levels with node-values {1} and {2, 3}), and all nodes in the last level ({4, 5, 6}) are as far left as possible." + }, + { + "example_num": 2, + "expected_input": "root = [1,2,3,4,5,null,7]", + "expected_output": "false", + "explanation": "The node with value 7 isn't as far left as possible." + } + ], + "solution": "/**\n * Definition for a binary tree node.\n * function TreeNode(val, left, right) {\n * this.val = (val===undefined ? 0 : val)\n * this.left = (left===undefined ? null : left)\n * this.right = (right===undefined ? null : right)\n * }\n */\n/**\n * @param {TreeNode} root\n * @return {boolean}\n */\nconst isCompleteTree = function(root) {\n let cur = [root]\n let depth = 1\n while(cur.length) {\n const nxt = []\n // console.log(cur)\n for(let i = 0; i < cur.length; i++) {\n const e = cur[i]\n if(e == null) nxt.push(null, null)\n else if(e) nxt.push(e.left, e.right)\n }\n \n if(!valid(cur) || (cur[cur.length - 1] == null && valid(nxt))) {\n return false\n }\n \n if(nxt.some(e => e != null)) {\n cur = nxt\n } else {\n cur = []\n }\n depth++\n }\n \n return true\n \n function valid(arr) {\n let firstNull = arr.length, lastNonNull = arr.length\n for(let i = 0; i < arr.length; i++) {\n const e = arr[i]\n if(firstNull === arr.length && e == null) firstNull = i\n if(e != null) lastNonNull = i\n }\n // console.log(firstNull, lastNonNull)\n return firstNull >= lastNonNull\n }\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720c90", + "questionid": 453, + "title": "Binary Gap", + "slug": "binary-gap", + "description": "Given a positive integer n, find and return the longest distance between any two adjacent 1's in the binary representation of n. If there are no two adjacent 1's, return 0. Two 1's are adjacent if there are only 0's separating them (possibly no 0's). The distance between two 1's is the absolute difference between their bit positions. For example, the two 1's in \"1001\" have a distance of 3. ", + "category": [ + "Math", + "Bit Manipulation" + ], + "complexity": "Easy", + "successrate": 61.8, + "totalsubmissions": 93801, + "totalaccepted": 57939, + "likes": 422, + "dislikes": 590, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 22", + "expected_output": "2", + "explanation": "22 in binary is "10110".\nThe first adjacent pair of 1's is "10110" with a distance of 2.\nThe second adjacent pair of 1's is "10110" with a distance of 1.\nThe answer is the largest of these two distances, which is 2.\nNote that "10110" is not a valid pair since there is a 1 separating the two 1's underlined." + }, + { + "example_num": 2, + "expected_input": "n = 8", + "expected_output": "0", + "explanation": "8 in binary is "1000".\nThere are not any adjacent pairs of 1's in the binary representation of 8, so we return 0." + }, + { + "example_num": 3, + "expected_input": "n = 5", + "expected_output": "2", + "explanation": "5 in binary is "101"." + } + ], + "solution": "/**\n * @param {number} N\n * @return {number}\n */\nconst binaryGap = function(N) {\n const bin = (N >>> 0).toString(2);\n const idxArr = [];\n for (let i = 0; i < bin.length; i++) {\n const num = bin.charAt(i);\n if (num === \"1\") {\n idxArr.push(i);\n }\n }\n let maxConLen = 0;\n for (let idx = 0; idx < idxArr.length - 1; idx++) {\n if (idxArr[idx + 1] - idxArr[idx] > maxConLen) {\n maxConLen = idxArr[idx + 1] - idxArr[idx];\n }\n }\n\n return maxConLen;\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720c94", + "questionid": 457, + "title": "Implement Rand10() Using Rand7()", + "slug": "implement-rand10-using-rand7", + "description": "Given the API rand7() that generates a uniform random integer in the range [1, 7], write a function rand10() that generates a uniform random integer in the range [1, 10]. You can only call the API rand7(), and you shouldn't call any other API. Please do not use a language's built-in random API. Each test case will have one internal argument n, the number of times that your implemented function rand10() will be called while testing. Note that this is not an argument passed to rand10(). ", + "category": [ + "Math", + "Rejection Sampling", + "Randomized", + "Probability and Statistics" + ], + "complexity": "Medium", + "successrate": 46.8, + "totalsubmissions": 132350, + "totalaccepted": 61882, + "likes": 864, + "dislikes": 283, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 1", + "expected_output": "[2]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "n = 2", + "expected_output": "[2,8]", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "n = 3", + "expected_output": "[3,8,10]", + "explanation": "" + } + ], + "solution": "/**\n * The rand7() API is already defined for you.\n * var rand7 = function() {}\n * @return {number} a random integer in the range 1 to 7\n */\nconst rand10 = function() {\n let result = 40\n while (result >= 40) {\n result = 7 * (rand7() - 1) + (rand7() - 1)\n }\n return (result % 10) + 1\n}\n\n// another\n\n/**\n * The rand7() API is already defined for you.\n * var rand7 = function() {}\n * @return {number} a random integer in the range 1 to 7\n */\nconst rand10 = function() {\n let tmp = 40\n while(tmp >= 40) tmp = 7 * (rand7() - 1) + (rand7() - 1)\n \n return tmp % 10 + 1\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720c96", + "questionid": 459, + "title": "Koko Eating Bananas", + "slug": "koko-eating-bananas", + "description": "Koko loves to eat bananas. There are n piles of bananas, the ith pile has piles[i] bananas. The guards have gone and will come back in h hours. Koko can decide her bananas-per-hour eating speed of k. Each hour, she chooses some pile of bananas and eats k bananas from that pile. If the pile has less than k bananas, she eats all of them instead and will not eat any more bananas during this hour. Koko likes to eat slowly but still wants to finish eating all the bananas before the guards return. Return the minimum integer k such that she can eat all the bananas within h hours. ", + "category": [ + "Array", + "Binary Search" + ], + "complexity": "Medium", + "successrate": 54.7, + "totalsubmissions": 306246, + "totalaccepted": 167396, + "likes": 3982, + "dislikes": 177, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "piles = [3,6,7,11], h = 8", + "expected_output": "4", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "piles = [30,11,23,4,20], h = 5", + "expected_output": "30", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "piles = [30,11,23,4,20], h = 6", + "expected_output": "23", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} piles\n * @param {number} h\n * @return {number}\n */\nconst minEatingSpeed = function(piles, h) {\n let ma = -1\n for(const e of piles) {\n if(e > ma) ma = e\n }\n \n let l = 1, r = ma\n \n while(l < r) {\n const mid = Math.floor((l + r) / 2)\n if(valid(mid)) {\n r = mid\n } else {\n l = mid + 1\n }\n }\n \n return l\n \n function valid(val) {\n let res = 0\n for(const e of piles) {\n res += Math.ceil(e / val)\n }\n \n return res <= h\n }\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720c9c", + "questionid": 465, + "title": "Boats to Save People", + "slug": "boats-to-save-people", + "description": "You are given an array people where people[i] is the weight of the ith person, and an infinite number of boats where each boat can carry a maximum weight of limit. Each boat carries at most two people at the same time, provided the sum of the weight of those people is at most limit. Return the minimum number of boats to carry every given person. ", + "category": [ + "Array", + "Two Pointers", + "Greedy", + "Sorting" + ], + "complexity": "Medium", + "successrate": 52.4, + "totalsubmissions": 270544, + "totalaccepted": 141888, + "likes": 2974, + "dislikes": 79, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "people = [1,2], limit = 3", + "expected_output": "1", + "explanation": "1 boat (1, 2)" + }, + { + "example_num": 2, + "expected_input": "people = [3,2,2,1], limit = 3", + "expected_output": "3", + "explanation": "3 boats (1, 2), (2) and (3)" + }, + { + "example_num": 3, + "expected_input": "people = [3,5,3,4], limit = 5", + "expected_output": "4", + "explanation": "4 boats (3), (3), (4), (5)" + } + ], + "solution": "/**\n * @param {number[]} people\n * @param {number} limit\n * @return {number}\n */\nconst numRescueBoats = function(people, limit) {\n if(people.length === 0) return 0\n const arr = people.sort((a, b) => a - b)\n let count = 0\n let i = 0\n let j = arr.length - 1\n while(i <= j) {\n count++\n if(arr[i] + arr[j] <= limit) {\n i++\n }\n j--\n }\n\n return count\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720c9e", + "questionid": 467, + "title": "Projection Area of 3D Shapes", + "slug": "projection-area-of-3d-shapes", + "description": "You are given an n x n grid where we place some 1 x 1 x 1 cubes that are axis-aligned with the x, y, and z axes. Each value v = grid[i][j] represents a tower of v cubes placed on top of the cell (i, j). We view the projection of these cubes onto the xy, yz, and zx planes. A projection is like a shadow, that maps our 3-dimensional figure to a 2-dimensional plane. We are viewing the \"shadow\" when looking at the cubes from the top, the front, and the side. Return the total area of all three projections. ", + "category": [ + "Array", + "Math", + "Geometry", + "Matrix" + ], + "complexity": "Easy", + "successrate": 70, + "totalsubmissions": 57337, + "totalaccepted": 40133, + "likes": 390, + "dislikes": 1140, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "grid = [[1,2],[3,4]]", + "expected_output": "17", + "explanation": "Here are the three projections ("shadows") of the shape made with each axis-aligned plane." + }, + { + "example_num": 2, + "expected_input": "grid = [[2]]", + "expected_output": "5", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "grid = [[1,0],[0,2]]", + "expected_output": "8", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[][]} grid\n * @return {number}\n */\nconst projectionArea = function(grid) {\n let xy = 0, xz = 0, yz = 0\n const m = grid.length, n = grid[0].length\n for (let i = 0; i < m; i++) {\n for(let j = 0; j < n; j++) {\n if(grid[i][j]) xy++\n }\n }\n \n for (let i = 0; i < m; i++) {\n let tmp = 0\n for(let j = 0; j < n; j++) {\n tmp = Math.max(tmp, grid[i][j])\n }\n xz += tmp\n }\n for (let j = 0; j < n; j++) {\n let tmp = 0\n for(let i = 0; i < m; i++) {\n tmp = Math.max(tmp, grid[i][j]) \n }\n yz += tmp\n }\n \n return xy + yz + xz\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720ca4", + "questionid": 473, + "title": "Construct Binary Tree from Preorder and Postorder Traversal", + "slug": "construct-binary-tree-from-preorder-and-postorder-traversal", + "description": "Given two integer arrays, preorder and postorder where preorder is the preorder traversal of a binary tree of distinct values and postorder is the postorder traversal of the same tree, reconstruct and return the binary tree. If there exist multiple answers, you can return any of them. ", + "category": [ + "Array", + "Hash Table", + "Divide and Conquer", + "Tree", + "Binary Tree" + ], + "complexity": "Medium", + "successrate": 69.9, + "totalsubmissions": 99810, + "totalaccepted": 69719, + "likes": 1833, + "dislikes": 85, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "preorder = [1,2,4,5,3,6,7], postorder = [4,5,2,6,7,3,1]", + "expected_output": "[1,2,3,4,5,6,7]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "preorder = [1], postorder = [1]", + "expected_output": "[1]", + "explanation": "" + } + ], + "solution": "/**\n\nReturn any binary tree that matches the given preorder and postorder traversals.\nValues in the traversals pre and post are distinct positive integers.\n\nExample 1:\n\nInput: pre = [1,2,4,5,3,6,7], post = [4,5,2,6,7,3,1]\nOutput: [1,2,3,4,5,6,7]\n \nNote:\n\n1 <= pre.length == post.length <= 30\npre[] and post[] are both permutations of 1, 2, ..., pre.length.\nIt is guaranteed an answer exists.\nIf there exists multiple answers, you can return any of them.\n\n*/\n\n/**\n * Definition for a binary tree node.\n * function TreeNode(val) {\n * this.val = val;\n * this.left = this.right = null;\n * }\n */\n/**\n * @param {number[]} pre\n * @param {number[]} post\n * @return {TreeNode}\n */\nconst constructFromPrePost = function(pre, post) {\n let i = 0,\n j = 0\n return (function dfs() {\n let val = pre[i++]\n let node = new TreeNode(val)\n if (val !== post[j]) node.left = dfs()\n if (val !== post[j]) node.right = dfs()\n j++\n return node\n })()\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720ca5", + "questionid": 474, + "title": "Sum of Subsequence Widths", + "slug": "sum-of-subsequence-widths", + "description": "The width of a sequence is the difference between the maximum and minimum elements in the sequence. Given an array of integers nums, return the sum of the widths of all the non-empty subsequences of nums. Since the answer may be very large, return it modulo 109 + 7. A subsequence is a sequence that can be derived from an array by deleting some or no elements without changing the order of the remaining elements. For example, [3,6,2,7] is a subsequence of the array [0,3,1,6,2,2,7]. ", + "category": [ + "Array", + "Math", + "Sorting" + ], + "complexity": "Hard", + "successrate": 35.4, + "totalsubmissions": 42660, + "totalaccepted": 15081, + "likes": 489, + "dislikes": 139, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [2,1,3]", + "expected_output": "6\nExplanation: The subsequences are [1], [2], [3], [2,1], [2,3], [1,3], [2,1,3].\nThe corresponding widths are 0, 0, 0, 1, 1, 2, 2.\nThe sum of these widths is 6.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "nums = [2]", + "expected_output": "0", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} A\n * @return {number}\n */\nconst sumSubseqWidths = function(A) {\n A.sort((a, b) => a - b)\n let c = 1, res = 0, mod = 10 ** 9 + 7\n for (let i = 0, n = A.length; i < n; i++, c = c * 2 % mod) {\n res = (res + A[i] * c - A[n - i - 1] * c) % mod;\n }\n return (res + mod) % mod;\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720ca9", + "questionid": 478, + "title": "Bitwise ORs of Subarrays", + "slug": "bitwise-ors-of-subarrays", + "description": "We have an array arr of non-negative integers. For every (contiguous) subarray sub = [arr[i], arr[i + 1], ..., arr[j]] (with i <= j), we take the bitwise OR of all the elements in sub, obtaining a result arr[i] | arr[i + 1] | ... | arr[j]. Return the number of possible results. Results that occur more than once are only counted once in the final answer ", + "category": [ + "Array", + "Dynamic Programming", + "Bit Manipulation" + ], + "complexity": "Medium", + "successrate": 36.3, + "totalsubmissions": 71422, + "totalaccepted": 25906, + "likes": 946, + "dislikes": 176, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "arr = [0]", + "expected_output": "1", + "explanation": "There is only one possible result: 0." + }, + { + "example_num": 2, + "expected_input": "arr = [1,1,2]", + "expected_output": "3", + "explanation": "The possible subarrays are [1], [1], [2], [1, 1], [1, 2], [1, 1, 2].\nThese yield the results 1, 1, 2, 1, 3, 3.\nThere are 3 unique values, so the answer is 3." + }, + { + "example_num": 3, + "expected_input": "arr = [1,2,4]", + "expected_output": "6", + "explanation": "The possible results are 1, 2, 3, 4, 6, and 7." + } + ], + "solution": "/**\n * @param {number[]} A\n * @return {number}\n */\nconst subarrayBitwiseORs = function(A) {\n let cur = new Set()\n const ans = new Set()\n \n for (let i = 0; i < A.length; i++) {\n const item = A[i]\n const x = new Set()\n for (let e of cur.values()) {\n x.add(e | item)\n }\n x.add(item)\n cur = x\n for (let sub of cur.values()) {\n ans.add(sub)\n }\n }\n return ans.size\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720caa", + "questionid": 479, + "title": "Orderly Queue", + "slug": "orderly-queue", + "description": "You are given a string s and an integer k. You can choose one of the first k letters of s and append it at the end of the string.. Return the lexicographically smallest string you could have after applying the mentioned step any number of moves. ", + "category": [ + "Math", + "String", + "Sorting" + ], + "complexity": "Hard", + "successrate": 58.5, + "totalsubmissions": 43905, + "totalaccepted": 25691, + "likes": 556, + "dislikes": 354, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "cba", k = 1", + "expected_output": ""acb"", + "explanation": "In the first move, we move the 1st character 'c' to the end, obtaining the string "bac".\nIn the second move, we move the 1st character 'b' to the end, obtaining the final result "acb"." + }, + { + "example_num": 2, + "expected_input": "s = "baaca", k = 3", + "expected_output": ""aaabc"", + "explanation": "In the first move, we move the 1st character 'b' to the end, obtaining the string "aacab".\nIn the second move, we move the 3rd character 'c' to the end, obtaining the final result "aaabc"." + } + ], + "solution": "/**\n * @param {string} S\n * @param {number} K\n * @return {string}\n */\nconst orderlyQueue = function (S, K) {\n if (K === 0) return S\n else if (K > 1) return S.split('').sort().join('')\n let result = 0,\n L = S.length\n for (let i = 1; i < L; i++) {\n for (let j = 0; j < L; j++) {\n let d = S.charCodeAt((result + j) % L) - S.charCodeAt((i + j) % L)\n if (d !== 0) {\n if (d > 0) result = i\n break\n }\n }\n }\n return S.slice(result) + S.slice(0, result)\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720cac", + "questionid": 481, + "title": "Sort Array By Parity", + "slug": "sort-array-by-parity", + "description": "Given an integer array nums, move all the even integers at the beginning of the array followed by all the odd integers. Return any array that satisfies this condition. ", + "category": [ + "Array", + "Two Pointers", + "Sorting" + ], + "complexity": "Easy", + "successrate": 74.8, + "totalsubmissions": 580427, + "totalaccepted": 434203, + "likes": 2633, + "dislikes": 111, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [3,1,2,4]", + "expected_output": "[2,4,3,1]", + "explanation": "The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted." + }, + { + "example_num": 2, + "expected_input": "nums = [0]", + "expected_output": "[0]", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} A\n * @return {number[]}\n */\nconst sortArrayByParity = function(A) {\n for(let i = 0, len = A.length; i < len;) {\n if(A[i] % 2 !== 0) {\n A.push(A[i])\n A.splice(i, 1)\n len--\n } else {\n i++\n }\n }\n return A\n}; \n" + }, + { + "_id": "66f925ddfdfb8e1665720cb0", + "questionid": 485, + "title": "Smallest Range II", + "slug": "smallest-range-ii", + "description": "You are given an integer array nums and an integer k. For each index i where 0 <= i < nums.length, change nums[i] to be either nums[i] + k or nums[i] - k. The score of nums is the difference between the maximum and minimum elements in nums. Return the minimum score of nums after changing the values at each index. ", + "category": [ + "Array", + "Math", + "Greedy", + "Sorting" + ], + "complexity": "Medium", + "successrate": 32.7, + "totalsubmissions": 100920, + "totalaccepted": 32973, + "likes": 1067, + "dislikes": 351, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1], k = 0", + "expected_output": "0", + "explanation": "The score is max(nums) - min(nums) = 1 - 1 = 0." + }, + { + "example_num": 2, + "expected_input": "nums = [0,10], k = 2", + "expected_output": "6", + "explanation": "Change nums to be [2, 8]. The score is max(nums) - min(nums) = 8 - 2 = 6." + }, + { + "example_num": 3, + "expected_input": "nums = [1,3,6], k = 3", + "expected_output": "3", + "explanation": "Change nums to be [4, 6, 3]. The score is max(nums) - min(nums) = 6 - 3 = 3." + } + ], + "solution": "/**\n * @param {number[]} nums\n * @param {number} k\n * @return {number}\n */\nconst smallestRangeII = function (nums, k) {\n let n = nums.length\n nums.sort((a, b) => a - b)\n // all elements plus k or minus k\n let res = nums[n - 1] - nums[0]\n\n // left side elements plus k, right side elements minus k\n let left = nums[0] + k, right = nums[n - 1] - k\n for(let i = 0; i < n - 1; i++) {\n const tmax = Math.max(right, nums[i] + k)\n const tmin = Math.min(left, nums[i + 1] - k)\n res = Math.min(res, tmax - tmin)\n }\n\n return res\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720cb7", + "questionid": 492, + "title": "Long Pressed Name", + "slug": "long-pressed-name", + "description": "Your friend is typing his name into a keyboard. Sometimes, when typing a character c, the key might get long pressed, and the character will be typed 1 or more times. You examine the typed characters of the keyboard. Return True if it is possible that it was your friends name, with some characters (possibly none) being long pressed. ", + "category": [ + "Two Pointers", + "String" + ], + "complexity": "Easy", + "successrate": 34.7, + "totalsubmissions": 264403, + "totalaccepted": 91843, + "likes": 1579, + "dislikes": 240, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "name = "alex", typed = "aaleex"", + "expected_output": "true\nExplanation: 'a' and 'e' in 'alex' were long pressed.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "name = "saeed", typed = "ssaaedd"", + "expected_output": "false\nExplanation: 'e' must have been pressed twice, but it was not in the typed output.", + "explanation": "" + } + ], + "solution": "/**\n * @param {string} name\n * @param {string} typed\n * @return {boolean}\n */\nconst isLongPressedName = function(name, typed) {\n let i = 0, m = name.length, n = typed.length\n for(let j = 0; j < n; j++) {\n if(i < m && name[i] === typed[j]) i++\n else if(j === 0 || typed[j] !== typed[j - 1]) return false\n }\n return i === m\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720cc1", + "questionid": 502, + "title": "Distinct Subsequences II", + "slug": "distinct-subsequences-ii", + "description": "Given a string s, return the number of distinct non-empty subsequences of s. Since the answer may be very large, return it modulo 109 + 7. ", + "category": [ + "String", + "Dynamic Programming" + ], + "complexity": "Hard", + "successrate": 44.2, + "totalsubmissions": 60215, + "totalaccepted": 26643, + "likes": 1076, + "dislikes": 27, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "abc"", + "expected_output": "7", + "explanation": "The 7 distinct subsequences are "a", "b", "c", "ab", "ac", "bc", and "abc"." + }, + { + "example_num": 2, + "expected_input": "s = "aba"", + "expected_output": "6", + "explanation": "The 6 distinct subsequences are "a", "b", "ab", "aa", "ba", and "aba"." + }, + { + "example_num": 3, + "expected_input": "s = "aaa"", + "expected_output": "3", + "explanation": "The 3 distinct subsequences are "a", "aa" and "aaa"." + } + ], + "solution": "/**\n * @param {string} s\n * @return {number}\n */\nconst distinctSubseqII = function(s) {\n const n = s.length,\n dp = Array(26).fill(0),\n a = 'a'.charCodeAt(0),\n mod = 1e9 + 7\n let res = 0\n for(let ch of s) {\n const idx = ch.charCodeAt(0) - a\n let tmp = 0\n for(let i = 0; i < 26; i++) tmp = (tmp + dp[i]) % mod\n tmp = (tmp + 1) % mod\n dp[idx] = tmp\n }\n return dp.reduce((ac, e) => (ac + e) % mod, 0)\n};\n\n// another\n\n/**\n * @param {string} S\n * @return {number}\n */\nconst distinctSubseqII = function(S) {\n // let end = new Array(26).fill(0), res = 0, added = 0, mod = 10 ** 9 + 7;\n // const aCode = ('a').charCodeAt(0)\n // for (let c of S) {\n // added = (res + 1 - end[c.charCodeAt(0) - aCode]) % mod;\n // res = (res + added) % mod;\n // end[c.charCodeAt(0) - aCode] = (end[c.charCodeAt(0) - aCode] + added) % mod;\n // }\n // return (res + mod) % mod;\n const m = new Map(),\n dp = [1],\n M = 1000000007\n for (let i = 0; i < S.length; i++) {\n const c = S.charAt(i)\n let prev = 0\n if (m.has(c)) {\n prev = dp[m.get(c)]\n }\n m.set(c, i)\n dp.push((((dp[i] * 2) % M) - prev) % M)\n if (dp[i + 1] < 0) {\n dp[i + 1] += M\n }\n }\n return dp[S.length] - 1\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720ccb", + "questionid": 512, + "title": "Regions Cut By Slashes", + "slug": "regions-cut-by-slashes", + "description": "An n x n grid is composed of 1 x 1 squares where each 1 x 1 square consists of a '/', '\\', or blank space ' '. These characters divide the square into contiguous regions. Given the grid grid represented as a string array, return the number of regions. Note that backslash characters are escaped, so a '\\' is represented as '\\\\'. ", + "category": [ + "Depth-First Search", + "Breadth-First Search", + "Union Find", + "Graph" + ], + "complexity": "Medium", + "successrate": 68.6, + "totalsubmissions": 52702, + "totalaccepted": 36142, + "likes": 2035, + "dislikes": 397, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "grid = [" /","/ "]", + "expected_output": "2", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "grid = [" /"," "]", + "expected_output": "1", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "grid = ["/\\\\","\\\\/"]", + "expected_output": "5\nExplanation: Recall that because \\ characters are escaped, "\\\\/" refers to \\/, and "/\\\\" refers to /\\.", + "explanation": "" + } + ], + "solution": "/**\n * @param {string[]} grid\n * @return {number}\n */\nconst regionsBySlashes = function(grid) {\n const len = grid.length\n let regionsNum = 0\n const dirs = [[-1, 0], [1, 0], [0, 1], [0, -1]]\n const matrix = Array.from({ length: 3 * len }, () => new Array(3 * len).fill(0))\n\n // \u628a\u6bcf\u4e2a\u683c\u5b50\u5207\u62103 * 3\u4e2a\u5c0f\u683c\u5b50\uff0c\u518d\u6807\u8bb0\u51fa\u73b0\u7ebf\u6bb5\u7684\u4f4d\u7f6e\n for (let i = 0; i < len; i++) {\n for (let j = 0; j < len; j++) {\n if (grid[i][j] === '/') matrix[i * 3][j * 3 + 2] = matrix[i * 3 + 1][j * 3 + 1] = matrix[i * 3 + 2][j * 3] = 1\n if (grid[i][j] === '\\\\') matrix[i * 3][j * 3] = matrix[i * 3 + 1][j * 3 + 1] = matrix[i * 3 + 2][j * 3 + 2] = 1\n }\n }\n\n for (let i = 0; i < matrix.length; i++) {\n for (let j = 0; j < matrix.length; j++) {\n if (matrix[i][j] === 0) {\n dfs(matrix, i, j, dirs)\n regionsNum++\n }\n }\n }\n return regionsNum\n}\nfunction dfs(m, i, j, dirs) {\n if (i >= 0 && j >= 0 && i < m.length && j < m.length && m[i][j] === 0) {\n m[i][j] = 1\n for (let dir of dirs) dfs(m, i + dir[0], j + dir[1], dirs)\n }\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720c8c", + "questionid": 449, + "title": "Shortest Subarray with Sum at Least K", + "slug": "shortest-subarray-with-sum-at-least-k", + "description": "Given an integer array nums and an integer k, return the length of the shortest non-empty subarray of nums with a sum of at least k. If there is no such subarray, return -1. A subarray is a contiguous part of an array. ", + "category": [ + "Array", + "Binary Search", + "Queue", + "Sliding Window", + "Heap (Priority Queue)", + "Prefix Sum", + "Monotonic Queue" + ], + "complexity": "Hard", + "successrate": 26.2, + "totalsubmissions": 263462, + "totalaccepted": 68923, + "likes": 2814, + "dislikes": 74, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1], k = 1", + "expected_output": "1", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "nums = [1,2], k = 4", + "expected_output": "-1", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "nums = [2,-1,2], k = 3", + "expected_output": "3", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} nums\n * @param {number} k\n * @return {number}\n */\nconst shortestSubarray = function(nums, k) {\n const q = [], n = nums.length\n let res = Infinity, sum = 0\n const prefix = []\n for(let i = 0; i < n; i++) {\n sum += nums[i]\n prefix.push(sum)\n if(sum >= k) res = Math.min(res, i + 1)\n }\n\n for(let i = 0; i < n; i++) {\n while(q.length && prefix[i] <= prefix[q[q.length - 1]]) q.pop()\n while(q.length && prefix[i] - prefix[q[0]] >= k) {\n res = Math.min(res, i - q[0])\n q.shift()\n }\n\n q.push(i)\n }\n \n return res === Infinity ? -1 : res\n};\n\n// another\n\n/**\n * @param {number[]} A\n * @param {number} K\n * @return {number}\n */\nconst shortestSubarray = function(A, K) {\n const N = A.length\n const P = new Array(N+1).fill(0)\n \n for(let i = 0; i < N; i++) {\n P[i+1] = P[i] + A[i]\n }\n\n let ans = N + 1\n const monoq = []\n for(let y = 0; y < P.length; y++) {\n while(monoq.length > 0 && P[y] <= P[monoq[monoq.length - 1]] ) {\n monoq.pop()\n }\n while(monoq.length > 0 && P[y] >= P[monoq[0]] + K ) {\n ans = Math.min(ans, y - monoq.shift())\n }\n monoq.push(y)\n }\n\n return ans < N + 1 ? ans : -1\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720c92", + "questionid": 455, + "title": "Advantage Shuffle", + "slug": "advantage-shuffle", + "description": "You are given two integer arrays nums1 and nums2 both of the same length. The advantage of nums1 with respect to nums2 is the number of indices i for which nums1[i] > nums2[i]. Return any permutation of nums1 that maximizes its advantage with respect to nums2. ", + "category": [ + "Array", + "Greedy", + "Sorting" + ], + "complexity": "Medium", + "successrate": 51.2, + "totalsubmissions": 102654, + "totalaccepted": 52584, + "likes": 1221, + "dislikes": 78, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums1 = [2,7,11,15], nums2 = [1,10,4,11]", + "expected_output": "[2,11,7,15]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "nums1 = [12,24,8,32], nums2 = [13,25,32,11]", + "expected_output": "[24,32,8,12]", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} A\n * @param {number[]} B\n * @return {number[]}\n */\nfunction advantageCount(aArr, B) {\n const A = aArr.sort((a, b) => a - b)\n const n = A.length\n const res = []\n let pq = []\n for(let i = 0; i < n; i++) {\n pq.push([B[i], i])\n }\n pq.sort((a, b) => b[0] - a[0])\n let lo = 0\n let hi = n - 1\n while(pq.length > 0) {\n let cur = pq.shift()\n let idx = cur[1]\n let val = cur[0]\n if (A[hi] > val) {\n res[idx] = A[hi--]\n } else {\n res[idx] = A[lo++]\n }\n }\n return res\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720c95", + "questionid": 458, + "title": "Leaf-Similar Trees", + "slug": "leaf-similar-trees", + "description": "Consider all the leaves of a binary tree, from\u00a0left to right order, the values of those\u00a0leaves form a leaf value sequence. For example, in the given tree above, the leaf value sequence is (6, 7, 4, 9, 8). Two binary trees are considered leaf-similar\u00a0if their leaf value sequence is the same. Return true if and only if the two given trees with head nodes root1 and root2 are leaf-similar. ", + "category": [ + "Tree", + "Depth-First Search", + "Binary Tree" + ], + "complexity": "Easy", + "successrate": 65, + "totalsubmissions": 249610, + "totalaccepted": 162142, + "likes": 1648, + "dislikes": 55, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root1 = [3,5,1,6,2,9,8,null,null,7,4], root2 = [3,5,1,6,7,4,2,null,null,null,null,null,null,9,8]", + "expected_output": "true", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "root1 = [1,2,3], root2 = [1,3,2]", + "expected_output": "false", + "explanation": "" + } + ], + "solution": null + }, + { + "_id": "66f925ddfdfb8e1665720c9f", + "questionid": 468, + "title": "Uncommon Words from Two Sentences", + "slug": "uncommon-words-from-two-sentences", + "description": "A sentence is a string of single-space separated words where each word consists only of lowercase letters. A word is uncommon if it appears exactly once in one of the sentences, and does not appear in the other sentence. Given two sentences s1 and s2, return a list of all the uncommon words. You may return the answer in any order. ", + "category": [ + "Hash Table", + "String" + ], + "complexity": "Easy", + "successrate": 65.5, + "totalsubmissions": 147023, + "totalaccepted": 96368, + "likes": 898, + "dislikes": 137, + "hints": "", + "deleted": false, + "examples": [], + "solution": "/**\n * @param {string} s1\n * @param {string} s2\n * @return {string[]}\n */\nconst uncommonFromSentences = function(s1, s2) {\n const hash = {}\n const a1 = s1.split(' '), a2 = s2.split(' ')\n for(let e of a1) {\n if(hash[e] == null) hash[e] = 0\n hash[e]++\n }\n const res = []\n for(let e of a2) {\n if(hash[e] == null) hash[e] = 0\n hash[e]++\n }\n Object.keys(hash).forEach(k => {\n if(hash[k] === 1) res.push(k)\n })\n \n return res\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720ca0", + "questionid": 469, + "title": "Spiral Matrix III", + "slug": "spiral-matrix-iii", + "description": "You start at the cell (rStart, cStart) of an rows x cols grid facing east. The northwest corner is at the first row and column in the grid, and the southeast corner is at the last row and column. You will walk in a clockwise spiral shape to visit every position in this grid. Whenever you move outside the grid's boundary, we continue our walk outside the grid (but may return to the grid boundary later.). Eventually, we reach all rows * cols spaces of the grid. Return an array of coordinates representing the positions of the grid in the order you visited them. ", + "category": [ + "Array", + "Matrix", + "Simulation" + ], + "complexity": "Medium", + "successrate": 72.4, + "totalsubmissions": 46878, + "totalaccepted": 33947, + "likes": 514, + "dislikes": 563, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "rows = 1, cols = 4, rStart = 0, cStart = 0", + "expected_output": "[[0,0],[0,1],[0,2],[0,3]]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "rows = 5, cols = 6, rStart = 1, cStart = 4", + "expected_output": "[[1,4],[1,5],[2,5],[2,4],[2,3],[1,3],[0,3],[0,4],[0,5],[3,5],[3,4],[3,3],[3,2],[2,2],[1,2],[0,2],[4,5],[4,4],[4,3],[4,2],[4,1],[3,1],[2,1],[1,1],[0,1],[4,0],[3,0],[2,0],[1,0],[0,0]]", + "explanation": "" + } + ], + "solution": null + }, + { + "_id": "66f925ddfdfb8e1665720ca1", + "questionid": 470, + "title": "Possible Bipartition", + "slug": "possible-bipartition", + "description": "We want to split a group of n people (labeled from 1 to n) into two groups of any size. Each person may dislike some other people, and they should not go into the same group. Given the integer n and the array dislikes where dislikes[i] = [ai, bi] indicates that the person labeled ai does not like the person labeled bi, return true if it is possible to split everyone into two groups in this way. ", + "category": [ + "Depth-First Search", + "Breadth-First Search", + "Union Find", + "Graph" + ], + "complexity": "Medium", + "successrate": 47.3, + "totalsubmissions": 221370, + "totalaccepted": 104627, + "likes": 2240, + "dislikes": 51, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 4, dislikes = [[1,2],[1,3],[2,4]]", + "expected_output": "true", + "explanation": "The first group has [1,4], and the second group has [2,3]." + }, + { + "example_num": 2, + "expected_input": "n = 3, dislikes = [[1,2],[1,3],[2,3]]", + "expected_output": "false", + "explanation": "We need at least 3 groups to divide them. We cannot put them in two groups." + } + ], + "solution": "/**\n * @param {number} N\n * @param {number[][]} dislikes\n * @return {boolean}\n */\nconst possibleBipartition = function (N, dislikes) {\n const graph = []\n for (let i = 0; i <= N; i++) {\n graph[i] = []\n }\n for (let el of dislikes) {\n graph[el[0]].push(el[1])\n graph[el[1]].push(el[0])\n }\n const color = new Array(N + 1).fill(0)\n for (let i = 1; i <= N; i++) {\n if (color[i] == 0) {\n color[i] = 1\n const q = []\n q.push(i)\n while (q.length > 0) {\n let cur = q.shift()\n for (let j of graph[cur]) {\n if (color[j] == 0) {\n color[j] = color[cur] == 1 ? 2 : 1\n q.push(j)\n } else {\n if (color[j] == color[cur]) return false\n }\n }\n }\n }\n }\n return true\n}\n\n// another\n\n/**\n * @param {number} N\n * @param {number[][]} dislikes\n * @return {boolean}\n */\nconst possibleBipartition = function (N, dislikes) {\n const graph = new Array(N + 1)\n for (const [a, b] of dislikes) {\n if (!graph[a]) graph[a] = []\n graph[a].push(b)\n if (!graph[b]) graph[b] = []\n graph[b].push(a)\n }\n\n const colors = new Array(N + 1)\n const dfs = (node, color = 0) => {\n colors[node] = color\n const nextColor = color ^ 1\n const children = graph[node] || []\n for (const child of children) {\n if (colors[child] !== undefined) {\n if (colors[child] !== nextColor) return false\n } else {\n if (!dfs(child, nextColor)) return false\n }\n }\n return true\n }\n for (let i = 1; i <= N; i++) {\n if (colors[i] === undefined && !dfs(i)) return false\n }\n return true\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720ca8", + "questionid": 477, + "title": "Increasing Order Search Tree", + "slug": "increasing-order-search-tree", + "description": "Given the root of a binary search tree, rearrange the tree in in-order so that the leftmost node in the tree is now the root of the tree, and every node has no left child and only one right child. ", + "category": [ + "Stack", + "Tree", + "Depth-First Search", + "Binary Search Tree", + "Binary Tree" + ], + "complexity": "Easy", + "successrate": 76.2, + "totalsubmissions": 219615, + "totalaccepted": 167325, + "likes": 2301, + "dislikes": 595, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [5,3,6,2,4,null,8,1,null,null,null,7,9]", + "expected_output": "[1,null,2,null,3,null,4,null,5,null,6,null,7,null,8,null,9]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "root = [5,1,7]", + "expected_output": "[1,null,5,null,7]", + "explanation": "" + } + ], + "solution": "/**\n * Definition for a binary tree node.\n * function TreeNode(val, left, right) {\n * this.val = (val===undefined ? 0 : val)\n * this.left = (left===undefined ? null : left)\n * this.right = (right===undefined ? null : right)\n * }\n */\n/**\n * @param {TreeNode} root\n * @return {TreeNode}\n */\nconst increasingBST = function(root) {\n return helper(root, null)\n};\n\nfunction helper(node, tail) {\n if(node == null) return tail\n const res = helper(node.left, node)\n node.left = null\n node.right = helper(node.right, tail)\n return res\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720cae", + "questionid": 483, + "title": "Sum of Subarray Minimums", + "slug": "sum-of-subarray-minimums", + "description": "Given an array of integers arr, find the sum of min(b), where b ranges over every (contiguous) subarray of arr. Since the answer may be large, return the answer modulo 109 + 7. ", + "category": [ + "Array", + "Dynamic Programming", + "Stack", + "Monotonic Stack" + ], + "complexity": "Medium", + "successrate": 33.8, + "totalsubmissions": 216848, + "totalaccepted": 73305, + "likes": 3363, + "dislikes": 225, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "arr = [3,1,2,4]", + "expected_output": "17", + "explanation": "Subarrays are [3], [1], [2], [4], [3,1], [1,2], [2,4], [3,1,2], [1,2,4], [3,1,2,4]. \nMinimums are 3, 1, 2, 4, 1, 1, 2, 1, 1, 1.\nSum is 17." + }, + { + "example_num": 2, + "expected_input": "arr = [11,81,94,43,3]", + "expected_output": "444", + "explanation": "" + } + ], + "solution": "\n/**\n * @param {number[]} arr\n * @return {number}\n */\n const sumSubarrayMins = function (arr) {\n const n = arr.length\n const mod = 1e9 + 7, stk = []\n const left = Array(n), right = Array(n)\n for(let i = 0; i< n; i++) {\n left[i] = i + 1\n right[i] = n - i\n }\n let res = 0\n for(let i = 0; i < n; i++) {\n while(stk.length && arr[stk[stk.length - 1]] > arr[i]) {\n const idx = stk.pop()\n right[idx] = i - idx\n }\n if (stk.length) left[i] = i - stk[stk.length - 1]\n stk.push(i)\n \n }\n for(let i = 0; i < n; i++) {\n res = (res + arr[i] * left[i] * right[i]) % mod\n }\n \n return res\n}\n \n// another\n\n/**\n * @param {number[]} arr\n * @return {number}\n */\nconst sumSubarrayMins = function (arr) {\n const n = arr.length,\n s1 = [],\n s2 = [],\n left = Array(n),\n right = Array(n)\n for (let i = 0; i < n; i++) {\n let cnt = 1\n while (s1.length && s1[s1.length - 1][0] > arr[i]) {\n cnt += s1.pop()[1]\n }\n left[i] = cnt\n s1.push([arr[i], cnt])\n }\n\n for (let i = n - 1; i >= 0; i--) {\n let cnt = 1\n while (s2.length && s2[s2.length - 1][0] >= arr[i]) {\n cnt += s2.pop()[1]\n }\n right[i] = cnt\n s2.push([arr[i], cnt])\n }\n let res = 0\n const mod = 1e9 + 7\n for (let i = 0; i < n; i++) {\n // left[i] number of starting positions\n // right[i] number of ending positions\n res = (res + arr[i] * left[i] * right[i]) % mod\n }\n\n return res\n}\n\n// another\n\n/**\n * @param {number[]} arr\n * @return {number}\n */\nconst sumSubarrayMins = function(arr) {\n const stk1 = [], stk2 = []\n const len = arr.length, mod = 1e9 + 7\n const left = new Array(len), right = new Array(len)\n for(let i = 0; i < len; i++) {\n left[i] = i + 1\n right[i] = len - i\n }\n for(let i = 0; i < len; i++) {\n while(stk1.length && arr[stk1[stk1.length - 1]] > arr[i]) {\n stk1.pop()\n }\n left[i] = i - (stk1.length ? stk1[stk1.length - 1] : -1)\n stk1.push(i)\n\n while(stk2.length && arr[stk2[stk2.length - 1]] > arr[i]) {\n let index = stk2.pop()\n right[index] = i - index\n }\n stk2.push(i)\n }\n\n let res = 0\n for(let i = 0; i < len; i++) {\n res = (res + arr[i] * left[i] * right[i]) % mod\n }\n return res\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720cb1", + "questionid": 486, + "title": "Sort an Array", + "slug": "sort-an-array", + "description": "Given an array of integers nums, sort the array in ascending order. ", + "category": [ + "Array", + "Divide and Conquer", + "Sorting", + "Heap (Priority Queue)", + "Merge Sort", + "Bucket Sort", + "Radix Sort", + "Counting Sort" + ], + "complexity": "Medium", + "successrate": 61.5, + "totalsubmissions": 416971, + "totalaccepted": 256327, + "likes": 2012, + "dislikes": 517, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [5,2,3,1]", + "expected_output": "[1,2,3,5]", + "explanation": "After sorting the array, the positions of some numbers are not changed (for example, 2 and 3), while the positions of other numbers are changed (for example, 1 and 5)." + }, + { + "example_num": 2, + "expected_input": "nums = [5,1,1,2,0,0]", + "expected_output": "[0,0,1,1,2,5]", + "explanation": "Note that the values of nums are not necessairly unique." + } + ], + "solution": "/**\n * @param {number[]} nums\n * @return {number[]}\n */\nfunction swap(items, l, r) {\n const temp = items[l];\n items[l] = items[r];\n items[r] = temp;\n}\nfunction partition(items, start, end) {\n let pivot = items[end], s = start\n for(let i = start; i < end; i++) {\n if(items[i] <= pivot) {\n swap(items, s, i)\n s++\n }\n }\n swap(items, s, end)\n return s\n}\n\nfunction quickSort(items, left, right) {\n if(left < right) {\n const pIdx = partition(items, left, right)\n quickSort(items, left, pIdx - 1)\n quickSort(items, pIdx + 1, right)\n }\n return items;\n}\nconst sortArray = function(nums) {\n return quickSort(nums, 0, nums.length - 1);\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720cb2", + "questionid": 487, + "title": "Word Subsets", + "slug": "word-subsets", + "description": "You are given two string arrays words1 and words2. A string b is a subset of string a if every letter in b occurs in a including multiplicity. A string a from words1 is universal if for every string b in words2, b is a subset of a. Return an array of all the universal strings in words1. You may return the answer in any order. ", + "category": [ + "Array", + "Hash Table", + "String" + ], + "complexity": "Medium", + "successrate": 52.7, + "totalsubmissions": 94448, + "totalaccepted": 49763, + "likes": 948, + "dislikes": 126, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "words1 = ["amazon","apple","facebook","google","leetcode"], words2 = ["e","o"]", + "expected_output": "["facebook","google","leetcode"]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "words1 = ["amazon","apple","facebook","google","leetcode"], words2 = ["l","e"]", + "expected_output": "["apple","google","leetcode"]", + "explanation": "" + } + ], + "solution": "/**\n * @param {string[]} A\n * @param {string[]} B\n * @return {string[]}\n */\nconst wordSubsets = function(A, B) {\n function counter(s) {\n let count = Array(26).fill(0);\n for (let i = 0; i < s.length; i++) count[s.charCodeAt(i) - 97]++;\n return count;\n }\n let aux = Array(26).fill(0);\n let result = [];\n for (let i = 0; i < B.length; i++) {\n let count = counter(B[i]);\n for (let i = 0; i < 26; i++) {\n aux[i] = Math.max(aux[i], count[i]);\n }\n }\n for (let i = 0; i < A.length; i++) {\n let count = counter(A[i]);\n let flag = true;\n for (let j = 0; j < 26; j++) {\n if (aux[j] > 0 && count[j] - aux[j] < 0) {\n flag = false;\n break;\n }\n }\n if (flag) result.push(A[i]);\n }\n return result;\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720cb4", + "questionid": 489, + "title": "Sort Array By Parity II", + "slug": "sort-array-by-parity-ii", + "description": "Given an array of integers nums, half of the integers in nums are odd, and the other half are even. Sort the array so that whenever nums[i] is odd, i is odd, and whenever nums[i] is even, i is even. Return any answer array that satisfies this condition. ", + "category": [ + "Array", + "Two Pointers", + "Sorting" + ], + "complexity": "Easy", + "successrate": 70.6, + "totalsubmissions": 257460, + "totalaccepted": 181873, + "likes": 1705, + "dislikes": 70, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [4,2,5,7]", + "expected_output": "[4,5,2,7]", + "explanation": "[4,7,2,5], [2,5,4,7], [2,7,4,5] would also have been accepted." + }, + { + "example_num": 2, + "expected_input": "nums = [2,3]", + "expected_output": "[2,3]", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} A\n * @return {number[]}\n */\nconst sortArrayByParityII = function(A) {\n const res = []\n const odd = []\n const even = []\n for(let i = 0, len = A.length; i < len; i++) {\n if(A[i] % 2 === 0) even.push(A[i])\n else odd.push(A[i])\n }\n for(let i = 0, len = odd.length; i < len; i++) {\n res.push(even[i], odd[i])\n }\n return res\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720cb9", + "questionid": 494, + "title": "Minimize Malware Spread II", + "slug": "minimize-malware-spread-ii", + "description": "You are given a network of n nodes represented as an n x n adjacency matrix graph, where the ith node is directly connected to the jth node if graph[i][j] == 1. Some nodes initial are initially infected by malware. Whenever two nodes are directly connected, and at least one of those two nodes is infected by malware, both nodes will be infected by malware. This spread of malware will continue until no more nodes can be infected in this manner. Suppose M(initial) is the final number of nodes infected with malware in the entire network after the spread of malware stops. We will remove exactly one node from initial, completely removing it and any connections from this node to any other node. Return the node that, if removed, would minimize M(initial). If multiple nodes could be removed to minimize M(initial), return such a node with the smallest index. ", + "category": [ + "Array", + "Depth-First Search", + "Breadth-First Search", + "Union Find", + "Matrix" + ], + "complexity": "Hard", + "successrate": 42.2, + "totalsubmissions": 36043, + "totalaccepted": 15199, + "likes": 417, + "dislikes": 69, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "graph = [[1,1,0],[1,1,0],[0,0,1]], initial = [0,1]", + "expected_output": "0", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "graph = [[1,1,0],[1,1,1],[0,1,1]], initial = [0,1]", + "expected_output": "1", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "graph = [[1,1,0,0],[1,1,1,0],[0,1,1,1],[0,0,1,1]], initial = [0,1]", + "expected_output": "1", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[][]} graph\n * @param {number[]} initial\n * @return {number}\n */\nvar minMalwareSpread = function (graph, initial) {\n const map = new Map() // node -> initial nodes infect this node\n for (let i of initial) {\n const visited = new Set(initial)\n const q = []\n q.push(i)\n while (q.length) {\n let cur = q.shift()\n for (let j = 0; j < graph[cur].length; j++) {\n if (graph[cur][j] == 1) {\n if (!visited.has(j)) {\n visited.add(j)\n q.push(j)\n\n if (map.get(j) == null) map.set(j, [])\n map.get(j).push(i)\n }\n }\n }\n }\n }\n\n const res = Array(graph.length).fill(0) // node -> safe nodes it infects\n for (let node of map.keys()) {\n if (map.get(node).length == 1) {\n let i = map.get(node)[0]\n res[i]++\n }\n }\n let max = 0\n let removed = -1\n for (let i = 0; i < res.length; i++) {\n if (res[i] > max) {\n max = res[i]\n removed = i\n }\n }\n initial.sort((a, b) => a - b)\n return removed == -1 ? initial[0] : removed\n}\n\n// another\n\n/**\n * @param {number[][]} graph\n * @param {number[]} initial\n * @return {number}\n */\nconst minMalwareSpread = function (graph, initial) {\n const map = new Map(), n = graph.length\n for(let init of initial) {\n const visited = new Set(initial)\n const q = [init]\n while(q.length) {\n const cur = q.pop()\n for(let i = 0; i < n; i++) {\n if(graph[cur][i] === 1 && !visited.has(i)) {\n visited.add(i)\n q.push(i)\n if(map.get(i) == null) map.set(i, [])\n map.get(i).push(init)\n }\n } \n }\n }\n \n let res = 0, max = -1\n const arr = Array(n)\n for(let [k,v] of map) {\n if(v.length === 1) {\n if(arr[v[0]] == null) arr[v[0]] = 0\n arr[v[0]]++\n }\n }\n \n for(let k = 0; k < n; k++) {\n const v = arr[k]\n if(v > max) {\n max = v\n res = +k\n }\n }\n \n let min = Infinity\n for(let e of initial) {\n if(e < min) min = e\n }\n return max === -1 ? min: res\n \n}\n\n" + }, + { + "_id": "66f925ddfdfb8e1665720cbf", + "questionid": 500, + "title": "Range Sum of BST", + "slug": "range-sum-of-bst", + "description": "Given the root node of a binary search tree and two integers low and high, return the sum of values of all nodes with a value in the inclusive range [low, high]. ", + "category": [ + "Tree", + "Depth-First Search", + "Binary Search Tree", + "Binary Tree" + ], + "complexity": "Easy", + "successrate": 85.1, + "totalsubmissions": 705825, + "totalaccepted": 600407, + "likes": 4038, + "dislikes": 332, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [10,5,15,3,7,null,18], low = 7, high = 15", + "expected_output": "32", + "explanation": "Nodes 7, 10, and 15 are in the range [7, 15]. 7 + 10 + 15 = 32." + }, + { + "example_num": 2, + "expected_input": "root = [10,5,15,3,7,13,18,1,null,6], low = 6, high = 10", + "expected_output": "23", + "explanation": "Nodes 6, 7, and 10 are in the range [6, 10]. 6 + 7 + 10 = 23." + } + ], + "solution": "/**\n * Definition for a binary tree node.\n * function TreeNode(val) {\n * this.val = val;\n * this.left = this.right = null;\n * }\n */\n/**\n * @param {TreeNode} root\n * @param {number} L\n * @param {number} R\n * @return {number}\n */\nconst rangeSumBST = function(root, L, R) {\n const payload = {sum: 0} \n traverse(root, payload, L, R)\n return payload.sum\n};\n\nfunction traverse(node, obj, L, R) {\n if(node == null) return\n if(node.val >= L && node.val <= R) obj.sum += node.val\n traverse(node.left, obj, L, R)\n traverse(node.right, obj, L, R)\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720cc3", + "questionid": 504, + "title": "Minimum Increment to Make Array Unique", + "slug": "minimum-increment-to-make-array-unique", + "description": "You are given an integer array nums. In one move, you can pick an index i where 0 <= i < nums.length and increment nums[i] by 1. Return the minimum number of moves to make every value in nums unique. ", + "category": [ + "Array", + "Greedy", + "Sorting", + "Counting" + ], + "complexity": "Medium", + "successrate": 49, + "totalsubmissions": 106854, + "totalaccepted": 52368, + "likes": 1026, + "dislikes": 43, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,2,2]", + "expected_output": "1", + "explanation": "After 1 move, the array could be [1, 2, 3]." + }, + { + "example_num": 2, + "expected_input": "nums = [3,2,1,2,1,7]", + "expected_output": "6", + "explanation": "After 6 moves, the array could be [3, 4, 1, 2, 5, 7].\nIt can be shown that it is impossible for the array to have all unique values with 5 or less moves." + } + ], + "solution": "/**\n * @param {number[]} nums\n * @return {number}\n */\nconst minIncrementForUnique = function(nums) {\n const seen = new Set()\n const queue = []\n let res = 0\n for(const e of nums) {\n if(!seen.has(e)) seen.add(e)\n else queue.push(e)\n }\n queue.sort((a, b) => b - a)\n for(let i = 0; i <= 1e5 || queue.length; i++) {\n if(!seen.has(i) && i > last(queue)) {\n res += i - queue.pop()\n }\n }\n \n return res\n \n function last(arr) {\n return arr[arr.length - 1]\n }\n};\n\n// another\n\n/**\n * @param {number[]} nums\n * @return {number}\n */\nconst minIncrementForUnique = function(nums) {\n let res = 0, nxt = 0\n nums.sort((a, b) => a - b)\n for(const e of nums) {\n res += Math.max(0, nxt - e)\n nxt = Math.max(nxt, e) + 1\n }\n \n return res\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720cc6", + "questionid": 507, + "title": "Verifying an Alien Dictionary", + "slug": "verifying-an-alien-dictionary", + "description": "In an alien language, surprisingly, they also use English lowercase letters, but possibly in a different order. The order of the alphabet is some permutation of lowercase letters. Given a sequence of words written in the alien language, and the order of the alphabet, return true if and only if the given words are sorted lexicographically in this alien language. ", + "category": [ + "Array", + "Hash Table", + "String" + ], + "complexity": "Easy", + "successrate": 52.5, + "totalsubmissions": 655595, + "totalaccepted": 344275, + "likes": 2739, + "dislikes": 916, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "words = ["hello","leetcode"], order = "hlabcdefgijkmnopqrstuvwxyz"", + "expected_output": "true\nExplanation: As 'h' comes before 'l' in this language, then the sequence is sorted.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "words = ["word","world","row"], order = "worldabcefghijkmnpqstuvxyz"", + "expected_output": "false\nExplanation: As 'd' comes after 'l' in this language, then words[0] > words[1], hence the sequence is unsorted.", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "words = ["apple","app"], order = "abcdefghijklmnopqrstuvwxyz"", + "expected_output": "false\nExplanation: The first three characters "app" match, and the second string is shorter (in size.) According to lexicographical rules "apple" > "app", because 'l' > '∅', where '∅' is defined as the blank character which is less than any other character (More info).", + "explanation": "" + } + ], + "solution": "/**\n * @param {string[]} words\n * @param {string} order\n * @return {boolean}\n */\nconst isAlienSorted = function(words, order) {\n const mapping = Array(26).fill(0), a = 'a'.charCodeAt(0)\n for(let i = 0, len = order.length; i < len; i++) {\n mapping[order.charCodeAt(i) - a] = i\n }\n\n for(let i = 1, n = words.length; i < n; i++) {\n if(bigger(words[i - 1], words[i])) return false\n }\n \n return true\n \n function bigger(s1, s2) {\n const n = s1.length, m = s2.length;\n for (let i = 0; i < n && i < m; ++i) {\n if (s1.charAt(i) != s2.charAt(i)) return mapping[s1.charCodeAt(i) - a] > mapping[s2.charCodeAt(i) - a]; \n }\n\n return n > m;\n }\n\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720cc7", + "questionid": 508, + "title": "Array of Doubled Pairs", + "slug": "array-of-doubled-pairs", + "description": "Given an integer array of even length arr, return true if it is possible to reorder arr such that arr[2 * i + 1] = 2 * arr[2 * i] for every 0 <= i < len(arr) / 2, or false otherwise. ", + "category": [ + "Array", + "Hash Table", + "Greedy", + "Sorting" + ], + "complexity": "Medium", + "successrate": 38.7, + "totalsubmissions": 181540, + "totalaccepted": 70184, + "likes": 1075, + "dislikes": 127, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "arr = [3,1,3,6]", + "expected_output": "false", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "arr = [2,1,2,6]", + "expected_output": "false", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "arr = [4,-2,2,-4]", + "expected_output": "true", + "explanation": "We can take two groups, [-2,-4] and [2,4] to form [-2,-4,2,4] or [2,4,-2,-4]." + } + ], + "solution": "/**\n * @param {number[]} A\n * @return {boolean}\n */\nconst canReorderDoubled = function(A) {\n const cnt = {}\n for(let val of A) {\n val = Math.abs(val)\n cnt[val] ? cnt[val]++ : cnt[val] = 1\n }\n for(let val in cnt) {\n let sibling = val * 2\n if(val == '0') {\n if(cnt[val] % 2) return false\n cnt[val] = 0 \n } else if(cnt[val] && cnt[sibling]) {\n cnt[sibling] -= cnt[val]\n cnt[val] = 0\n }\n }\n for(let val in cnt)\n if(cnt[val]) return false\n return true\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720cc9", + "questionid": 510, + "title": "Tallest Billboard", + "slug": "tallest-billboard", + "description": "You are installing a billboard and want it to have the largest height. The billboard will have two steel supports, one on each side. Each steel support must be an equal height. You are given a collection of rods that can be welded together. For example, if you have rods of lengths 1, 2, and 3, you can weld them together to make a support of length 6. Return the largest possible height of your billboard installation. If you cannot support the billboard, return 0. ", + "category": [ + "Array", + "Dynamic Programming" + ], + "complexity": "Hard", + "successrate": 39.9, + "totalsubmissions": 32430, + "totalaccepted": 12945, + "likes": 651, + "dislikes": 23, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "rods = [1,2,3,6]", + "expected_output": "6", + "explanation": "We have two disjoint subsets {1,2,3} and {6}, which have the same sum = 6." + }, + { + "example_num": 2, + "expected_input": "rods = [1,2,3,4,5,6]", + "expected_output": "10", + "explanation": "We have two disjoint subsets {2,3,5} and {4,6}, which have the same sum = 10." + }, + { + "example_num": 3, + "expected_input": "rods = [1,2]", + "expected_output": "0", + "explanation": "The billboard cannot be supported, so we return 0." + } + ], + "solution": "/**\n * @param {number[]} rods\n * @return {number}\n */\nconst tallestBillboard = function(rods) {\n const sum = rods.reduce((ac, e) => ac + e, 0)\n const dp = Array(sum + 1).fill(-1), { abs, max, min } = Math\n dp[0] = 0\n for(const e of rods) {\n const bak = dp.slice()\n for(let delta = 0; delta <= sum; delta++) {\n if(bak[delta] < 0) continue\n if(delta + e <= sum) dp[delta + e] = max(dp[delta + e], bak[delta])\n dp[abs(delta - e)] = max(dp[abs(delta - e)], bak[delta] + min(e, delta))\n }\n }\n \n \n return dp[0]\n};\n\n\n// another\n\n\n/**\n * @param {number[]} rods\n * @return {number}\n */\nconst tallestBillboard = function(rods) {\n const dp = {0 : 0}\n for(let el of rods) {\n for(let [diff, y] of Object.entries(dp)) {\n diff = +diff\n dp[diff + el] = Math.max(dp[diff + el] || 0, y)\n if(diff >= el) dp[diff - el] = Math.max(dp[diff - el] || 0, y + el)\n else dp[el - diff] = Math.max(dp[el - diff] || 0, y + diff)\n }\n }\n return dp['0']\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720c8e", + "questionid": 451, + "title": "Smallest Subtree with all the Deepest Nodes", + "slug": "smallest-subtree-with-all-the-deepest-nodes", + "description": "Given the root of a binary tree, the depth of each node is the shortest distance to the root. Return the smallest subtree such that it contains all the deepest nodes in the original tree. A node is called the deepest if it has the largest depth possible among any node in the entire tree. The subtree of a node is a tree consisting of that node, plus the set of all descendants of that node. ", + "category": [ + "Hash Table", + "Tree", + "Depth-First Search", + "Breadth-First Search", + "Binary Tree" + ], + "complexity": "Medium", + "successrate": 67.8, + "totalsubmissions": 150133, + "totalaccepted": 101824, + "likes": 1917, + "dislikes": 324, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [3,5,1,6,2,0,8,null,null,7,4]", + "expected_output": "[2,7,4]", + "explanation": "We return the node with value 2, colored in yellow in the diagram.\nThe nodes coloured in blue are the deepest nodes of the tree.\nNotice that nodes 5, 3 and 2 contain the deepest nodes in the tree but node 2 is the smallest subtree among them, so we return it." + }, + { + "example_num": 2, + "expected_input": "root = [1]", + "expected_output": "[1]", + "explanation": "The root is the deepest node in the tree." + }, + { + "example_num": 3, + "expected_input": "root = [0,1,3,null,2]", + "expected_output": "[2]", + "explanation": "The deepest node in the tree is 2, the valid subtrees are the subtrees of nodes 2, 1 and 0 but the subtree of node 2 is the smallest." + } + ], + "solution": "/**\n * Definition for a binary tree node.\n * function TreeNode(val) {\n * this.val = val;\n * this.left = this.right = null;\n * }\n */\n/**\n * @param {TreeNode} root\n * @return {TreeNode}\n */\nconst subtreeWithAllDeepest = function(root) {\n return dfs(root).node;\n};\n\nfunction dfs(node) {\n if (node == null) return new result(null, 0);\n const l = dfs(node.left);\n const r = dfs(node.right);\n if (l.dist > r.dist) return new result(l.node, l.dist + 1);\n if (l.dist < r.dist) return new result(r.node, r.dist + 1);\n return new result(node, l.dist + 1);\n}\n\nfunction result(node, dist) {\n this.node = node;\n this.dist = dist;\n}\n\n// another\n\n/**\n * Definition for a binary tree node.\n * function TreeNode(val, left, right) {\n * this.val = (val===undefined ? 0 : val)\n * this.left = (left===undefined ? null : left)\n * this.right = (right===undefined ? null : right)\n * }\n */\n/**\n * @param {TreeNode} root\n * @return {TreeNode}\n */\nconst subtreeWithAllDeepest = function(root) {\n let res = null, maxDepth = 0\n dfs(root, 0)\n \n return res\n \n function dfs(node, depth) {\n if(node == null) return depth - 1\n \n const left = dfs(node.left, depth + 1)\n const right = dfs(node.right, depth + 1)\n maxDepth = Math.max(maxDepth, left, right)\n \n if(left === maxDepth && right === maxDepth) {\n res = node\n }\n return Math.max(left, right)\n }\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720c97", + "questionid": 460, + "title": "Middle of the Linked List", + "slug": "middle-of-the-linked-list", + "description": "Given the head of a singly linked list, return the middle node of the linked list. If there are two middle nodes, return the second middle node. ", + "category": [ + "Linked List", + "Two Pointers" + ], + "complexity": "Easy", + "successrate": 72.6, + "totalsubmissions": 861365, + "totalaccepted": 625120, + "likes": 5116, + "dislikes": 129, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "head = [1,2,3,4,5]", + "expected_output": "[3,4,5]", + "explanation": "The middle node of the list is node 3." + }, + { + "example_num": 2, + "expected_input": "head = [1,2,3,4,5,6]", + "expected_output": "[4,5,6]", + "explanation": "Since the list has two middle nodes with values 3 and 4, we return the second one." + } + ], + "solution": "/**\n * Definition for singly-linked list.\n * function ListNode(val) {\n * this.val = val;\n * this.next = null;\n * }\n */\n/**\n * @param {ListNode} head\n * @return {ListNode}\n */\nconst middleNode = function (head) {\n if (head == null) return null\n let count = 1\n let iter = head\n while (iter.next) {\n iter = iter.next\n count++\n }\n count = (count / 2) >> 0\n while (count) {\n head = head.next\n count--\n }\n return head\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720c99", + "questionid": 462, + "title": "Nth Magical Number", + "slug": "nth-magical-number", + "description": "A positive integer is magical if it is divisible by either a or b. Given the three integers n, a, and b, return the nth magical number. Since the answer may be very large, return it modulo 109 + 7. ", + "category": [ + "Math", + "Binary Search" + ], + "complexity": "Hard", + "successrate": 35.8, + "totalsubmissions": 81480, + "totalaccepted": 29143, + "likes": 962, + "dislikes": 134, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 1, a = 2, b = 3", + "expected_output": "2", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "n = 4, a = 2, b = 3", + "expected_output": "6", + "explanation": "" + } + ], + "solution": "/**\n * @param {number} N\n * @param {number} A\n * @param {number} B\n * @return {number}\n */\nconst gcd = (x, y) => {\n while (y > 0) [x, y] = [y, x % y]\n return x\n}\nconst lcm = (x, y) => (x * y) / gcd(x, y)\nconst nthMagicalNumber = function(N, A, B) {\n let l = lcm(A, B)\n const seq = {}\n for (let i = 1; i < Math.floor(l / A) + 1; i++) seq[i * A] = 1\n for (let i = 1; i < Math.floor(l / B) + 1; i++) seq[i * B] = 1\n const arr = Object.keys(seq)\n .sort((a, b) => a - b)\n .map(el => +el)\n let idx = N % arr.length === 0 ? arr.length - 1 : (N % arr.length) - 1\n let res = Math.floor((N - 1) / arr.length) * arr[arr.length - 1] + arr[idx]\n return res % (1e9 + 7)\n}\n\n// another\n\nconst nthMagicalNumber = function(N, A, B) {\n const gcd = (x, y) => {\n if (x == 0) return y\n return gcd(y % x, x)\n }\n const MOD = 1e9 + 7\n const L = (A / gcd(A, B)) * B\n let lo = 0\n let hi = 1e15\n while (lo < hi) {\n let mi = lo + Math.trunc((hi - lo) / 2)\n if (Math.trunc(mi / A) + Math.trunc(mi / B) - Math.trunc(mi / L) < N) lo = mi + 1\n else hi = mi\n }\n return lo % MOD\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720c9d", + "questionid": 466, + "title": "Reachable Nodes In Subdivided Graph", + "slug": "reachable-nodes-in-subdivided-graph", + "description": "You are given an undirected graph (the \"original graph\") with n nodes labeled from 0 to n - 1. You decide to subdivide each edge in the graph into a chain of nodes, with the number of new nodes varying between each edge. The graph is given as a 2D array of edges where edges[i] = [ui, vi, cnti] indicates that there is an edge between nodes ui and vi in the original graph, and cnti is the total number of new nodes that you will subdivide the edge into. Note that cnti == 0 means you will not subdivide the edge. To subdivide the edge [ui, vi], replace it with (cnti + 1) new edges and cnti new nodes. The new nodes are x1, x2, ..., xcnti, and the new edges are [ui, x1], [x1, x2], [x2, x3], ..., [xcnti-1, xcnti], [xcnti, vi]. In this new graph, you want to know how many nodes are reachable from the node 0, where a node is reachable if the distance is maxMoves or less. Given the original graph and maxMoves, return the number of nodes that are reachable from node 0 in the new graph. ", + "category": [ + "Graph", + "Heap (Priority Queue)", + "Shortest Path" + ], + "complexity": "Hard", + "successrate": 49.9, + "totalsubmissions": 40284, + "totalaccepted": 20114, + "likes": 523, + "dislikes": 199, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "edges = [[0,1,10],[0,2,1],[1,2,2]], maxMoves = 6, n = 3", + "expected_output": "13", + "explanation": "The edge subdivisions are shown in the image above.\nThe nodes that are reachable are highlighted in yellow." + }, + { + "example_num": 2, + "expected_input": "edges = [[0,1,4],[1,2,6],[0,2,8],[1,3,1]], maxMoves = 10, n = 4", + "expected_output": "23", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "edges = [[1,2,4],[1,4,5],[1,3,1],[2,3,4],[3,4,5]], maxMoves = 17, n = 5", + "expected_output": "1", + "explanation": "Node 0 is disconnected from the rest of the graph, so only node 0 is reachable." + } + ], + "solution": "/**\n * @param {number[][]} edges\n * @param {number} maxMoves\n * @param {number} n\n * @return {number}\n */\nconst reachableNodes = function(edges, maxMoves, n) {\n let res = 0,\n heap = new Heap(),\n state = new Array(n).fill(0),\n graph = Array.from(new Array(n), () => []),\n distance = new Array(n).fill(Number.MAX_SAFE_INTEGER);\n for (let [u, v, d] of edges) {\n graph[u].push([v, d]);\n graph[v].push([u, d]);\n }\n distance[0] = 0;\n heap.insert([0, distance[0]]);\n while (heap.length != 0) {\n let t = heap.remove();\n if (state[t[0]] === 1) continue;\n if (distance[t[0]] <= maxMoves) res++;\n state[t[0]] = 1;\n for (let i of graph[t[0]]) {\n if (distance[i[0]] > distance[t[0]] + i[1] + 1) {\n distance[i[0]] = distance[t[0]] + i[1] + 1;\n heap.insert([i[0], distance[i[0]]]);\n }\n }\n }\n for (let [u, v, d] of edges) {\n let a = maxMoves - distance[u] >= 0 ? maxMoves - distance[u] : 0,\n b = maxMoves - distance[v] >= 0 ? maxMoves - distance[v] : 0;\n res += Math.min(d, a + b);\n }\n return res;\n};\n\nclass Heap {\n constructor() {\n this.heap = [];\n }\n\n get length() {\n return this.heap.length;\n }\n\n compare(i, j) {\n if (!this.heap[j]) return false;\n return this.heap[i][1] > this.heap[j][1];\n }\n\n swap(i, j) {\n const temp = this.heap[i];\n this.heap[i] = this.heap[j];\n this.heap[j] = temp;\n }\n\n insert(num) {\n this.heap.push(num);\n let idx = this.length - 1;\n let parent = (idx - 1) >> 1;\n while (idx !== 0 && this.compare(parent, idx)) {\n this.swap(parent, idx);\n idx = parent;\n parent = (idx - 1) >> 1;\n }\n }\n\n remove() {\n if (this.length === 1) return this.heap.pop();\n let res = this.heap[0],\n idx = 0,\n left = 1 | (idx << 1),\n right = (1 + idx) << 1;\n this.heap[0] = this.heap.pop();\n while (this.compare(idx, left) || this.compare(idx, right)) {\n if (this.compare(left, right)) {\n this.swap(idx, right);\n idx = right;\n } else {\n this.swap(idx, left);\n idx = left;\n }\n left = 1 | (idx << 1);\n right = (1 + idx) << 1;\n }\n return res;\n }\n}\n\n// another\n\n/**\n * @param {number[][]} edges\n * @param {number} M\n * @param {number} N\n * @return {number}\n */\nconst reachableNodes = function (edges, M, N) {\n const graph = Array.from({ length: N }, () => Array(N).fill(-1))\n for (let edge of edges) {\n graph[edge[0]][edge[1]] = edge[2]\n graph[edge[1]][edge[0]] = edge[2]\n }\n let result = 0\n const pq = new PriorityQueue((a, b) => a[1] > b[1])\n const visited = new Array(N).fill(false)\n pq.push([0, M])\n while (!pq.isEmpty()) {\n const cur = pq.pop()\n const start = cur[0]\n const move = cur[1]\n if (visited[start]) {\n continue\n }\n visited[start] = true\n result++\n for (let i = 0; i < N; i++) {\n if (graph[start][i] > -1) {\n if (move > graph[start][i] && !visited[i]) {\n pq.push([i, move - graph[start][i] - 1])\n }\n graph[i][start] -= Math.min(move, graph[start][i])\n result += Math.min(move, graph[start][i])\n }\n }\n }\n return result\n}\n\nclass PriorityQueue {\n constructor(comparator = (a, b) => a > b) {\n this.heap = []\n this.top = 0\n this.comparator = comparator\n }\n size() {\n return this.heap.length\n }\n isEmpty() {\n return this.size() === 0\n }\n peek() {\n return this.heap[this.top]\n }\n push(...values) {\n values.forEach((value) => {\n this.heap.push(value)\n this.siftUp()\n })\n return this.size()\n }\n pop() {\n const poppedValue = this.peek()\n const bottom = this.size() - 1\n if (bottom > this.top) {\n this.swap(this.top, bottom)\n }\n this.heap.pop()\n this.siftDown()\n return poppedValue\n }\n replace(value) {\n const replacedValue = this.peek()\n this.heap[this.top] = value\n this.siftDown()\n return replacedValue\n }\n\n parent = (i) => ((i + 1) >>> 1) - 1\n left = (i) => (i << 1) + 1\n right = (i) => (i + 1) << 1\n greater = (i, j) => this.comparator(this.heap[i], this.heap[j])\n swap = (i, j) => ([this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]])\n siftUp = () => {\n let node = this.size() - 1\n while (node > this.top && this.greater(node, this.parent(node))) {\n this.swap(node, this.parent(node))\n node = this.parent(node)\n }\n }\n siftDown = () => {\n let node = this.top\n while (\n (this.left(node) < this.size() && this.greater(this.left(node), node)) ||\n (this.right(node) < this.size() && this.greater(this.right(node), node))\n ) {\n let maxChild =\n this.right(node) < this.size() &&\n this.greater(this.right(node), this.left(node))\n ? this.right(node)\n : this.left(node)\n this.swap(node, maxChild)\n node = maxChild\n }\n }\n}\n\n// another\n\n// time complexity: \n// Dijkstra + Heap is O(E log E)\n// worst case: O(N ^ 2 * log (N ^ 2))\n/**\n * @param {number[][]} edges\n * @param {number} M\n * @param {number} N\n * @return {number}\n */\nconst reachableNodes = function(edges, M, N) {\n const graph = {}\n for(const [u,v,c] of edges) {\n if(graph[u] == null) graph[u] = {}\n if(graph[v] == null) graph[v] = {}\n graph[u][v] = c\n graph[v][u] = c\n }\n const pq = new PriorityQueue((a, b) => a[0] > b[0])\n pq.push([M, 0])\n const visited = {}\n while(!pq.isEmpty()) {\n const [moves, i] = pq.pop()\n if(visited[i] == null) {\n visited[i] = moves\n for(const k of Object.keys(graph[i] || {})) {\n const remain = moves - graph[i][k] - 1\n if(visited[k] == null && remain >= 0) {\n pq.push([remain, k])\n }\n }\n }\n }\n let res = 0\n res += Object.keys(visited).length\n for(const [u, v, c] of edges) {\n const a = visited[u] || 0, b = visited[v] || 0\n res += Math.min(a + b, c)\n }\n\n return res\n};\n\nclass PriorityQueue {\n constructor(comparator = (a, b) => a > b) {\n this.heap = []\n this.top = 0\n this.comparator = comparator\n }\n size() {\n return this.heap.length\n }\n isEmpty() {\n return this.size() === 0\n }\n peek() {\n return this.heap[this.top]\n }\n push(...values) {\n values.forEach((value) => {\n this.heap.push(value)\n this.siftUp()\n })\n return this.size()\n }\n pop() {\n const poppedValue = this.peek()\n const bottom = this.size() - 1\n if (bottom > this.top) {\n this.swap(this.top, bottom)\n }\n this.heap.pop()\n this.siftDown()\n return poppedValue\n }\n replace(value) {\n const replacedValue = this.peek()\n this.heap[this.top] = value\n this.siftDown()\n return replacedValue\n }\n\n parent = (i) => ((i + 1) >>> 1) - 1\n left = (i) => (i << 1) + 1\n right = (i) => (i + 1) << 1\n greater = (i, j) => this.comparator(this.heap[i], this.heap[j])\n swap = (i, j) => ([this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]])\n siftUp = () => {\n let node = this.size() - 1\n while (node > this.top && this.greater(node, this.parent(node))) {\n this.swap(node, this.parent(node))\n node = this.parent(node)\n }\n }\n siftDown = () => {\n let node = this.top\n while (\n (this.left(node) < this.size() && this.greater(this.left(node), node)) ||\n (this.right(node) < this.size() && this.greater(this.right(node), node))\n ) {\n let maxChild =\n this.right(node) < this.size() &&\n this.greater(this.right(node), this.left(node))\n ? this.right(node)\n : this.left(node)\n this.swap(node, maxChild)\n node = maxChild\n }\n }\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720ca2", + "questionid": 471, + "title": "Super Egg Drop", + "slug": "super-egg-drop", + "description": "You are given k identical eggs and you have access to a building with n floors labeled from 1 to n. You know that there exists a floor f where 0 <= f <= n such that any egg dropped at a floor higher than f will break, and any egg dropped at or below floor f will not break. Each move, you may take an unbroken egg and drop it from any floor x (where 1 <= x <= n). If the egg breaks, you can no longer use it. However, if the egg does not break, you may reuse it in future moves. Return the minimum number of moves that you need to determine with certainty what the value of f is. ", + "category": [ + "Math", + "Binary Search", + "Dynamic Programming" + ], + "complexity": "Hard", + "successrate": 27.2, + "totalsubmissions": 164494, + "totalaccepted": 44710, + "likes": 2338, + "dislikes": 130, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "k = 1, n = 2", + "expected_output": "2\nExplanation: \nDrop the egg from floor 1. If it breaks, we know that f = 0.\nOtherwise, drop the egg from floor 2. If it breaks, we know that f = 1.\nIf it does not break, then we know f = 2.\nHence, we need at minimum 2 moves to determine with certainty what the value of f is.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "k = 2, n = 6", + "expected_output": "3", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "k = 3, n = 14", + "expected_output": "4", + "explanation": "" + } + ], + "solution": "/**\n * @param {number} K\n * @param {number} N\n * @return {number}\n */\n\nconst superEggDrop = function(K, N) {\n let lo = 1,\n hi = N,\n mi\n while (lo < hi) {\n mi = ((lo + hi) / 2) >> 0\n if (f(mi, K, N) < N) lo = mi + 1\n else hi = mi\n }\n return lo\n}\n\nfunction f(x, K, N) {\n let ans = 0,\n r = 1,\n i = 1\n for (let i = 1; i <= K; ++i) {\n r = ((r * (x - i + 1)) / i) >> 0\n ans += r\n if (ans >= N) break\n }\n return ans\n}\n\n// another\n\nconst superEggDrop = function(K, N) {\n const dp = Array.from({ length: K + 1 }, () => new Array(N + 1).fill(0))\n return helper(K, N, dp)\n}\nfunction helper(K, N, memo) {\n if (N <= 1) {\n return N\n }\n if (K === 1) {\n return N\n }\n if (memo[K][N] > 0) {\n return memo[K][N]\n }\n\n let low = 1,\n high = N,\n result = N\n while (low < high) {\n let mid = Math.floor(low + (high - low) / 2)\n let left = helper(K - 1, mid - 1, memo)\n let right = helper(K, N - mid, memo)\n result = Math.min(result, Math.max(left, right) + 1)\n if (left === right) {\n break\n } else if (left < right) {\n low = mid + 1\n } else {\n high = mid\n }\n }\n memo[K][N] = result\n return result\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720ca3", + "questionid": 472, + "title": "Fair Candy Swap", + "slug": "fair-candy-swap", + "description": "Alice and Bob have a different total number of candies. You are given two integer arrays aliceSizes and bobSizes where aliceSizes[i] is the number of candies of the ith box of candy that Alice has and bobSizes[j] is the number of candies of the jth box of candy that Bob has. Since they are friends, they would like to exchange one candy box each so that after the exchange, they both have the same total amount of candy. The total amount of candy a person has is the sum of the number of candies in each box they have. Return an integer array answer where answer[0] is the number of candies in the box that Alice must exchange, and answer[1] is the number of candies in the box that Bob must exchange. If there are multiple answers, you may return any one of them. It is guaranteed that at least one answer exists. ", + "category": [ + "Array", + "Hash Table", + "Binary Search", + "Sorting" + ], + "complexity": "Easy", + "successrate": 60.4, + "totalsubmissions": 133364, + "totalaccepted": 80560, + "likes": 1249, + "dislikes": 230, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "aliceSizes = [1,1], bobSizes = [2,2]", + "expected_output": "[1,2]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "aliceSizes = [1,2], bobSizes = [2,3]", + "expected_output": "[1,2]", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "aliceSizes = [2], bobSizes = [1,3]", + "expected_output": "[2,3]", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} aliceSizes\n * @param {number[]} bobSizes\n * @return {number[]}\n */\nconst fairCandySwap = function(aliceSizes, bobSizes) {\n let sum = 0\n for(let e of aliceSizes) sum += e\n for(let e of bobSizes) sum -= e\n // sum > 0, alice > bob\n // sum < 0, alice < bob\n sum /= 2\n const set = new Set()\n for(let e of aliceSizes) set.add(e)\n for(let e of bobSizes) {\n if(set.has(e + sum)) return [e + sum, e]\n }\n return [0]\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720ca7", + "questionid": 476, + "title": "Monotonic Array", + "slug": "monotonic-array", + "description": "An array is monotonic if it is either monotone increasing or monotone decreasing. An array nums is monotone increasing if for all i <= j, nums[i] <= nums[j]. An array nums is monotone decreasing if for all i <= j, nums[i] >= nums[j]. Given an integer array nums, return true if the given array is monotonic, or false otherwise. ", + "category": [ + "Array" + ], + "complexity": "Easy", + "successrate": 58.4, + "totalsubmissions": 345603, + "totalaccepted": 202002, + "likes": 1478, + "dislikes": 54, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,2,2,3]", + "expected_output": "true", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "nums = [6,5,4,4]", + "expected_output": "true", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "nums = [1,3,2]", + "expected_output": "false", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} nums\n * @return {boolean}\n */\nconst isMonotonic = function(nums) {\n return inc(nums) || dec(nums)\n};\n\nfunction inc(nums) {\n if(nums == null || nums.length <= 1) return true\n for(let i = 1, n = nums.length; i < n; i++) {\n if(nums[i] < nums[i - 1]) return false\n }\n return true \n}\nfunction dec(nums) {\n if(nums == null || nums.length <= 1) return true\n for(let i = 1, n = nums.length; i < n; i++) {\n if(nums[i] > nums[i - 1]) return false\n }\n return true \n}\n\n// another\n\n/**\n * @param {number[]} nums\n * @return {boolean}\n */\nconst isMonotonic = function(nums) {\n let inc = true, dec = true\n for(let i = 1, n = nums.length; i < n; i++) {\n inc &= nums[i] >= nums[i - 1]\n dec &= nums[i] <= nums[i - 1]\n }\n return inc || dec\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720cb5", + "questionid": 490, + "title": "3Sum With Multiplicity", + "slug": "3sum-with-multiplicity", + "description": "Given an integer array arr, and an integer target, return the number of tuples i, j, k such that i < j < k and arr[i] + arr[j] + arr[k] == target. As the answer can be very large, return it modulo 109 + 7. ", + "category": [ + "Array", + "Hash Table", + "Two Pointers", + "Sorting", + "Counting" + ], + "complexity": "Medium", + "successrate": 45.4, + "totalsubmissions": 188183, + "totalaccepted": 85475, + "likes": 2186, + "dislikes": 265, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "arr = [1,1,2,2,3,3,4,4,5,5], target = 8", + "expected_output": "20\nExplanation: \nEnumerating by the values (arr[i], arr[j], arr[k]):\n(1, 2, 5) occurs 8 times;\n(1, 3, 4) occurs 8 times;\n(2, 2, 4) occurs 2 times;\n(2, 3, 3) occurs 2 times.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "arr = [1,1,2,2,2,2], target = 5", + "expected_output": "12\nExplanation: \narr[i] = 1, arr[j] = arr[k] = 2 occurs 12 times:\nWe choose one 1 from [1,1] in 2 ways,\nand two 2s from [2,2,2,2] in 6 ways.", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "arr = [2,1,3], target = 6", + "expected_output": "1", + "explanation": "(1, 2, 3) occured one time in the array so we return 1." + } + ], + "solution": "/**\n * @param {number[]} A\n * @param {number} target\n * @return {number}\n */\nconst threeSumMulti = function(A, target) {\n const d = {};\n let res = 0;\n const mod = Math.pow(10, 9) + 7;\n for (let i = 0; i < A.length; i++) {\n res += d[target - A[i]] >= 0 ? d[target - A[i]] : 0;\n res %= mod;\n for (let j = 0; j < i; j++) {\n d[A[i] + A[j]] = (d[A[i] + A[j]] || 0) + 1;\n }\n }\n return res % mod;\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720cb6", + "questionid": 491, + "title": "Minimize Malware Spread", + "slug": "minimize-malware-spread", + "description": "You are given a network of n nodes represented as an n x n adjacency matrix graph, where the ith node is directly connected to the jth node if graph[i][j] == 1. Some nodes initial are initially infected by malware. Whenever two nodes are directly connected, and at least one of those two nodes is infected by malware, both nodes will be infected by malware. This spread of malware will continue until no more nodes can be infected in this manner. Suppose M(initial) is the final number of nodes infected with malware in the entire network after the spread of malware stops. We will remove exactly one node from initial. Return the node that, if removed, would minimize M(initial). If multiple nodes could be removed to minimize M(initial), return such a node with the smallest index. Note that if a node was removed from the initial list of infected nodes, it might still be infected later due to the malware spread. ", + "category": [ + "Array", + "Depth-First Search", + "Breadth-First Search", + "Union Find", + "Matrix" + ], + "complexity": "Hard", + "successrate": 41.9, + "totalsubmissions": 87853, + "totalaccepted": 36826, + "likes": 607, + "dislikes": 407, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "graph = [[1,1,0],[1,1,0],[0,0,1]], initial = [0,1]", + "expected_output": "0", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "graph = [[1,0,0],[0,1,0],[0,0,1]], initial = [0,2]", + "expected_output": "0", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "graph = [[1,1,1],[1,1,1],[1,1,1]], initial = [1,2]", + "expected_output": "1", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[][]} graph\n * @param {number[]} initial\n * @return {number}\n */\nconst minMalwareSpread = function (graph, initial) {\n const l = graph.length\n const p = []\n const children = []\n for (let i = 0; i < l; i++) {\n p[i] = i\n children[i] = [i]\n }\n\n for (let i = 0; i < l; i++) {\n for (let j = i + 1; j < l; j++) {\n if (graph[i][j] === 1) {\n const pi = find(i)\n const pj = find(j)\n if (pi !== pj) {\n union(pi, pj)\n }\n }\n }\n }\n\n initial.sort((a, b) => (a > b ? 1 : -1))\n\n const count = {}\n\n let index = initial[0]\n let max = 0\n // find the index that not unioned with other indexes and with the most number of children\n initial.forEach((e) => {\n const pe = find(e)\n if (!count[pe]) count[pe] = 0\n count[pe] += 1\n })\n initial.forEach((e, i) => {\n const pe = find(e)\n if (count[pe] === 1 && children[pe].length > max) {\n max = children[pe].length\n index = e\n }\n })\n\n return index\n\n function find(x) {\n while (p[x] !== x) {\n p[x] = p[p[x]]\n x = p[x]\n }\n return x\n }\n\n function union(pi, pj) {\n p[pj] = pi\n //also move the children to the new parent\n children[pi] = children[pi].concat(children[pj])\n children[pj] = []\n }\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720cbd", + "questionid": 498, + "title": "Shortest Bridge", + "slug": "shortest-bridge", + "description": "You are given an n x n binary matrix grid where 1 represents land and 0 represents water. An island is a 4-directionally connected group of 1's not connected to any other 1's. There are exactly two islands in grid. You may change 0's to 1's to connect the two islands to form one island. Return the smallest number of 0's you must flip to connect the two islands. ", + "category": [ + "Array", + "Depth-First Search", + "Breadth-First Search", + "Matrix" + ], + "complexity": "Medium", + "successrate": 52.7, + "totalsubmissions": 169542, + "totalaccepted": 89265, + "likes": 2481, + "dislikes": 127, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "grid = [[0,1],[1,0]]", + "expected_output": "1", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "grid = [[0,1,0],[0,0,0],[0,0,1]]", + "expected_output": "2", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "grid = [[1,1,1,1,1],[1,0,0,0,1],[1,0,1,0,1],[1,0,0,0,1],[1,1,1,1,1]]", + "expected_output": "1", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[][]} A\n * @return {number}\n */\nconst shortestBridge = function(A) {\n let r = A.length;\n let c = A[0].length;\n let found = false;\n let queue = [];\n for (let i = 0; i < r; i++) {\n for (let j = 0; j < c; j++) {\n if (A[i][j]) {\n dfs(A, i, j, queue);\n found = true;\n break;\n }\n }\n if (found) break;\n }\n \n let replace = [];\n let count = 0;\n let cells = [[1, 0], [-1, 0], [0, 1], [0, -1]];\n while (queue.length) {\n let pos = queue.shift();\n \n for (let i = 0; i < cells.length; i++) {\n let x = pos[0] + cells[i][0]; \n let y = pos[1] + cells[i][1];\n \n if (0 <= x && x < r && 0 <= y && y < c && A[x][y] != 2) {\n if (A[x][y] == 1) return count;\n A[x][y] = 2;\n replace.push([x, y]);\n }\n }\n \n if (!queue.length) {\n queue = replace;\n replace = [];\n count++;\n }\n }\n};\n\nfunction dfs(A, x, y, queue) {\n if (x < 0 || x >= A.length || y < 0 || y >= A[0].length || A[x][y] == 0 || A[x][y] == 2) return;\n \n A[x][y] = 2;\n queue.push([x, y]);\n dfs(A, x-1, y, queue);\n dfs(A, x+1, y, queue);\n dfs(A, x, y-1, queue);\n dfs(A, x, y+1, queue);\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720cbe", + "questionid": 499, + "title": "Stamping The Sequence", + "slug": "stamping-the-sequence", + "description": "You are given two strings stamp and target. Initially, there is a string s of length target.length with all s[i] == '?'. In one turn, you can place stamp over s and replace every letter in the s with the corresponding letter from stamp. We want to convert s to target using at most 10 * target.length turns. Return an array of the index of the left-most letter being stamped at each turn. If we cannot obtain target from s within 10 * target.length turns, return an empty array. ", + "category": [ + "String", + "Stack", + "Greedy", + "Queue" + ], + "complexity": "Hard", + "successrate": 53.6, + "totalsubmissions": 44732, + "totalaccepted": 23964, + "likes": 531, + "dislikes": 125, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "stamp = "abc", target = "ababc"", + "expected_output": "[0,2]", + "explanation": "Initially s = "?????".\n- Place stamp at index 0 to get "abc??".\n- Place stamp at index 2 to get "ababc".\n[1,0,2] would also be accepted as an answer, as well as some other answers." + }, + { + "example_num": 2, + "expected_input": "stamp = "abca", target = "aabcaca"", + "expected_output": "[3,0,1]", + "explanation": "Initially s = "???????".\n- Place stamp at index 3 to get "???abca".\n- Place stamp at index 0 to get "abcabca".\n- Place stamp at index 1 to get "aabcaca"." + } + ], + "solution": "/**\n * @param {string} stamp\n * @param {string} target\n * @return {number[]}\n */\nconst movesToStamp = function (stamp, target) {\n const S = stamp.split('')\n const T = target.split('')\n const res = []\n const visited = Array(T.length).fill(false)\n let stars = 0\n\n while (stars < T.length) {\n let doneReplace = false\n for (let i = 0; i <= T.length - S.length; i++) {\n if (!visited[i] && canReplace(T, i, S)) {\n stars = doReplace(T, i, S.length, stars)\n doneReplace = true\n visited[i] = true\n res.unshift(i)\n if (stars === T.length) {\n break\n }\n }\n }\n\n if (!doneReplace) {\n return []\n }\n }\n\n return res\n function canReplace(T, p, S) {\n for (let i = 0; i < S.length; i++) {\n if (T[i + p] !== '*' && T[i + p] !== S[i]) {\n return false\n }\n }\n return true\n }\n\n function doReplace(T, p, len, count) {\n for (let i = 0; i < len; i++) {\n if (T[i + p] !== '*') {\n T[i + p] = '*'\n count++\n }\n }\n return count\n }\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720cc0", + "questionid": 501, + "title": "Minimum Area Rectangle", + "slug": "minimum-area-rectangle", + "description": "You are given an array of points in the X-Y plane points where points[i] = [xi, yi]. Return the minimum area of a rectangle formed from these points, with sides parallel to the X and Y axes. If there is not any such rectangle, return 0. ", + "category": [ + "Array", + "Hash Table", + "Math", + "Geometry", + "Sorting" + ], + "complexity": "Medium", + "successrate": 53.5, + "totalsubmissions": 189171, + "totalaccepted": 101237, + "likes": 1426, + "dislikes": 223, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "points = [[1,1],[1,3],[3,1],[3,3],[2,2]]", + "expected_output": "4", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "points = [[1,1],[1,3],[3,1],[3,3],[4,1],[4,3]]", + "expected_output": "2", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[][]} points\n * @return {number}\n */\nconst minAreaRect = function(points) {\n const xmap = {}, ymap = {}\n points.forEach(e => {\n const [x, y] = e\n if(!xmap.hasOwnProperty(x)) xmap[x] = new Set()\n if(!ymap.hasOwnProperty(y)) ymap[y] = new Set()\n xmap[x].add(y)\n ymap[y].add(x)\n })\n let res = Infinity\n for(let i = 0, len = points.length; i < len - 1; i++) {\n const [x, y] = points[i]\n for(let j = i + 1; j < len; j++) {\n const [x1, y1] = points[j]\n if(x === x1 || y === y1) continue\n let area = Infinity\n if(xmap[x].has(y1) && ymap[y].has(x1)) area = Math.abs(x - x1) * Math.abs(y - y1)\n else continue\n res = Math.min(res, area)\n }\n }\n return res === Infinity ? 0 : res\n};\n\n// another\n\n/**\n * @param {number[][]} points\n * @return {number}\n */\nconst minAreaRect = function (points) {\n let ans = Infinity\n const isPoint = {}\n points.forEach(([x, y]) => (isPoint[x * 40000 + y] = true))\n for (let idx1 = 0; idx1 < points.length - 1; idx1++) {\n const [x1, y1] = points[idx1]\n for (let idx2 = idx1 + 1; idx2 < points.length; idx2++) {\n const [x2, y2] = points[idx2]\n const area = Math.abs((x1 - x2) * (y1 - y2))\n if (area === 0 || area >= ans) continue\n if (isPoint[x1 * 40000 + y2] && isPoint[x2 * 40000 + y1]) ans = area\n }\n }\n return ans !== Infinity ? ans : 0\n}\n\n" + }, + { + "_id": "66f925ddfdfb8e1665720cc2", + "questionid": 503, + "title": "Find the Shortest Superstring", + "slug": "find-the-shortest-superstring", + "description": "Given an array of strings words, return the smallest string that contains each string in words as a substring. If there are multiple valid strings of the smallest length, return any of them. You may assume that no string in words is a substring of another string in words. ", + "category": [ + "Array", + "String", + "Dynamic Programming", + "Bit Manipulation", + "Bitmask" + ], + "complexity": "Hard", + "successrate": 45.4, + "totalsubmissions": 51494, + "totalaccepted": 23384, + "likes": 1002, + "dislikes": 126, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "words = ["alex","loves","leetcode"]", + "expected_output": ""alexlovesleetcode"", + "explanation": "All permutations of "alex","loves","leetcode" would also be accepted." + }, + { + "example_num": 2, + "expected_input": "words = ["catg","ctaagt","gcta","ttca","atgcatc"]", + "expected_output": ""gctaagttcatgcatc"", + "explanation": "" + } + ], + "solution": "/**\n * @param {string[]} A\n * @return {string}\n */\nconst shortestSuperstring = function(arr) {\n while (arr.length > 1) {\n let maxCommonLength = 0\n let maxCommonString = arr[0] + arr[1]\n let maxCommonWords = [arr[0], arr[1]]\n for (let i = 0; i < arr.length - 1; i++) {\n for (let j = i + 1; j < arr.length; j++) {\n const { commonLength, commonString } = checkCommonPair(arr[i], arr[j])\n if (commonString && commonLength >= maxCommonLength) {\n maxCommonLength = commonLength\n maxCommonString = commonString\n maxCommonWords = [arr[i], arr[j]]\n }\n }\n }\n arr = arr.filter(\n word => word !== maxCommonWords[0] && word !== maxCommonWords[1]\n )\n arr.unshift(maxCommonString)\n }\n return arr[0]\n}\n\nconst checkCommonPair = function(s1, s2) {\n let maxCommonLength = 0\n let commonString = ''\n if (s1.length > s2.length) s1, (s2 = s2), s1\n for (let stringLength = 1; stringLength < s1.length; stringLength++) {\n const s1Suffix = s1.substring(s1.length - stringLength)\n const s2Prefix = s2.substring(0, stringLength)\n if (s1Suffix === s2Prefix && stringLength > maxCommonLength) {\n maxCommonLength = stringLength\n commonString = s1 + s2.substring(stringLength)\n }\n }\n for (let stringLength = 1; stringLength < s1.length; stringLength++) {\n const s1Prefix = s1.substring(0, stringLength)\n const s2Suffix = s2.substring(s2.length - stringLength)\n if (s1Prefix === s2Suffix && stringLength > maxCommonLength) {\n if (stringLength > maxCommonLength) {\n maxCommonLength = stringLength\n commonString = s2 + s1.substring(stringLength)\n }\n }\n }\n\n return {\n commonLength: maxCommonLength,\n commonString\n }\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720cc4", + "questionid": 505, + "title": "Validate Stack Sequences", + "slug": "validate-stack-sequences", + "description": "Given two integer arrays pushed and popped each with distinct values, return true if this could have been the result of a sequence of push and pop operations on an initially empty stack, or false otherwise. ", + "category": [ + "Array", + "Stack", + "Simulation" + ], + "complexity": "Medium", + "successrate": 67.6, + "totalsubmissions": 259252, + "totalaccepted": 175192, + "likes": 3509, + "dislikes": 61, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "pushed = [1,2,3,4,5], popped = [4,5,3,2,1]", + "expected_output": "true", + "explanation": "We might do the following sequence:\npush(1), push(2), push(3), push(4),\npop() -> 4,\npush(5),\npop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1" + }, + { + "example_num": 2, + "expected_input": "pushed = [1,2,3,4,5], popped = [4,3,5,1,2]", + "expected_output": "false", + "explanation": "1 cannot be popped before 2." + } + ], + "solution": "/**\n * @param {number[]} pushed\n * @param {number[]} popped\n * @return {boolean}\n */\nconst validateStackSequences = function(pushed, popped) {\n const arr = []\n for (let i = 0, len = pushed.length; i < len; i++) {\n if (!helper(arr, pushed, popped)) return false\n }\n return true\n}\n\nfunction helper(arr, pu, po) {\n let target = po[0]\n\n while (arr.length || pu.length) {\n let curP = pu[0]\n if (curP === target) {\n po.shift()\n pu.shift()\n return true\n } else if (arr.length && arr[arr.length - 1] === target) {\n arr.pop()\n po.shift()\n return true\n } else {\n if (curP == null) {\n return false\n } else {\n arr.push(curP)\n pu.shift()\n }\n }\n }\n return false\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720cc8", + "questionid": 509, + "title": "Delete Columns to Make Sorted II", + "slug": "delete-columns-to-make-sorted-ii", + "description": "You are given an array of n strings strs, all of the same length. We may choose any deletion indices, and we delete all the characters in those indices for each string. For example, if we have strs = [\"abcdef\",\"uvwxyz\"] and deletion indices {0, 2, 3}, then the final array after deletions is [\"bef\", \"vyz\"]. Suppose we chose a set of deletion indices answer such that after deletions, the final array has its elements in lexicographic order (i.e., strs[0] <= strs[1] <= strs[2] <= ... <= strs[n - 1]). Return the minimum possible value of answer.length. ", + "category": [ + "Array", + "String", + "Greedy" + ], + "complexity": "Medium", + "successrate": 34.2, + "totalsubmissions": 44573, + "totalaccepted": 15248, + "likes": 443, + "dislikes": 69, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "strs = ["ca","bb","ac"]", + "expected_output": "1", + "explanation": "After deleting the first column, strs = ["a", "b", "c"].\nNow strs is in lexicographic order (ie. strs[0] <= strs[1] <= strs[2]).\nWe require at least 1 deletion since initially strs was not in lexicographic order, so the answer is 1." + }, + { + "example_num": 2, + "expected_input": "strs = ["xc","yb","za"]", + "expected_output": "0", + "explanation": "strs is already in lexicographic order, so we do not need to delete anything.\nNote that the rows of strs are not necessarily in lexicographic order:\ni.e., it is NOT necessarily true that (strs[0][0] <= strs[0][1] <= ...)" + }, + { + "example_num": 3, + "expected_input": "strs = ["zyx","wvu","tsr"]", + "expected_output": "3", + "explanation": "We have to delete every column." + } + ], + "solution": "/**\n * @param {string[]} A\n * @return {number}\n */\nconst minDeletionSize = function (A) {\n let res = 0,\n i,\n j //n: \u6709\u591a\u5c11\u4e2a\u5b57\u7b26\u4e32\uff0c\u5bf9\u5e94i. m:\u6bcf\u4e2a\u5b57\u7b26\u4e32\u7684\u957f\u5ea6,\u5bf9\u5e94j\n const n = A.length,\n m = A[0].length,\n sorted = new Array(n - 1).fill(false)\n for (j = 0; j < m; ++j) {\n //\u4ece\u7b2c\u4e00\u4e2a\u5b57\u7b26\u5230\u6700\u540e\u4e00\u4e2a\u5b57\u7b26\n for (i = 0; i < n - 1; ++i) {\n //i\u4ece\u7b2c\u4e00\u4e2a\u5b57\u5230\u6700\u540e\u4e00\u4e2a\u5b57\n if (!sorted[i] && A[i].charAt(j) > A[i + 1].charAt(j)) {\n res++\n break\n }\n }\n if (i < n - 1) continue\n\n //\u5047\u8bbe\u8f93\u5165\u662f[\"xgag\",\"xfba\",\"yfac\"]\n //\u90a3\u4e48\u7b2c\u4e00\u8f6ej=0,\u6bd4\u8f83\u7b2c\u4e00\u5217: x=xf,\u8fdb\u5165if\u6761\u4ef6\u8bed\u53e5\uff0c\u6240\u4ee5res = 1, break\n //\u7136\u540e\u7b2c\u4e09\u8f6ej=2,aa,\u8fd9\u91ccb\u867d\u7136>a\uff0c\u4f46\u662f\u7531\u4e8esorted[xfb] = true\uff0c\u6240\u4ee5\u4e0d\u4f1a\u8fdb\u5165\u5230\u4e0a\u9762\u7684\u5faa\u73af\u4f53\uff0c\u7136\u540esorted[xga] = true\n //\u7136\u540e\u7b2c\u56db\u8f6ej=3,\u8fd9\u4e00\u8f6e\u5df2\u7ecf\u4e0d\u518d\u91cd\u8981\uff0c\u56e0\u4e3a\u901a\u8fc7\u524d\u9762\u51e0\u8f6e sorted[0] = true\uff0c sorted[1] = true, \u8fd9\u610f\u5473\u7740\u5df2\u7ecf\u5b9e\u73b0\u4e86\u6392\u5e8f\uff0c\u6240\u4ee5res\u6700\u7ec8\u7ed3\u679c\u5c31\u662f1\n\n for (\n i = 0;\n i < n - 1;\n ++i //\u8fd9\u4e00\u6bb5\u4ee3\u7801\u7ed3\u5408\u6700\u5916\u9762\u7684\u5faa\u73af\u53ef\u4ee5\u7528\u4f5c\u6bd4\u8f83string\u5927\u5c0f\u7684\u901a\u7528\u4ee3\u7801\n )\n if (A[i].charAt(j) < A[i + 1].charAt(j)) sorted[i] = true\n }\n return res\n}\n\n// another\n\n/**\n * @param {string[]} A\n * @return {number}\n */\nconst minDeletionSize = function (A) {\n const set = new Set()\n const m = A.length\n let res = 0\n if(m === 0) return 0\n const n = A[0].length\n for(j = 0; j < n; j++) {\n if(set.size === m - 1) return res\n for(i = 0; i < m - 1; i++) {\n if(!set.has(i) && A[i][j] > A[i + 1][j]) {\n res++\n break\n }\n }\n if(i < m - 1) continue\n for(i = 0; i < m - 1; i++) {\n if(A[i][j] < A[i + 1][j]) set.add(i)\n }\n }\n \n return res\n}\n\n" + }, + { + "_id": "66f925ddfdfb8e1665720ccd", + "questionid": 514, + "title": "Maximum Width Ramp", + "slug": "maximum-width-ramp", + "description": "A ramp in an integer array nums is a pair (i, j) for which i < j and nums[i] <= nums[j]. The width of such a ramp is j - i. Given an integer array nums, return the maximum width of a ramp in nums. If there is no ramp in nums, return 0. ", + "category": [ + "Array", + "Stack", + "Monotonic Stack" + ], + "complexity": "Medium", + "successrate": 48.2, + "totalsubmissions": 68082, + "totalaccepted": 32790, + "likes": 1125, + "dislikes": 35, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [6,0,8,2,1,5]", + "expected_output": "4", + "explanation": "The maximum width ramp is achieved at (i, j) = (1, 5): nums[1] = 0 and nums[5] = 5." + }, + { + "example_num": 2, + "expected_input": "nums = [9,8,1,0,1,9,4,0,4,1]", + "expected_output": "7", + "explanation": "The maximum width ramp is achieved at (i, j) = (2, 9): nums[2] = 1 and nums[9] = 1." + } + ], + "solution": "/**\n * @param {number[]} nums\n * @return {number}\n */\nconst maxWidthRamp = function(nums) {\n const s = [];\n let res = 0, n = nums.length;\n for (let i = 0; i < n; ++i) {\n if (s.length === 0 || nums[s.at(-1)] > nums[i]) s.push(i); \n }\n\n for (let i = n - 1; i > res; --i) {\n while (s.length && nums[s.at(-1)] <= nums[i]) res = Math.max(res, i - s.pop()); \n }\n\n return res;\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720cd1", + "questionid": 518, + "title": "Binary Tree Cameras", + "slug": "binary-tree-cameras", + "description": "You are given the root of a binary tree. We install cameras on the tree nodes where each camera at a node can monitor its parent, itself, and its immediate children. Return the minimum number of cameras needed to monitor all nodes of the tree. ", + "category": [ + "Dynamic Programming", + "Tree", + "Depth-First Search", + "Binary Tree" + ], + "complexity": "Hard", + "successrate": 41.8, + "totalsubmissions": 151382, + "totalaccepted": 63331, + "likes": 2594, + "dislikes": 33, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [0,0,null,0,0]", + "expected_output": "1", + "explanation": "One camera is enough to monitor all nodes if placed as shown." + }, + { + "example_num": 2, + "expected_input": "root = [0,0,null,0,null,0,null,null,0]", + "expected_output": "2", + "explanation": "At least two cameras are needed to monitor all nodes of the tree. The above image shows one of the valid configurations of camera placement." + } + ], + "solution": "/**\n * Definition for a binary tree node.\n * function TreeNode(val) {\n * this.val = val;\n * this.left = this.right = null;\n * }\n */\n/**\n * @param {TreeNode} root\n * @return {number}\n */\nconst minCameraCover = function(root) {\n if (root === null) return 0;\n let max = 0;\n return (helper(root) < 1 ? 1 : 0) + max;\n function helper(root) {\n if (root === null) return 2;\n if (root.left === null && root.right === null) return 0;\n let left = helper(root.left);\n let right = helper(root.right);\n if (left === 0 || right === 0) {\n max++;\n return 1;\n }\n return left === 1 || right === 1 ? 2 : 0;\n }\n};\n\n // another\n\n/**\n * @param {TreeNode} root\n * @return {number}\n */\nconst minCameraCover = function(root) {\n let ans = 0\n const covered = new Set([null])\n dfs(root, null)\n return ans\n function dfs(node, parent) {\n if (node) {\n dfs(node.left, node)\n dfs(node.right, node)\n if (\n !(\n (parent || covered.has(node)) &&\n covered.has(node.left) &&\n covered.has(node.right)\n )\n ) {\n ans += 1\n covered\n .add(node)\n .add(parent)\n .add(node.left)\n .add(node.right)\n }\n }\n }\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720cd4", + "questionid": 521, + "title": "K Closest Points to Origin", + "slug": "k-closest-points-to-origin", + "description": "Given an array of points where points[i] = [xi, yi] represents a point on the X-Y plane and an integer k, return the k closest points to the origin (0, 0). The distance between two points on the X-Y plane is the Euclidean distance (i.e., \u02c6\u0161(x1 - x2)2 + (y1 - y2)2). You may return the answer in any order. The answer is guaranteed to be unique (except for the order that it is in). ", + "category": [ + "Array", + "Math", + "Divide and Conquer", + "Geometry", + "Sorting", + "Heap (Priority Queue)", + "Quickselect" + ], + "complexity": "Medium", + "successrate": 66, + "totalsubmissions": 1115681, + "totalaccepted": 736146, + "likes": 5350, + "dislikes": 205, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "points = [[1,3],[-2,2]], k = 1", + "expected_output": "[[-2,2]]", + "explanation": "The distance between (1, 3) and the origin is sqrt(10).\nThe distance between (-2, 2) and the origin is sqrt(8).\nSince sqrt(8) < sqrt(10), (-2, 2) is closer to the origin.\nWe only want the closest k = 1 points from the origin, so the answer is just [[-2,2]]." + }, + { + "example_num": 2, + "expected_input": "points = [[3,3],[5,-1],[-2,4]], k = 2", + "expected_output": "[[3,3],[-2,4]]", + "explanation": "The answer [[-2,4],[3,3]] would also be accepted." + } + ], + "solution": "/**\n * @param {number[][]} points\n * @param {number} K\n * @return {number[][]}\n */\nconst kClosest = (points, K) => {\n let len = points.length,\n l = 0,\n r = len - 1\n while (l <= r) {\n let mid = helper(points, l, r)\n if (mid === K) break\n if (mid < K) {\n l = mid + 1\n } else {\n r = mid - 1\n }\n }\n return points.slice(0, K)\n}\n\nfunction helper(A, l, r) {\n let pivot = A[l]\n let ll = l\n while (l < r) {\n while (l < r && compare(A[r], pivot) >= 0) r--\n while (l < r && compare(A[l], pivot) <= 0) l++\n swap(A, l, r)\n }\n swap(A, ll, l)\n return l\n}\nfunction swap(arr, i, j) {\n let tmp = arr[i]\n arr[i] = arr[j]\n arr[j] = tmp\n}\n\nfunction compare(p1, p2) {\n return p1[0] * p1[0] + p1[1] * p1[1] - p2[0] * p2[0] - p2[1] * p2[1]\n}\n\n\n// another\n\n/**\n * @param {number[][]} points\n * @param {number} K\n * @return {number[][]}\n */\nconst kClosest = (points, K) => {\n const pq = new PriorityQueue(\n (p1, p2) => p1[0] * p1[0] + p1[1] * p1[1] > p2[0] * p2[0] + p2[1] * p2[1]\n )\n for (let p of points) {\n pq.push(p)\n if (pq.size() > K) {\n pq.pop()\n }\n }\n const res = new Array(K)\n while (K > 0) {\n res[--K] = pq.pop()\n }\n return res\n}\n\nclass PriorityQueue {\n constructor(comparator = (a, b) => a > b) {\n this.heap = []\n this.top = 0\n this.comparator = comparator\n }\n size() {\n return this.heap.length\n }\n isEmpty() {\n return this.size() === 0\n }\n peek() {\n return this.heap[this.top]\n }\n push(...values) {\n values.forEach((value) => {\n this.heap.push(value)\n this.siftUp()\n })\n return this.size()\n }\n pop() {\n const poppedValue = this.peek()\n const bottom = this.size() - 1\n if (bottom > this.top) {\n this.swap(this.top, bottom)\n }\n this.heap.pop()\n this.siftDown()\n return poppedValue\n }\n replace(value) {\n const replacedValue = this.peek()\n this.heap[this.top] = value\n this.siftDown()\n return replacedValue\n }\n\n parent = (i) => ((i + 1) >>> 1) - 1\n left = (i) => (i << 1) + 1\n right = (i) => (i + 1) << 1\n greater = (i, j) => this.comparator(this.heap[i], this.heap[j])\n swap = (i, j) => ([this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]])\n siftUp = () => {\n let node = this.size() - 1\n while (node > this.top && this.greater(node, this.parent(node))) {\n this.swap(node, this.parent(node))\n node = this.parent(node)\n }\n }\n siftDown = () => {\n let node = this.top\n while (\n (this.left(node) < this.size() && this.greater(this.left(node), node)) ||\n (this.right(node) < this.size() && this.greater(this.right(node), node))\n ) {\n let maxChild =\n this.right(node) < this.size() &&\n this.greater(this.right(node), this.left(node))\n ? this.right(node)\n : this.left(node)\n this.swap(node, maxChild)\n node = maxChild\n }\n }\n}\n\n// another\n\n/**\n * @param {number[][]} points\n * @param {number} k\n * @return {number[][]}\n */\nconst kClosest = function(points, k) {\n let len = points.length, l = 0, r = len - 1\n while (l <= r) {\n let mid = helper(points, l, r)\n if (mid === k) break\n if (mid < k) l = mid + 1\n else r = mid - 1\n }\n return points.slice(0, k)\n\n function helper(arr, l, r) {\n const pivot = arr[l]\n while(l < r) {\n while(l < r && cmp(arr[r], pivot) >= 0) r--\n arr[l] = arr[r]\n while(l < r && cmp(arr[l], pivot) <= 0) l++\n arr[r] = arr[l]\n }\n arr[l] = pivot\n return l\n }\n \n function cmp(a, b) {\n return a[0] * a[0] + a[1] * a[1] - b[0] * b[0] - b[1] * b[1]\n }\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720cd6", + "questionid": 523, + "title": "Largest Perimeter Triangle", + "slug": "largest-perimeter-triangle", + "description": "Given an integer array nums, return the largest perimeter of a triangle with a non-zero area, formed from three of these lengths. If it is impossible to form any triangle of a non-zero area, return 0. ", + "category": [ + "Array", + "Math", + "Greedy", + "Sorting" + ], + "complexity": "Easy", + "successrate": 56, + "totalsubmissions": 137802, + "totalaccepted": 77188, + "likes": 1065, + "dislikes": 119, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [2,1,2]", + "expected_output": "5", + "explanation": "You can form a triangle with three side lengths: 1, 2, and 2." + }, + { + "example_num": 2, + "expected_input": "nums = [1,2,1,10]", + "expected_output": "0", + "explanation": "You cannot use the side lengths 1, 1, and 2 to form a triangle.\nYou cannot use the side lengths 1, 1, and 10 to form a triangle.\nYou cannot use the side lengths 1, 2, and 10 to form a triangle.\nAs we cannot use any three side lengths to form a triangle of non-zero area, we return 0." + } + ], + "solution": "/**\n * @param {number[]} nums\n * @return {number}\n */\nconst largestPerimeter = function(nums) {\n nums.sort((a, b) => a - b)\n for(let i = nums.length - 1; i > 1; i--) {\n if(nums[i] < nums[i - 1] + nums[i - 2]) return nums[i - 2] + nums[i - 1] + nums[i]\n }\n return 0\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720cde", + "questionid": 531, + "title": "Subarrays with K Different Integers", + "slug": "subarrays-with-k-different-integers", + "description": "Given an integer array nums and an integer k, return the number of good subarrays of nums. A good array is an array where the number of different integers in that array is exactly k. A subarray is a contiguous part of an array. ", + "category": [ + "Array", + "Hash Table", + "Sliding Window", + "Counting" + ], + "complexity": "Hard", + "successrate": 53.3, + "totalsubmissions": 126886, + "totalaccepted": 67665, + "likes": 2888, + "dislikes": 40, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,2,1,2,3], k = 2", + "expected_output": "7", + "explanation": "Subarrays formed with exactly 2 different integers: [1,2], [2,1], [1,2], [2,3], [1,2,1], [2,1,2], [1,2,1,2]" + }, + { + "example_num": 2, + "expected_input": "nums = [1,2,1,3,4], k = 3", + "expected_output": "3", + "explanation": "Subarrays formed with exactly 3 different integers: [1,2,1,3], [2,1,3], [1,3,4]." + } + ], + "solution": "/**\n * @param {number[]} nums\n * @param {number} k\n * @return {number}\n */\nconst subarraysWithKDistinct = function(nums, k) {\n return mostK(k) - mostK(k - 1)\n \n function mostK(k) {\n const map = new Map(), n = nums.length\n let i = 0, j = 0, res = 0\n for(; j < n; j++) {\n const e = nums[j]\n map.set(e, (map.get(e) || 0) + 1)\n while(map.size > k) {\n const tmp = nums[i]\n map.set(tmp, map.get(tmp) - 1)\n if(map.get(tmp) === 0) map.delete(tmp)\n i++\n }\n res += j - i + 1\n }\n \n \n return res\n }\n};\n\n// another\n\n/**\n * @param {number[]} nums\n * @param {number} k\n * @return {number}\n */\nconst subarraysWithKDistinct = function(nums, k) {\n return mostK(k) - mostK(k - 1)\n function mostK(limit) {\n const map = new Map()\n let i = 0, j = 0, res = 0\n const n = nums.length\n for(; j< n; j++) {\n const e = nums[j]\n map.set(e, (map.get(e) || 0) + 1)\n while(map.size > limit) {\n const tmp = nums[i]\n map.set(tmp, (map.get(tmp) || 0) - 1)\n if(map.get(tmp) === 0) map.delete(tmp)\n i++\n }\n res += j - i + 1\n }\n \n return res\n }\n};\n\n// another\n\n/**\n * @param {number[]} A\n * @param {number} K\n * @return {number}\n */\nconst subarraysWithKDistinct = function(A, K) {\n let res = 0\n let prefix = 0\n const m = new Array(A.length + 1).fill(0)\n for (let i = 0, j = 0, cnt = 0, len = A.length; i < len; i++) {\n if (m[A[i]]++ === 0) cnt++\n if (cnt > K) {\n m[A[j++]]--\n cnt--\n prefix = 0\n }\n while (m[A[j]] > 1) {\n prefix++\n m[A[j++]]--\n }\n if (cnt === K) res += prefix + 1\n }\n return res\n}\n\n// another\n\n/**\n * @param {number[]} A\n * @param {number} K\n * @return {number}\n */\nconst subarraysWithKDistinct = function (A, K) {\n return mostK(K) - mostK(K - 1)\n function mostK(num) {\n const m = {}, len = A.length\n let i = 0, j = 0, res = 0\n for(j = 0; j < len; j++) {\n if(!m[A[j]]) m[A[j]] = 0, num--\n m[A[j]]++\n while(num < 0) {\n m[A[i]]--\n if(!m[A[i]]) num++\n i++\n }\n res += j - i + 1\n }\n return res\n }\n}\n\n// another\n\nconst subarraysWithKDistinct = function (nums, k) {\n const n = nums.length\n const atMost = (k) => {\n const freq = new Array(n + 1).fill(0)\n let l = 0,\n r = 0\n let res = 0\n let cnt = 0\n while (r < n) {\n if (freq[nums[r]] === 0) {\n cnt++\n }\n freq[nums[r]]++\n while (cnt > k) {\n freq[nums[l]]--\n if (freq[nums[l]] === 0) {\n cnt--\n }\n l++\n }\n res += r - l + 1\n r++\n }\n return res\n }\n return atMost(k) - atMost(k - 1)\n}\n\n\n" + }, + { + "_id": "66f925ddfdfb8e1665720cdf", + "questionid": 532, + "title": "Cousins in Binary Tree", + "slug": "cousins-in-binary-tree", + "description": "Given the root of a binary tree with unique values and the values of two different nodes of the tree x and y, return true if the nodes corresponding to the values x and y in the tree are cousins, or false otherwise. Two nodes of a binary tree are cousins if they have the same depth with different parents. Note that in a binary tree, the root node is at the depth 0, and children of each depth k node are at the depth k + 1. ", + "category": [ + "Tree", + "Depth-First Search", + "Breadth-First Search", + "Binary Tree" + ], + "complexity": "Easy", + "successrate": 53.8, + "totalsubmissions": 380002, + "totalaccepted": 204495, + "likes": 2682, + "dislikes": 138, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [1,2,3,4], x = 4, y = 3", + "expected_output": "false", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "root = [1,2,3,null,4,null,5], x = 5, y = 4", + "expected_output": "true", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "root = [1,2,3,null,4], x = 2, y = 3", + "expected_output": "false", + "explanation": "" + } + ], + "solution": null + }, + { + "_id": "66f925ddfdfb8e1665720ce1", + "questionid": 534, + "title": "Number of Squareful Arrays", + "slug": "number-of-squareful-arrays", + "description": "An array is squareful if the sum of every pair of adjacent elements is a perfect square. Given an integer array nums, return the number of permutations of nums that are squareful. Two permutations perm1 and perm2 are different if there is some index i such that perm1[i] != perm2[i]. ", + "category": [ + "Array", + "Math", + "Dynamic Programming", + "Backtracking", + "Bit Manipulation", + "Bitmask" + ], + "complexity": "Hard", + "successrate": 49.1, + "totalsubmissions": 51178, + "totalaccepted": 25134, + "likes": 657, + "dislikes": 27, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,17,8]", + "expected_output": "2", + "explanation": "[1,8,17] and [17,8,1] are the valid permutations." + }, + { + "example_num": 2, + "expected_input": "nums = [2,2,2]", + "expected_output": "1", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} A\n * @return {number}\n */\n\nconst numSquarefulPerms = function (A) {\n const cntMap = {}\n const squareMap = {}\n let cnt = 0\n for (let num of A) {\n if (!cntMap.hasOwnProperty(num)) {\n cntMap[num] = 1\n squareMap[num] = new Set()\n } else {\n cntMap[num] = cntMap[num] + 1\n }\n }\n\n for (let num1 of Object.keys(cntMap)) {\n for (let num2 of Object.keys(cntMap)) {\n let c = Math.sqrt(+num1 + +num2)\n if (c === Math.floor(c)) {\n squareMap[num1].add(+num2)\n squareMap[num2].add(+num1)\n }\n }\n }\n for (let num of Object.keys(cntMap)) {\n countPerm(num, A.length - 1)\n }\n return cnt\n function countPerm(num, left) {\n cntMap[num] = cntMap[num] - 1\n if (left === 0) {\n cnt++\n } else {\n for (let next of squareMap[num]) {\n if (cntMap[next] !== 0) {\n countPerm(next, left - 1)\n }\n }\n }\n cntMap[num] = cntMap[num] + 1\n }\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720ce4", + "questionid": 537, + "title": "Grid Illumination", + "slug": "grid-illumination", + "description": "There is a 2D grid of size n x n where each cell of this grid has a lamp that is initially turned off. You are given a 2D array of lamp positions lamps, where lamps[i] = [rowi, coli] indicates that the lamp at grid[rowi][coli] is turned on. Even if the same lamp is listed more than once, it is turned on. When a lamp is turned on, it illuminates its cell and all other cells in the same row, column, or diagonal. You are also given another 2D array queries, where queries[j] = [rowj, colj]. For the jth query, determine whether grid[rowj][colj] is illuminated or not. After answering the jth query, turn off the lamp at grid[rowj][colj] and its 8 adjacent lamps if they exist. A lamp is adjacent if its cell shares either a side or corner with grid[rowj][colj]. Return an array of integers ans, where ans[j] should be 1 if the cell in the jth query was illuminated, or 0 if the lamp was not. ", + "category": [ + "Array", + "Hash Table" + ], + "complexity": "Hard", + "successrate": 36.2, + "totalsubmissions": 41358, + "totalaccepted": 14957, + "likes": 390, + "dislikes": 104, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 5, lamps = [[0,0],[4,4]], queries = [[1,1],[1,0]]", + "expected_output": "[1,0]", + "explanation": "We have the initial grid with all lamps turned off. In the above picture we see the grid after turning on the lamp at grid[0][0] then turning on the lamp at grid[4][4].\nThe 0th query asks if the lamp at grid[1][1] is illuminated or not (the blue square). It is illuminated, so set ans[0] = 1. Then, we turn off all lamps in the red square.\n\"\"\nThe 1st query asks if the lamp at grid[1][0] is illuminated or not (the blue square). It is not illuminated, so set ans[1] = 0. Then, we turn off all lamps in the red rectangle.\n\"\"" + }, + { + "example_num": 2, + "expected_input": "n = 5, lamps = [[0,0],[4,4]], queries = [[1,1],[1,1]]", + "expected_output": "[1,1]", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "n = 5, lamps = [[0,0],[0,4]], queries = [[0,4],[0,1],[1,4]]", + "expected_output": "[1,1,0]", + "explanation": "" + } + ], + "solution": "/**\n * @param {number} N\n * @param {number[][]} lamps\n * @param {number[][]} queries\n * @return {number[]}\n */\nconst gridIllumination = function (N, lamps, queries) {\n const rowMap = new Map()\n const colMap = new Map()\n const hillMap = new Map()\n const daleMap = new Map()\n const litMap = new Map()\n const direction = [\n [0, 0],\n [0, 1],\n [1, 0],\n [-1, 0],\n [0, -1],\n [-1, -1],\n [1, 1],\n ]\n //map what areas are lit\n for (let [x, y] of lamps) {\n insert(rowMap, x)\n insert(colMap, y)\n insert(hillMap, x + y)\n insert(daleMap, x - y)\n litMap.set(N * x + y, true)\n }\n const result = new Array(queries.length).fill(0)\n let count = 0\n for (let [x, y] of queries) {\n if (\n rowMap.get(x) > 0 ||\n colMap.get(y) > 0 ||\n hillMap.get(x + y) > 0 ||\n daleMap.get(x - y) > 0\n ) {\n result[count] = 1\n }\n for (let [i, j] of direction) {\n let newX = x + i\n let newY = y + j\n if (litMap.has(N * newX + newY)) {\n decrease(rowMap, newX)\n decrease(colMap, newY)\n decrease(hillMap, newX + newY)\n decrease(daleMap, N * newX + newY)\n litMap.delete(N * newX + newY)\n }\n }\n count++\n }\n return result\n}\nconst insert = (map, value) => {\n if (map.has(value)) {\n map.set(value, map.get(value) + 1)\n } else {\n map.set(value, 1)\n }\n}\nconst decrease = (map, value) => {\n if (map.has(value)) {\n map.set(value, map.get(value) - 1)\n }\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720ceb", + "questionid": 544, + "title": "Pairs of Songs With Total Durations Divisible by 60", + "slug": "pairs-of-songs-with-total-durations-divisible-by-60", + "description": "You are given a list of songs where the ith song has a duration of time[i] seconds. Return the number of pairs of songs for which their total duration in seconds is divisible by 60. Formally, we want the number of indices i, j such that i < j with (time[i] + time[j]) % 60 == 0. ", + "category": [ + "Array", + "Hash Table", + "Counting" + ], + "complexity": "Medium", + "successrate": 53.7, + "totalsubmissions": 352306, + "totalaccepted": 189080, + "likes": 3064, + "dislikes": 118, + "hints": "We only need to consider each song length modulo 60. We can count the number of songs with (length % 60) equal to r, and store that in an array of size 60.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "time = [30,20,150,100,40]", + "expected_output": "3", + "explanation": "Three pairs have a total duration divisible by 60:\n(time[0] = 30, time[2] = 150): total duration 180\n(time[1] = 20, time[3] = 100): total duration 120\n(time[1] = 20, time[4] = 40): total duration 60" + }, + { + "example_num": 2, + "expected_input": "time = [60,60,60]", + "expected_output": "3", + "explanation": "All three pairs have a total duration of 120, which is divisible by 60." + } + ], + "solution": "/**\n * @param {number[]} time\n * @return {number}\n */\nconst numPairsDivisibleBy60 = function(time) {\n const count = new Map();\n let n = 0;\n for (let t of time) {\n // two sum like method\n let d = (60 - t % 60) % 60;\n if (count.has(d)) { n += count.get(d); }\n count.set(t % 60, 1 + (count.get(t % 60) || 0));\n }\n return n;\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720ced", + "questionid": 546, + "title": "Numbers With Repeated Digits", + "slug": "numbers-with-repeated-digits", + "description": "Given an integer n, return the number of positive integers in the range [1, n] that have at least one repeated digit. ", + "category": [ + "Math", + "Dynamic Programming" + ], + "complexity": "Hard", + "successrate": 38.5, + "totalsubmissions": 23326, + "totalaccepted": 8983, + "likes": 393, + "dislikes": 62, + "hints": "How many numbers with no duplicate digits? How many numbers with K digits and no duplicates? How many numbers with same length as N? How many numbers with same prefix as N?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 20", + "expected_output": "1", + "explanation": "The only positive number (<= 20) with at least 1 repeated digit is 11." + }, + { + "example_num": 2, + "expected_input": "n = 100", + "expected_output": "10", + "explanation": "The positive numbers (<= 100) with atleast 1 repeated digit are 11, 22, 33, 44, 55, 66, 77, 88, 99, and 100." + }, + { + "example_num": 3, + "expected_input": "n = 1000", + "expected_output": "262", + "explanation": "" + } + ], + "solution": "/**\n * @param {number} n\n * @return {number}\n */\nfunction numDupDigitsAtMostN(n) {\n let numNoDupDigits = 0; // the number of positive integers less than or equal to n with no repeated digits\n\n let lst = Array.from(String(n), Number);\n let n_digits = lst.length;\n\n // if n = 8765, lst = [8,7,6,5],\n // the number without repeated digit can the the following format:\n // XXX\n // XX\n // X\n for (let i = 1; i < n_digits; i++) {\n // the number of i digits without repeated digit\n // the leading digit cannot be 0\n numNoDupDigits += 9 * perm(9, i - 1);\n }\n\n // and\n // 1XXX ~ 7XXX\n // 80XX ~ 86XX\n // 870X ~ 875X\n // 8760 ~ 8764\n let seen = new Set();\n for (let i = 0; i < lst.length; i++) {\n let x = lst[i];\n for (let y = (i === 0 ? 1 : 0); y < x; y++) {\n if (!seen.has(y)) {\n // the leading digit used - y\n // for the remaining positions we cannot use digits in set seen and y\n numNoDupDigits += perm(9 - i, n_digits - i - 1);\n }\n }\n if (seen.has(x)) {\n break;\n }\n seen.add(x);\n }\n\n // and\n // 8765\n if (n_digits === new Set(lst).size) {\n numNoDupDigits += 1;\n }\n\n return n - numNoDupDigits;\n}\n\nfunction perm(m, n) {\n let res = 1\n for(let i = 0; i < n; i++) {\n res *= m\n m--\n }\n\n return res\n}\n\n// another\n\n\n/**\n * @param {number} n\n * @return {number}\n */\nvar numDupDigitsAtMostN = function(n) {\n const digits = [], {floor} = Math\n let tmp = n + 1\n while(tmp) {\n digits.push(tmp % 10)\n tmp = floor(tmp / 10)\n }\n let res = 0\n const len = digits.length\n let cur = 9\n for(let i = 0; i < len - 1; i++) {\n res += cur\n cur *= (9 - i)\n }\n cur = floor(cur / 9)\n const seen = Array(10).fill(false)\n for(let i = 0; i < len; i++) {\n const d = digits[len - i - 1]\n for(let j = (i === 0 ? 1 : 0); j < d; j++) {\n if(!seen[j]) res += cur\n }\n cur = floor(cur / (9 - i))\n if(seen[d]) break\n seen[d] = true\n }\n\n return n - res\n};\n\n// another\n\n/**\n * @param {number} n\n * @return {number}\n */\nvar numDupDigitsAtMostN = function(n) {\n return n - helper(n)\n function helper(num) {\n let res = 0\n const s = `${num}`\n const slen = s.length\n for(let len = 1; len < slen; len++) {\n res += perm(10, len) - perm(9, len - 1)\n }\n const visited = Array(10).fill(null)\n dfs(s, 0, visited)\n \n return res\n function dfs(s, i, visited) {\n const n = s.length\n if(i === n) {\n res++\n return\n }\n for(let d = 0; d <= 9; d++) {\n if(d === 0 && i === 0) continue\n if(visited[d]) continue\n if(d < +s[i]) {\n res += perm(10 - i - 1, n - i - 1)\n } else if(d === +s[i]) {\n visited[d] = 1\n dfs(s, i + 1, visited)\n visited[d] = 0\n }\n }\n }\n }\n\n function perm(m, n) {\n if(n === 0) return 1\n let res = 1\n for(let i = 0; i < n; i++) {\n res *= m - i\n }\n return res\n }\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720cf1", + "questionid": 550, + "title": "Binary Prefix Divisible By 5", + "slug": "binary-prefix-divisible-by-5", + "description": "You are given a binary array nums (0-indexed). We define xi as the number whose binary representation is the subarray nums[0..i] (from most-significant-bit to least-significant-bit). Return an array of booleans answer where answer[i] is true if xi is divisible by 5. ", + "category": [ + "Array" + ], + "complexity": "Easy", + "successrate": 47.5, + "totalsubmissions": 80946, + "totalaccepted": 38484, + "likes": 514, + "dislikes": 137, + "hints": "If X is the first i digits of the array as a binary number, then 2X + A[i] is the first i+1 digits.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [0,1,1]", + "expected_output": "[true,false,false]", + "explanation": "The input numbers in binary are 0, 01, 011; which are 0, 1, and 3 in base-10.\nOnly the first number is divisible by 5, so answer[0] is true." + }, + { + "example_num": 2, + "expected_input": "nums = [1,1,1]", + "expected_output": "[false,false,false]", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} A\n * @return {boolean[]}\n */\nconst prefixesDivBy5 = function(A) {\n const res = []\n let pre = 0\n const len = A.length\n for(let i = 0; i < len; i++) {\n pre = (pre % 100) * 2 + A[i]\n res.push(pre % 5 === 0 ? true : false)\n }\n return res\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720cf2", + "questionid": 551, + "title": "Next Greater Node In Linked List", + "slug": "next-greater-node-in-linked-list", + "description": "You are given the head of a linked list with n nodes. For each node in the list, find the value of the next greater node. That is, for each node, find the value of the first node that is next to it and has a strictly larger value than it. Return an integer array answer where answer[i] is the value of the next greater node of the ith node (1-indexed). If the ith node does not have a next greater node, set answer[i] = 0. ", + "category": [ + "Array", + "Linked List", + "Stack", + "Monotonic Stack" + ], + "complexity": "Medium", + "successrate": 59.7, + "totalsubmissions": 168238, + "totalaccepted": 100376, + "likes": 2114, + "dislikes": 96, + "hints": "We can use a stack that stores nodes in monotone decreasing order of value. When we see a node_j with a larger value, every node_i in the stack has next_larger(node_i) = node_j .", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "head = [2,1,5]", + "expected_output": "[5,5,0]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "head = [2,7,4,3,5]", + "expected_output": "[7,0,5,5,0]", + "explanation": "" + } + ], + "solution": "/**\n * Definition for singly-linked list.\n * function ListNode(val) {\n * this.val = val;\n * this.next = null;\n * }\n */\n/**\n * @param {ListNode} head\n * @return {number[]}\n */\nconst nextLargerNodes = function(head) {\n const A = []\n while (head != null) A.push(head.val), (head = head.next)\n const res = new Array(A.length).fill(0)\n const stack = []\n for (let i = 0; i < A.length; i++) {\n while (stack.length && A[stack[stack.length - 1]] < A[i])\n res[stack.pop()] = A[i]\n stack.push(i)\n }\n return res\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720cf4", + "questionid": 553, + "title": "Sum of Root To Leaf Binary Numbers", + "slug": "sum-of-root-to-leaf-binary-numbers", + "description": "You are given the root of a binary tree where each node has a value 0 or 1. Each root-to-leaf path represents a binary number starting with the most significant bit. For all leaves in the tree, consider the numbers represented by the path from the root to that leaf. Return the sum of these numbers. The test cases are generated so that the answer fits in a 32-bits integer. ", + "category": [ + "Tree", + "Depth-First Search", + "Binary Tree" + ], + "complexity": "Easy", + "successrate": 73.9, + "totalsubmissions": 215956, + "totalaccepted": 159601, + "likes": 2476, + "dislikes": 149, + "hints": "Find each path, then transform that path to an integer in base 10.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [1,0,1,0,1,0,1]", + "expected_output": "22\nExplanation: (100) + (101) + (110) + (111) = 4 + 5 + 6 + 7 = 22", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "root = [0]", + "expected_output": "0", + "explanation": "" + } + ], + "solution": "/**\n * Definition for a binary tree node.\n * function TreeNode(val) {\n * this.val = val;\n * this.left = this.right = null;\n * }\n */\n/**\n * @param {TreeNode} root\n * @return {number}\n */\nconst sumRootToLeaf = function(root) {\n if(root == null) return 0\n const res = []\n dfs(root, 0, res)\n const mod = Math.pow(10, 9) + 7\n return res.reduce((ac, el) => (ac + el) % mod ,0) \n};\n\nfunction dfs(node, val, res) {\n const mod = Math.pow(10, 9) + 7\n if(node == null) return\n val = (val * 2 + node.val) % mod\n if(node.left === null && node.right === null) {\n res.push(val)\n }\n dfs(node.left, val, res)\n dfs(node.right, val, res)\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720cf9", + "questionid": 558, + "title": "Matrix Cells in Distance Order", + "slug": "matrix-cells-in-distance-order", + "description": "You are given four integers row, cols, rCenter, and cCenter. There is a rows x cols matrix and you are on the cell with the coordinates (rCenter, cCenter). Return the coordinates of all cells in the matrix, sorted by their distance from (rCenter, cCenter) from the smallest distance to the largest distance. You may return the answer in any order that satisfies this condition. The distance between two cells (r1, c1) and (r2, c2) is |r1 - r2| + |c1 - c2|. ", + "category": [ + "Array", + "Math", + "Geometry", + "Sorting", + "Matrix" + ], + "complexity": "Easy", + "successrate": 69.1, + "totalsubmissions": 60168, + "totalaccepted": 41554, + "likes": 481, + "dislikes": 218, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "rows = 1, cols = 2, rCenter = 0, cCenter = 0", + "expected_output": "[[0,0],[0,1]]", + "explanation": "The distances from (0, 0) to other cells are: [0,1]" + }, + { + "example_num": 2, + "expected_input": "rows = 2, cols = 2, rCenter = 0, cCenter = 1", + "expected_output": "[[0,1],[0,0],[1,1],[1,0]]", + "explanation": "The distances from (0, 1) to other cells are: [0,1,1,2]\nThe answer [[0,1],[1,1],[0,0],[1,0]] would also be accepted as correct." + }, + { + "example_num": 3, + "expected_input": "rows = 2, cols = 3, rCenter = 1, cCenter = 2", + "expected_output": "[[1,2],[0,2],[1,1],[0,1],[1,0],[0,0]]", + "explanation": "The distances from (1, 2) to other cells are: [0,1,1,2,2,3]\nThere are other answers that would also be accepted as correct, such as [[1,2],[1,1],[0,2],[1,0],[0,1],[0,0]]." + } + ], + "solution": "/**\n * @param {number} R\n * @param {number} C\n * @param {number} r0\n * @param {number} c0\n * @return {number[][]}\n */\nconst allCellsDistOrder = function(R, C, r0, c0) {\n const matrix = Array.from({ length: R }, () => new Array(C))\n const arr = []\n for (let i = 0; i < R; i++) {\n for (let j = 0; j < C; j++) {\n arr.push([i, j])\n }\n }\n\n return arr.sort(\n (a, b) =>\n Math.abs(a[0] - r0) +\n Math.abs(a[1] - c0) -\n (Math.abs(b[0] - r0) + Math.abs(b[1] - c0))\n )\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720cfc", + "questionid": 561, + "title": "Coloring A Border", + "slug": "coloring-a-border", + "description": "You are given an m x n integer matrix grid, and three integers row, col, and color. Each value in the grid represents the color of the grid square at that location. Two squares belong to the same connected component if they have the same color and are next to each other in any of the 4 directions. The border of a connected component is all the squares in the connected component that are either 4-directionally adjacent to a square not in the component, or on the boundary of the grid (the first or last row or column). You should color the border of the connected component that contains the square grid[row][col] with color. Return the final grid. ", + "category": [ + "Array", + "Depth-First Search", + "Breadth-First Search", + "Matrix" + ], + "complexity": "Medium", + "successrate": 48.4, + "totalsubmissions": 45975, + "totalaccepted": 22235, + "likes": 400, + "dislikes": 597, + "hints": "Use a DFS to find every square in the component. Then for each square, color it if it has a neighbor that is outside the grid or a different color.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "grid = [[1,1],[1,2]], row = 0, col = 0, color = 3", + "expected_output": "[[3,3],[3,2]]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "grid = [[1,2,2],[2,3,2]], row = 0, col = 1, color = 3", + "expected_output": "[[1,3,3],[2,3,3]]", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "grid = [[1,1,1],[1,1,1],[1,1,1]], row = 1, col = 1, color = 2", + "expected_output": "[[2,2,2],[2,1,2],[2,2,2]]", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[][]} grid\n * @param {number} r0\n * @param {number} c0\n * @param {number} color\n * @return {number[][]}\n */\nconst colorBorder = function(grid, r0, c0, color) {\n const dirs = [[-1,0], [1,0], [0,1], [0,-1]]\n const c = grid[r0][c0]\n const rows = grid.length\n const cols = grid[0].length\n const visited = Array.from({length: rows}, () => new Array(cols).fill(0))\n dfs(r0, c0, c, rows, cols, visited, grid, dirs)\n for(let i = 0; i < rows; i++) {\n for(let j = 0; j < cols; j++) {\n if(visited[i][j] === -1) {\n if(i === 0 || j === 0 || i === rows - 1 || j === cols - 1) {\n visited[i][j] = -2\n } else {\n for(let dir of dirs) {\n if(visited[i + dir[0]][j + dir[1]] === 0) {\n visited[i][j] = -2\n break\n }\n } \n }\n }\n }\n }\n for(let i = 0; i < rows; i++) {\n for(let j = 0; j < cols; j++) {\n if(visited[i][j] === -2) grid[i][j] = color\n }\n }\n \n return grid\n};\n\nfunction dfs(row, col, target, rows, cols, visited, grid, dirs) {\n if(row >= rows || col >= cols || row < 0 || col < 0 || grid[row][col] !== target || visited[row][col] === -1) {\n return \n }\n visited[row][col] = -1\n for(let dir of dirs) {\n dfs(row + dir[0], col+dir[1], target, rows, cols, visited, grid, dirs)\n }\n \n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720cfd", + "questionid": 562, + "title": "Escape a Large Maze", + "slug": "escape-a-large-maze", + "description": "There is a 1 million by 1 million grid on an XY-plane, and the coordinates of each grid square are (x, y). We start at the source = [sx, sy] square and want to reach the target = [tx, ty] square. There is also an array of blocked squares, where each blocked[i] = [xi, yi] represents a blocked square with coordinates (xi, yi). Each move, we can walk one square north, east, south, or west if the square is not in the array of blocked squares. We are also not allowed to walk outside of the grid. Return true if and only if it is possible to reach the target square from the source square through a sequence of valid moves. ", + "category": [ + "Array", + "Hash Table", + "Depth-First Search", + "Breadth-First Search" + ], + "complexity": "Hard", + "successrate": 34.4, + "totalsubmissions": 45503, + "totalaccepted": 15635, + "likes": 449, + "dislikes": 139, + "hints": "If we become stuck, there's either a loop around the source or around the target. If there is a loop around say, the source, what is the maximum number of squares it can have?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "blocked = [[0,1],[1,0]], source = [0,0], target = [0,2]", + "expected_output": "false", + "explanation": "The target square is inaccessible starting from the source square because we cannot move.\nWe cannot move north or east because those squares are blocked.\nWe cannot move south or west because we cannot go outside of the grid." + }, + { + "example_num": 2, + "expected_input": "blocked = [], source = [0,0], target = [999999,999999]", + "expected_output": "true", + "explanation": "Because there are no blocked cells, it is possible to reach the target square." + } + ], + "solution": "/**\n * @param {number[][]} blocked\n * @param {number[]} source\n * @param {number[]} target\n * @return {boolean}\n */\nconst isEscapePossible = function(blocked, source, target) {\n const blockedSet = new Set()\n for (let el of blocked) {\n let key = el[0] + \",\" + el[1]\n blockedSet.add(key)\n }\n return canVisit(blockedSet, source, target) && canVisit(blockedSet, target, source)\n}\n\nfunction canVisit(blocked, start, end) {\n const visited = new Set()\n return dfs(blocked, start[0], start[1], end[0], end[1], visited)\n}\nfunction dfs(blocked, i, j, m, n, visited) {\n visited.add(i + \",\" + j)\n const dirs = [[i - 1, j], [i + 1, j], [i, j + 1], [i, j - 1]]\n if ((i == m && j == n) || visited.size >= 20000) {\n return true\n }\n for (let dir of dirs) {\n let nextKey = dir[0] + \",\" + dir[1]\n if (\n dir[0] >= 0 &&\n dir[1] >= 0 &&\n dir[0] < 1e6 &&\n dir[1] < 1e6 &&\n !blocked.has(nextKey) &&\n !visited.has(nextKey)\n ) {\n if (dfs(blocked, dir[0], dir[1], m, n, visited)) {\n return true\n }\n }\n }\n return false\n}\n\n// another\n\n/**\n * @param {number[][]} blocked\n * @param {number[]} source\n * @param {number[]} target\n * @return {boolean}\n */\nconst isEscapePossible = function(blocked, source, target) {\n if (blocked.length < 2) {\n return true\n }\n// if (blocked[0][0] == 100025) {\n// return false\n// }\n const blockSet = new Set(\n blocked.map(el => {\n return el[0] + \",\" + el[1]\n })\n )\n let targetR, targetC, curR, curC\n ;[targetR, targetC] = target\n let visited = new Set([])\n let DIRS = [[0, 1], [-1, 0], [0, -1], [1, 0]],\n queue = [source]\n const inBound = (r, c) => {\n return r >= 0 && c >= 0 && r < 1000000 && c < 1000000\n }\n let count = 0\n while (queue.length > 0) {\n count++\n ;[curR, curC] = queue.shift()\n\n if (count > 20000) {\n return true\n }\n for (let dir of DIRS) {\n const newR = curR + dir[0],\n newC = curC + dir[1]\n if (\n !inBound(newR, newC) ||\n blockSet.has(newR + \",\" + newC) ||\n visited.has(newR + \",\" + newC)\n ) {\n continue\n }\n\n if (newR == targetR && newC == targetC) {\n return true\n }\n visited.add(newR + \",\" + newC)\n queue.push([newR, newC])\n }\n }\n return false\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720d00", + "questionid": 565, + "title": "Valid Boomerang", + "slug": "valid-boomerang", + "description": "Given an array points where points[i] = [xi, yi] represents a point on the X-Y plane, return true if these points are a boomerang. A boomerang is a set of three points that are all distinct and not in a straight line. ", + "category": [ + "Math", + "Geometry" + ], + "complexity": "Easy", + "successrate": 37.4, + "totalsubmissions": 82488, + "totalaccepted": 30881, + "likes": 223, + "dislikes": 348, + "hints": "3 points form a boomerang if and only if the triangle formed from them has non-zero area.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "points = [[1,1],[2,3],[3,2]]", + "expected_output": "true", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "points = [[1,1],[2,2],[3,3]]", + "expected_output": "false", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[][]} points\n * @return {boolean}\n */\nconst isBoomerang = function(points) {\n if(angle(points[0], points[1], points[2]) &&\n angle(points[1], points[2], points[0]) &&\n angle(points[1], points[0], points[2]) ) return false\n return true\n};\n\n// distinct or in a line\nfunction angle(p1, p2, p3) {\n if((p1[0] === p2[0] && p1[1] === p2[1]) ||\n (p2[0] === p3[0] && p2[1] === p3[1]) ||\n (p1[0] === p3[0] && p1[1] === p3[1]) ) return true\n \n return collinear(p1[0], p1[1], p2[0], p2[1], p3[0], p3[1])\n}\nfunction collinear(x1, y1, x2, y2, x3, y3) { \n return (y3 - y2) * (x2 - x1) === (y2 - y1) * (x3 - x2)\n} \n" + }, + { + "_id": "66f925ddfdfb8e1665720d02", + "questionid": 567, + "title": "Flower Planting With No Adjacent", + "slug": "flower-planting-with-no-adjacent", + "description": "You have n gardens, labeled from 1 to n, and an array paths where paths[i] = [xi, yi] describes a bidirectional path between garden xi to garden yi. In each garden, you want to plant one of 4 types of flowers. All gardens have at most 3 paths coming into or leaving it. Your task is to choose a flower type for each garden such that, for any two gardens connected by a path, they have different types of flowers. Return any such a choice as an array answer, where answer[i] is the type of flower planted in the (i+1)th garden. The flower types are denoted 1, 2, 3, or 4. It is guaranteed an answer exists. ", + "category": [ + "Depth-First Search", + "Breadth-First Search", + "Graph" + ], + "complexity": "Medium", + "successrate": 49.8, + "totalsubmissions": 109234, + "totalaccepted": 54424, + "likes": 822, + "dislikes": 650, + "hints": "Since each garden is connected to at most 3 gardens, there's always an available color for each garden. For example, if one garden is next to gardens with colors 1, 3, 4, then color #2 is available.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 3, paths = [[1,2],[2,3],[3,1]]", + "expected_output": "[1,2,3]", + "explanation": "Gardens 1 and 2 have different types.\nGardens 2 and 3 have different types.\nGardens 3 and 1 have different types.\nHence, [1,2,3] is a valid answer. Other valid answers include [1,2,4], [1,4,2], and [3,2,1]." + }, + { + "example_num": 2, + "expected_input": "n = 4, paths = [[1,2],[3,4]]", + "expected_output": "[1,2,1,2]", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "n = 4, paths = [[1,2],[2,3],[3,4],[4,1],[1,3],[2,4]]", + "expected_output": "[1,2,3,4]", + "explanation": "" + } + ], + "solution": "/**\n * @param {number} N\n * @param {number[][]} paths\n * @return {number[]}\n */\nconst gardenNoAdj = function(N, paths) {\n const map = {};\n for (let i = 0; i < N; i++) {\n map[i] = [];\n }\n for (let path of paths) {\n let l = path[0] - 1;\n let r = path[1] - 1;\n map[l].push(r);\n map[r].push(l);\n }\n const result = new Array(N).fill(-1);\n for (let i = 0; i < N; i++) {\n let colors = new Array(4).fill(false);\n for (let neighbor of map[i]) {\n if (result[neighbor] !== -1) {\n colors[result[neighbor]] = true;\n }\n }\n for (let j = 0; j < colors.length; j++) {\n if (!colors[j]) {\n result[i] = j;\n break;\n }\n }\n }\n return result.map(i => ++i);\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720d03", + "questionid": 568, + "title": "Partition Array for Maximum Sum", + "slug": "partition-array-for-maximum-sum", + "description": "Given an integer array arr, partition the array into (contiguous) subarrays of length at most k. After partitioning, each subarray has their values changed to become the maximum value of that subarray. Return the largest sum of the given array after partitioning. Test cases are generated so that the answer fits in a 32-bit integer. ", + "category": [ + "Array", + "Dynamic Programming" + ], + "complexity": "Medium", + "successrate": 70.3, + "totalsubmissions": 67101, + "totalaccepted": 47141, + "likes": 2083, + "dislikes": 196, + "hints": "Think dynamic programming: dp[i] will be the answer for array A[0], ..., A[i-1]. For j = 1 .. k that keeps everything in bounds, dp[i] is the maximum of dp[i-j] + max(A[i-1], ..., A[i-j]) * j .", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "arr = [1,15,7,9,2,5,10], k = 3", + "expected_output": "84", + "explanation": "arr becomes [15,15,15,9,10,10,10]" + }, + { + "example_num": 2, + "expected_input": "arr = [1,4,1,5,7,3,6,1,9,9,3], k = 4", + "expected_output": "83", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "arr = [1], k = 1", + "expected_output": "1", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} A\n * @param {number} K\n * @return {number}\n */\nconst maxSumAfterPartitioning = function(A, K) {\n const N = A.length\n const dp = new Array(N).fill(0);\n for (let i = 0; i < N; ++i) {\n let curMax = 0;\n for (let j = 1; j <= K && i - j + 1 >= 0; j++) {\n curMax = Math.max(curMax, A[i - j + 1]);\n dp[i] = Math.max(dp[i], (i >= j ? dp[i - j] : 0) + curMax * j);\n }\n }\n return dp[N - 1];\n};\n\n// another\n\n/**\n * @param {number[]} arr\n * @param {number} k\n * @return {number}\n */\nconst maxSumAfterPartitioning = function(arr, k) {\n const n = arr.length, memo = Array(n + 1)\n memo[0] = 0\n return dp(n)\n \n function dp(i) {\n if(i === 0) return 0\n if(memo[i] != null) return memo[i]\n \n let sum = 0, max = 0, res = 0\n for(let j = i; j > 0 && i - j < k; j--) {\n max = Math.max(max, arr[j - 1])\n sum = (i - j + 1) * max\n res = Math.max(res, dp(j - 1) + sum)\n }\n return memo[i] = res\n }\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720d04", + "questionid": 569, + "title": "Remove All Adjacent Duplicates In String", + "slug": "remove-all-adjacent-duplicates-in-string", + "description": "You are given a string s consisting of lowercase English letters. A duplicate removal consists of choosing two adjacent and equal letters and removing them. We repeatedly make duplicate removals on s until we no longer can. Return the final string after all such duplicate removals have been made. It can be proven that the answer is unique. ", + "category": [ + "String", + "Stack" + ], + "complexity": "Easy", + "successrate": 71, + "totalsubmissions": 390692, + "totalaccepted": 277370, + "likes": 3093, + "dislikes": 152, + "hints": "Use a stack to process everything greedily.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "abbaca"", + "expected_output": ""ca"", + "explanation": "For example, in "abbaca" we could remove "bb" since the letters are adjacent and equal, and this is the only possible move. The result of this move is that the string is "aaca", of which only "aa" is possible, so the final string is "ca"." + }, + { + "example_num": 2, + "expected_input": "s = "azxxzy"", + "expected_output": ""ay"", + "explanation": "" + } + ], + "solution": "/**\n * @param {string} S\n * @return {string}\n */\nconst removeDuplicates = function(S) {\n const queue = []\n for(let i = 0; i < S.length; i++) {\n if(queue.length > 0 && queue[queue.length - 1] === S[i]) {\n queue.pop()\n } else {\n queue.push(S[i])\n }\n }\n return queue.join('')\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720d08", + "questionid": 573, + "title": "Grumpy Bookstore Owner", + "slug": "grumpy-bookstore-owner", + "description": "There is a bookstore owner that has a store open for n minutes. Every minute, some number of customers enter the store. You are given an integer array customers of length n where customers[i] is the number of the customer that enters the store at the start of the ith minute and all those customers leave after the end of that minute. On some minutes, the bookstore owner is grumpy. You are given a binary array grumpy where grumpy[i] is 1 if the bookstore owner is grumpy during the ith minute, and is 0 otherwise. When the bookstore owner is grumpy, the customers of that minute are not satisfied, otherwise, they are satisfied. The bookstore owner knows a secret technique to keep themselves not grumpy for minutes consecutive minutes, but can only use it once. Return the maximum number of customers that can be satisfied throughout the day. ", + "category": [ + "Array", + "Sliding Window" + ], + "complexity": "Medium", + "successrate": 56.7, + "totalsubmissions": 92423, + "totalaccepted": 52409, + "likes": 1115, + "dislikes": 93, + "hints": "Say the store owner uses their power in minute 1 to X and we have some answer A. If they instead use their power from minute 2 to X+1, we only have to use data from minutes 1, 2, X and X+1 to update our answer A.", + "deleted": false, + "examples": [], + "solution": "/**\n * @param {number[]} customers\n * @param {number[]} grumpy\n * @param {number} X\n * @return {number}\n */\nconst maxSatisfied = function(customers, grumpy, X) {\n if (customers.length === 1) return customers[0]\n const totalSatisfiedCustomers = customers.reduce(\n (ac, el, idx) => ac + (grumpy[idx] === 0 ? el : 0),\n 0\n )\n const arr = customers.map((el, idx) => (grumpy[idx] === 1 ? el : 0))\n const acArr = []\n let ac = 0\n for (let i = 0, len = arr.length; i < len; i++) {\n acArr[i] = ac = ac + arr[i]\n }\n let max = 0\n for (let i = X - 1, len = grumpy.length; i < len; i++) {\n let tmp = i - X < 0 ? 0 : acArr[i - X]\n if (acArr[i] - tmp > max) max = acArr[i] - tmp\n }\n\n return totalSatisfiedCustomers + max\n}\n\n// another\n\n/**\n * @param {number[]} customers\n * @param {number[]} grumpy\n * @param {number} X\n * @return {number}\n */\nconst maxSatisfied = function (customers, grumpy, X) {\n let satisfied = 0,\n maxMakeSatisfied = 0\n for (let i = 0, winOfMakeSatisfied = 0; i < grumpy.length; ++i) {\n if (grumpy[i] === 0) {\n satisfied += customers[i]\n } else {\n winOfMakeSatisfied += customers[i]\n }\n if (i >= X) {\n winOfMakeSatisfied -= grumpy[i - X] * customers[i - X]\n }\n maxMakeSatisfied = Math.max(winOfMakeSatisfied, maxMakeSatisfied)\n }\n return satisfied + maxMakeSatisfied\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720d0b", + "questionid": 576, + "title": "Greatest Common Divisor of Strings", + "slug": "greatest-common-divisor-of-strings", + "description": "For two strings s and t, we say \"t divides s\" if and only if s = t + ... + t (i.e., t is concatenated with itself one or more times). Given two strings str1 and str2, return the largest string x such that x divides both str1 and str2. ", + "category": [ + "Math", + "String" + ], + "complexity": "Easy", + "successrate": 51.5, + "totalsubmissions": 138025, + "totalaccepted": 71079, + "likes": 1267, + "dislikes": 253, + "hints": "The greatest common divisor must be a prefix of each string, so we can try all prefixes.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "str1 = "ABCABC", str2 = "ABC"", + "expected_output": ""ABC"", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "str1 = "ABABAB", str2 = "ABAB"", + "expected_output": ""AB"", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "str1 = "LEET", str2 = "CODE"", + "expected_output": """", + "explanation": "" + } + ], + "solution": "/**\n * @param {string} str1\n * @param {string} str2\n * @return {string}\n */\nconst gcdOfStrings = function(str1, str2) {\n let res = \"\";\n\n if (str1[0] !== str2[0]) return res;\n if (str1[str1.length - 1] !== str2[str2.length - 1]) return res;\n let s = str1[0];\n let e = str1[str1.length - 1];\n\n let loopStr = str1.length > str2.length ? str2 : str1;\n for (let i = 1, len = loopStr.length; i < len; i++) {\n if (loopStr[i] !== e) continue;\n let tmp = loopStr.slice(0, i + 1);\n let ok1 = false;\n let ok2 = false;\n let t1 = \"\";\n let t2 = \"\";\n while (t1.length < str1.length) {\n t1 += tmp;\n if (t1 === str1) {\n ok1 = true;\n break;\n }\n }\n while (t2.length < str2.length) {\n t2 += tmp;\n if (t2 === str2) {\n ok2 = true;\n break;\n }\n }\n\n if (ok1 && ok2 && tmp.length > res.length) res = tmp;\n }\n\n return res;\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720cd3", + "questionid": 520, + "title": "Fibonacci Number", + "slug": "fibonacci-number", + "description": "The Fibonacci numbers, commonly denoted F(n) form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1. That is, Given n, calculate F(n). ", + "category": [ + "Math", + "Dynamic Programming", + "Recursion", + "Memoization" + ], + "complexity": "Easy", + "successrate": 68.2, + "totalsubmissions": 1075067, + "totalaccepted": 732697, + "likes": 3284, + "dislikes": 261, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 2", + "expected_output": "1", + "explanation": "F(2) = F(1) + F(0) = 1 + 0 = 1." + }, + { + "example_num": 2, + "expected_input": "n = 3", + "expected_output": "2", + "explanation": "F(3) = F(2) + F(1) = 1 + 1 = 2." + }, + { + "example_num": 3, + "expected_input": "n = 4", + "expected_output": "3", + "explanation": "F(4) = F(3) + F(2) = 2 + 1 = 3." + } + ], + "solution": "/**\n * @param {number} N\n * @return {number}\n */\nconst cache = {}\nconst fib = function(N) {\n if(cache[N]) return cache[N]\n if(N === 0) return 0\n if(N === 1) return 1\n let res = fib(N - 1) + fib(N - 2)\n cache[N] = res\n return res\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720cd8", + "questionid": 525, + "title": "Distribute Coins in Binary Tree", + "slug": "distribute-coins-in-binary-tree", + "description": "You are given the root of a binary tree with n nodes where each node in the tree has node.val coins. There are n coins in total throughout the whole tree. In one move, we may choose two adjacent nodes and move one coin from one node to another. A move may be from parent to child, or from child to parent. Return the minimum number of moves required to make every node have exactly one coin. ", + "category": [ + "Tree", + "Depth-First Search", + "Binary Tree" + ], + "complexity": "Medium", + "successrate": 71.5, + "totalsubmissions": 116380, + "totalaccepted": 83207, + "likes": 3561, + "dislikes": 119, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [3,0,0]", + "expected_output": "2\nExplanation: From the root of the tree, we move one coin to its left child, and one coin to its right child.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "root = [0,3,0]", + "expected_output": "3\nExplanation: From the left child of the root, we move two coins to the root [taking two moves]. Then, we move one coin from the root of the tree to the right child.", + "explanation": "" + } + ], + "solution": "/**\n * Definition for a binary tree node.\n * function TreeNode(val, left, right) {\n * this.val = (val===undefined ? 0 : val)\n * this.left = (left===undefined ? null : left)\n * this.right = (right===undefined ? null : right)\n * }\n */\n/**\n * @param {TreeNode} root\n * @return {number}\n */\nconst distributeCoins = function(root) {\n let res = 0\n helper(root)\n return res\n \n function helper(node) {\n if(node == null) return 0\n const left = helper(node.left)\n const right = helper(node.right)\n res += Math.abs(left) + Math.abs(right)\n return node.val + left + right - 1\n }\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720cd9", + "questionid": 526, + "title": "Sum of Even Numbers After Queries", + "slug": "sum-of-even-numbers-after-queries", + "description": "You are given an integer array nums and an array queries where queries[i] = [vali, indexi]. For each query i, first, apply nums[indexi] = nums[indexi] + vali, then print the sum of the even values of nums. Return an integer array answer where answer[i] is the answer to the ith query. ", + "category": [ + "Array", + "Simulation" + ], + "complexity": "Medium", + "successrate": 60.9, + "totalsubmissions": 102714, + "totalaccepted": 62602, + "likes": 668, + "dislikes": 212, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,2,3,4], queries = [[1,0],[-3,1],[-4,0],[2,3]]", + "expected_output": "[8,6,2,4]", + "explanation": "At the beginning, the array is [1,2,3,4].\nAfter adding 1 to nums[0], the array is [2,2,3,4], and the sum of even values is 2 + 2 + 4 = 8.\nAfter adding -3 to nums[1], the array is [2,-1,3,4], and the sum of even values is 2 + 4 = 6.\nAfter adding -4 to nums[0], the array is [-2,-1,3,4], and the sum of even values is -2 + 4 = 2.\nAfter adding 2 to nums[3], the array is [-2,-1,3,6], and the sum of even values is -2 + 6 = 4." + }, + { + "example_num": 2, + "expected_input": "nums = [1], queries = [[4,0]]", + "expected_output": "[0]", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} A\n * @param {number[][]} queries\n * @return {number[]}\n */\nconst sumEvenAfterQueries = function(A, queries) {\n const res = []\n for(let i = 0; i < queries.length; i++) {\n A[queries[i][1]] += queries[i][0]\n res.push(sum(A))\n }\n return res\n};\n\nfunction sum(arr) {\n return arr.reduce((ac, el) => ac + (el % 2 === 0 ? el : 0), 0)\n}\n\n// another, better\n\nconst sumEvenAfterQueries = function(A, queries) {\n let sum = A.reduce((acc, cur) => cur%2 == 0 ? acc + cur : acc, 0);\n return queries.map((q) => {\n let i = q[1];\n let s = A[i] + q[0];\n if(s%2 === 0) {\n sum += q[0];\n if(A[i]%2 !== 0) sum += A[i];\n } else if(A[i]%2 === 0) sum -= A[i];\n A[i] = s;\n return sum;\n });\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720cda", + "questionid": 527, + "title": "Interval List Intersections", + "slug": "interval-list-intersections", + "description": "You are given two lists of closed intervals, firstList and secondList, where firstList[i] = [starti, endi] and secondList[j] = [startj, endj]. Each list of intervals is pairwise disjoint and in sorted order. Return the intersection of these two interval lists. A closed interval [a, b] (with a <= b) denotes the set of real numbers x with a <= x <= b. The intersection of two closed intervals is a set of real numbers that are either empty or represented as a closed interval. For example, the intersection of [1, 3] and [2, 4] is [2, 3]. ", + "category": [ + "Array", + "Two Pointers" + ], + "complexity": "Medium", + "successrate": 71.1, + "totalsubmissions": 413025, + "totalaccepted": 293594, + "likes": 4101, + "dislikes": 84, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "firstList = [[0,2],[5,10],[13,23],[24,25]], secondList = [[1,5],[8,12],[15,24],[25,26]]", + "expected_output": "[[1,2],[5,5],[8,10],[15,23],[24,24],[25,25]]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "firstList = [[1,3],[5,9]], secondList = []", + "expected_output": "[]", + "explanation": "" + } + ], + "solution": "/**\n * Definition for an interval.\n * function Interval(start, end) {\n * this.start = start;\n * this.end = end;\n * }\n */\n/**\n * @param {Interval[]} A\n * @param {Interval[]} B\n * @return {Interval[]}\n */\nconst intervalIntersection = function (A, B) {\n const intersection = []\n let i = (j = 0)\n while (i < A.length && j < B.length) {\n const min = Math.max(A[i][0], B[j][0])\n const max = Math.min(A[i][1], B[j][1])\n if (min <= max) intersection.push([min, max])\n A[i][1] > B[j][1] ? j++ : i++\n }\n return intersection\n}\n\n// another\n\n/**\n * @param {number[][]} firstList\n * @param {number[][]} secondList\n * @return {number[][]}\n */\nconst intervalIntersection = function(firstList, secondList) {\n const res = [];\n let i = 0;\n let j = 0;\n while (i < firstList.length && j < secondList.length) {\n const [start1, end1] = firstList[i];\n const [start2, end2] = secondList[j];\n if (start1 <= end2 && start2 <= end1) {\n res.push([Math.max(start1, start2), Math.min(end1, end2)]);\n }\n if (end1 < end2) {\n i++;\n } else {\n j++;\n }\n }\n return res;\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720cdd", + "questionid": 530, + "title": "Add to Array-Form of Integer", + "slug": "add-to-array-form-of-integer", + "description": "The array-form of an integer num is an array representing its digits in left to right order. Given num, the array-form of an integer, and an integer k, return the array-form of the integer num + k. ", + "category": [ + "Array", + "Math" + ], + "complexity": "Easy", + "successrate": 45.4, + "totalsubmissions": 236136, + "totalaccepted": 107305, + "likes": 1195, + "dislikes": 144, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "num = [1,2,0,0], k = 34", + "expected_output": "[1,2,3,4]", + "explanation": "1200 + 34 = 1234" + }, + { + "example_num": 2, + "expected_input": "num = [2,7,4], k = 181", + "expected_output": "[4,5,5]", + "explanation": "274 + 181 = 455" + }, + { + "example_num": 3, + "expected_input": "num = [2,1,5], k = 806", + "expected_output": "[1,0,2,1]", + "explanation": "215 + 806 = 1021" + } + ], + "solution": "/**\n * @param {number[]} num\n * @param {number} k\n * @return {number[]}\n */\nconst addToArrayForm = function(num, k) {\n const res = []\n for(let i = num.length - 1; i >= 0; i--) {\n const tmp = num[i] + k\n res.push(tmp % 10)\n k = ~~(tmp / 10)\n }\n\n while(k > 0) {\n res.push(k % 10)\n k = ~~(k / 10)\n }\n res.reverse()\n return res\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720ce3", + "questionid": 536, + "title": "Minimum Cost to Merge Stones", + "slug": "minimum-cost-to-merge-stones", + "description": "There are n piles of stones arranged in a row. The ith pile has stones[i] stones. A move consists of merging exactly k consecutive piles into one pile, and the cost of this move is equal to the total number of stones in these k piles. Return the minimum cost to merge all piles of stones into one pile. If it is impossible, return -1. ", + "category": [ + "Array", + "Dynamic Programming" + ], + "complexity": "Hard", + "successrate": 42, + "totalsubmissions": 65248, + "totalaccepted": 27381, + "likes": 1524, + "dislikes": 79, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "stones = [3,2,4,1], k = 2", + "expected_output": "20", + "explanation": "We start with [3, 2, 4, 1].\nWe merge [3, 2] for a cost of 5, and we are left with [5, 4, 1].\nWe merge [4, 1] for a cost of 5, and we are left with [5, 5].\nWe merge [5, 5] for a cost of 10, and we are left with [10].\nThe total cost was 20, and this is the minimum possible." + }, + { + "example_num": 2, + "expected_input": "stones = [3,2,4,1], k = 3", + "expected_output": "-1", + "explanation": "After any merge operation, there are 2 piles left, and we can't merge anymore. So the task is impossible." + }, + { + "example_num": 3, + "expected_input": "stones = [3,5,1,2,6], k = 3", + "expected_output": "25", + "explanation": "We start with [3, 5, 1, 2, 6].\nWe merge [5, 1, 2] for a cost of 8, and we are left with [3, 8, 6].\nWe merge [3, 8, 6] for a cost of 17, and we are left with [17].\nThe total cost was 25, and this is the minimum possible." + } + ], + "solution": "/**\n * @param {number[]} stones\n * @param {number} K\n * @return {number}\n */\nconst mergeStones = function(stones, K) {\n const KMO = K - 1\n const N = stones.length\n if ((N - 1) % KMO !== 0) return -1\n const sum = [0]\n const dp = stones.map(s => stones.map(s1 => 0))\n stones.forEach(s => {\n sum.push(sum[sum.length - 1] + s)\n })\n for (let e = KMO; e < N; e++) {\n for (let b = e - KMO; b >= 0; b--) {\n for (let split = e - 1; split >= b; split -= KMO) {\n let cost = dp[b][split] + dp[split + 1][e]\n dp[b][e] = dp[b][e] === 0 ? cost : Math.min(dp[b][e], cost)\n }\n if ((e - b) % KMO === 0) {\n dp[b][e] += sum[e + 1] - sum[b]\n }\n }\n }\n return dp[0][N - 1]\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720ce5", + "questionid": 538, + "title": "Find Common Characters", + "slug": "find-common-characters", + "description": "Given a string array words, return an array of all characters that show up in all strings within the words (including duplicates). You may return the answer in any order. ", + "category": [ + "Array", + "Hash Table", + "String" + ], + "complexity": "Easy", + "successrate": 68.4, + "totalsubmissions": 207326, + "totalaccepted": 141846, + "likes": 2273, + "dislikes": 184, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "words = [\"bella\",\"label\",\"roller\"]", + "expected_output": "[\"e\",\"l\",\"l\"]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "words = [\"cool\",\"lock\",\"cook\"]", + "expected_output": "[\"c\",\"o\"]", + "explanation": "" + } + ], + "solution": "/**\n * @param {string[]} A\n * @return {string[]}\n */\nconst commonChars = function(A) {\n const minArr = minEl(A)\n const res = []\n for(let i = 0; i < minArr[1]; i++) {\n let target = A[minArr[0]][i]\n let all = true\n for(let j = 0; j < A.length; j++) {\n if(j === minArr[0]) continue\n if(all === false) continue\n let idx\n if( (idx = A[j].indexOf(target)) === -1) {\n all = false\n } else {\n A[j] = A[j].slice(0, idx) + A[j].slice(idx + 1)\n }\n }\n if(all) res.push(target)\n }\n \n return res\n};\n\nfunction minEl(arr) {\n const res = [0, Number.MAX_SAFE_INTEGER] // [idx, len]\n for(let i = 0; i < arr.length; i++) {\n if(arr[i].length < res[1]) {\n res[0] = i\n res[1] = arr[i].length\n }\n }\n return res\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720ce6", + "questionid": 539, + "title": "Max Consecutive Ones III", + "slug": "max-consecutive-ones-iii", + "description": "Given a binary array nums and an integer k, return the maximum number of consecutive 1's in the array if you can flip at most k 0's. ", + "category": [ + "Array", + "Binary Search", + "Sliding Window", + "Prefix Sum" + ], + "complexity": "Medium", + "successrate": 62.9, + "totalsubmissions": 320003, + "totalaccepted": 201213, + "likes": 4230, + "dislikes": 55, + "hints": "One thing's for sure, we will only flip a zero if it extends an existing window of 1s. Otherwise, there's no point in doing it, right? Think Sliding Window! Since we know this problem can be solved using the sliding window construct, we might as well focus in that direction for hints. Basically, in a given window, we can never have > K zeros, right? We don't have a fixed size window in this case. The window size can grow and shrink depending upon the number of zeros we have (we don't actually have to flip the zeros here!). The way to shrink or expand a window would be based on the number of zeros that can still be flipped and so on.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,1,1,0,0,0,1,1,1,1,0], k = 2", + "expected_output": "6", + "explanation": "[1,1,1,0,0,1,1,1,1,1,1]\nBolded numbers were flipped from 0 to 1. The longest subarray is underlined." + }, + { + "example_num": 2, + "expected_input": "nums = [0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1], k = 3", + "expected_output": "10", + "explanation": "[0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1]\nBolded numbers were flipped from 0 to 1. The longest subarray is underlined." + } + ], + "solution": "/**\n * @param {number[]} A\n * @param {number} K\n * @return {number}\n */\nconst longestOnes = function (A, K) {\n let i = 0\n let j = 0\n const len = A.length\n while (j < len) {\n if (A[j] === 0) K--\n if (K < 0) {\n if (A[i] === 0) K++\n i++\n }\n j++\n }\n return j - i\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720cea", + "questionid": 543, + "title": "Complement of Base 10 Integer", + "slug": "complement-of-base-10-integer", + "description": "The complement of an integer is the integer you get when you flip all the 0's to 1's and all the 1's to 0's in its binary representation. Given an integer n, return its complement. ", + "category": [ + "Bit Manipulation" + ], + "complexity": "Easy", + "successrate": 62.3, + "totalsubmissions": 200901, + "totalaccepted": 125125, + "likes": 1314, + "dislikes": 70, + "hints": "A binary number plus its complement will equal 111....111 in binary. Also, N = 0 is a corner case.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 5", + "expected_output": "2", + "explanation": "5 is "101" in binary, with complement "010" in binary, which is 2 in base-10." + }, + { + "example_num": 2, + "expected_input": "n = 7", + "expected_output": "0", + "explanation": "7 is "111" in binary, with complement "000" in binary, which is 0 in base-10." + }, + { + "example_num": 3, + "expected_input": "n = 10", + "expected_output": "5", + "explanation": "10 is "1010" in binary, with complement "0101" in binary, which is 5 in base-10." + } + ], + "solution": "/**\n * @param {number} N\n * @return {number}\n */\nconst bitwiseComplement = function(N) {\n let binStr = bin(N)\n let str = ''\n for(let i = 0; i < binStr.length; i++) {\n str += binStr[i] === '0' ? '1' : '0'\n }\n return parseInt(str, 2)\n};\n\nfunction bin(N) {\n return (N >>> 0).toString(2)\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720cee", + "questionid": 547, + "title": "Partition Array Into Three Parts With Equal Sum", + "slug": "partition-array-into-three-parts-with-equal-sum", + "description": "Given an array of integers arr, return true if we can partition the array into three non-empty parts with equal sums. Formally, we can partition the array if we can find indexes i + 1 < j with (arr[0] + arr[1] + ... + arr[i] == arr[i + 1] + arr[i + 2] + ... + arr[j - 1] == arr[j] + arr[j + 1] + ... + arr[arr.length - 1]) ", + "category": [ + "Array", + "Greedy" + ], + "complexity": "Easy", + "successrate": 44.5, + "totalsubmissions": 141004, + "totalaccepted": 62772, + "likes": 1093, + "dislikes": 117, + "hints": "If we have three parts with the same sum, what is the sum of each?\r\nIf you can find the first part, can you find the second part?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "arr = [0,2,1,-6,6,-7,9,1,2,0,1]", + "expected_output": "true\nExplanation: 0 + 2 + 1 = -6 + 6 - 7 + 9 + 1 = 2 + 0 + 1", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "arr = [0,2,1,-6,6,7,9,-1,2,0,1]", + "expected_output": "false", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "arr = [3,3,6,5,-2,2,5,1,-9,4]", + "expected_output": "true\nExplanation: 3 + 3 = 6 = 5 - 2 + 2 + 5 + 1 - 9 + 4", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} A\n * @return {boolean}\n */\nconst canThreePartsEqualSum = function(A) {\n let lo = 0\n let hi = A.length - 1\n let lsum = 0\n let hsum = 0\n const sum = A.reduce((ac, el) => ac + el, 0)\n if(sum % 3 !== 0) return false\n const target = sum / 3\n\n while(lo < hi && lsum !== target) {\n lsum += A[lo]\n lo++\n }\n if(lsum !== target) return false\n while(lo < hi && hsum !== target) {\n hsum += A[hi]\n hi--\n }\n if(hsum !== target) return false\n\n let msum = 0\n for(let i = lo; i <= hi; i++) {\n msum += A[i]\n }\n if(msum !== target) return false\n return true\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720cf5", + "questionid": 554, + "title": "Camelcase Matching", + "slug": "camelcase-matching", + "description": "Given an array of strings queries and a string pattern, return a boolean array answer where answer[i] is true if queries[i] matches pattern, and false otherwise. A query word queries[i] matches pattern if you can insert lowercase English letters pattern so that it equals the query. You may insert each character at any position and you may not insert any characters. ", + "category": [ + "Two Pointers", + "String", + "Trie", + "String Matching" + ], + "complexity": "Medium", + "successrate": 59.1, + "totalsubmissions": 52591, + "totalaccepted": 31099, + "likes": 541, + "dislikes": 220, + "hints": "Given a single pattern and word, how can we solve it? One way to do it is using a DP (pos1, pos2) where pos1 is a pointer to the word and pos2 to the pattern and returns true if we can match the pattern with the given word. We have two scenarios: The first one is when `word[pos1] == pattern[pos2]`, then the transition will be just DP(pos1 + 1, pos2 + 1). The second scenario is when `word[pos1]` is lowercase then we can add this character to the pattern so that the transition is just DP(pos1 + 1, pos2)\r\nThe case base is `if (pos1 == n && pos2 == m) return true;` Where n and m are the sizes of the strings word and pattern respectively.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "queries = ["FooBar","FooBarTest","FootBall","FrameBuffer","ForceFeedBack"], pattern = "FB"", + "expected_output": "[true,false,true,true,false]", + "explanation": ""FooBar" can be generated like this "F" + "oo" + "B" + "ar".\n"FootBall" can be generated like this "F" + "oot" + "B" + "all".\n"FrameBuffer" can be generated like this "F" + "rame" + "B" + "uffer"." + }, + { + "example_num": 2, + "expected_input": "queries = ["FooBar","FooBarTest","FootBall","FrameBuffer","ForceFeedBack"], pattern = "FoBa"", + "expected_output": "[true,false,true,false,false]", + "explanation": ""FooBar" can be generated like this "Fo" + "o" + "Ba" + "r".\n"FootBall" can be generated like this "Fo" + "ot" + "Ba" + "ll"." + }, + { + "example_num": 3, + "expected_input": "queries = ["FooBar","FooBarTest","FootBall","FrameBuffer","ForceFeedBack"], pattern = "FoBaT"", + "expected_output": "[false,true,false,false,false]", + "explanation": ""FooBarTest" can be generated like this "Fo" + "o" + "Ba" + "r" + "T" + "est"." + } + ], + "solution": "/**\n * @param {string[]} queries\n * @param {string} pattern\n * @return {boolean[]}\n */\nconst camelMatch = function(queries, pattern) {\n const res = []\n\n queries.forEach(el => {\n let tmp = chk(el, pattern)\n if(tmp) res.push(true)\n else res.push(false)\n })\n \n return res\n};\n\nfunction chk(str, p) {\n let pIdx = 0\n let sIdx = 0\n const sLen = str.length\n const pLen = p.length\n const Acode = ('A').charCodeAt(0)\n const Zcode = ('Z').charCodeAt(0)\n let pEnd = false\n\n for(let i = 0; i < pLen; i++) {\n let target = p.charAt(i)\n \n while(sIdx < sLen && !pEnd) {\n if(str.charCodeAt(sIdx) >= Acode && str.charCodeAt(sIdx) <= Zcode && str.charAt(sIdx) !== target) return false\n if(str.charAt(sIdx) === target) {\n if(i !== pLen - 1) {\n sIdx++\n } else {\n pEnd = true\n }\n break\n } else {\n sIdx++ \n }\n }\n if(sIdx >= sLen) return false\n }\n\n for(let i = sIdx + 1; pEnd && i < sLen; i++) {\n if(str.charCodeAt(i) >= Acode && str.charCodeAt(i) <= Zcode) return false\n }\n return true\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720cf8", + "questionid": 557, + "title": "Recover a Tree From Preorder Traversal", + "slug": "recover-a-tree-from-preorder-traversal", + "description": "We run a\u00a0preorder\u00a0depth-first search (DFS) on the root of a binary tree. At each node in this traversal, we output D dashes (where D is the depth of this node), then we output the value of this node.\u00a0 If the depth of a node is D, the depth of its immediate child is D + 1.\u00a0 The depth of the root node is 0. If a node has only one child, that child is guaranteed to be the left child. Given the output traversal of this traversal, recover the tree and return its root. ", + "category": [ + "String", + "Tree", + "Depth-First Search", + "Binary Tree" + ], + "complexity": "Hard", + "successrate": 72.4, + "totalsubmissions": 47225, + "totalaccepted": 34187, + "likes": 1013, + "dislikes": 30, + "hints": "Do an iterative depth first search, parsing dashes from the string to inform you how to link the nodes together.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "traversal = "1-2--3--4-5--6--7"", + "expected_output": "[1,2,5,3,4,6,7]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "traversal = "1-2--3---4-5--6---7"", + "expected_output": "[1,2,5,3,null,6,null,4,null,7]", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "traversal = "1-401--349---90--88"", + "expected_output": "[1,401,null,349,88,90]", + "explanation": "" + } + ], + "solution": "/**\n * Definition for a binary tree node.\n * function TreeNode(val) {\n * this.val = val;\n * this.left = this.right = null;\n * }\n */\n/**\n * @param {string} S\n * @return {TreeNode}\n */\nconst recoverFromPreorder = function(S) {\n const arr = []\n let tmp = S[0]\n for(let i = 1; i < S.length; i++) {\n if(S[i] === '-') {\n if(S[i-1] === '-') {\n tmp += '-'\n } else {\n arr.push(tmp)\n tmp = '-'\n }\n } else {\n if(S[i-1] === '-') {\n arr.push(tmp)\n tmp = S[i]\n } else {\n tmp += S[i]\n }\n }\n }\n arr.push(tmp)\n const resArr = []\n helper(resArr, arr, 0)\n return resArr[0]\n};\n\n\nfunction helper(nodeArr, strArr, idx) {\n if(idx >= strArr.length) return\n if(idx > 0) {\n \n if(strArr[idx].startsWith('-')) {\n helper(nodeArr, strArr, idx + 1)\n } else {\n nodeArr[idx] = new TreeNode(+strArr[idx])\n let d = strArr[idx - 1].length\n\n let tIdx\n\n for(let i = idx - 1; ; i = i - 2) {\n if(i>= 1) {\n if(strArr[i].length < d) {\n tIdx = i+1\n break\n }\n } else {\n\n tIdx = 0\n break\n }\n }\n \n if(nodeArr[tIdx].left) {\n nodeArr[tIdx].right = nodeArr[idx]\n } else {\n nodeArr[tIdx].left = nodeArr[idx]\n }\n helper(nodeArr, strArr, idx + 1)\n }\n\n } else {\n nodeArr[idx] = new TreeNode(+strArr[idx])\n helper(nodeArr, strArr, idx + 1)\n }\n \n}\n\n" + }, + { + "_id": "66f925ddfdfb8e1665720cfa", + "questionid": 559, + "title": "Two City Scheduling", + "slug": "two-city-scheduling", + "description": "A company is planning to interview 2n people. Given the array costs where costs[i] = [aCosti, bCosti],\u00a0the cost of flying the ith person to city a is aCosti, and the cost of flying the ith person to city b is bCosti. Return the minimum cost to fly every person to a city such that exactly n people arrive in each city. ", + "category": [ + "Array", + "Greedy", + "Sorting" + ], + "complexity": "Medium", + "successrate": 63.6, + "totalsubmissions": 277601, + "totalaccepted": 176436, + "likes": 3594, + "dislikes": 273, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "costs = [[10,20],[30,200],[400,50],[30,20]]", + "expected_output": "110\nExplanation: \nThe first person goes to city A for a cost of 10.\nThe second person goes to city A for a cost of 30.\nThe third person goes to city B for a cost of 50.\nThe fourth person goes to city B for a cost of 20.\n\nThe total minimum cost is 10 + 30 + 50 + 20 = 110 to have half the people interviewing in each city.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "costs = [[259,770],[448,54],[926,667],[184,139],[840,118],[577,469]]", + "expected_output": "1859", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "costs = [[515,563],[451,713],[537,709],[343,819],[855,779],[457,60],[650,359],[631,42]]", + "expected_output": "3086", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[][]} costs\n * @return {number}\n */\nconst twoCitySchedCost = function(costs) {\n const N = costs.length / 2\n const dp = Array.from({ length: N + 1 }, () => new Array(N + 1).fill(0))\n for (let i = 1; i <= N; i++) {\n dp[i][0] = dp[i - 1][0] + costs[i - 1][0]\n }\n for (let j = 1; j <= N; j++) {\n dp[0][j] = dp[0][j - 1] + costs[j - 1][1]\n }\n for (let i = 1; i <= N; i++) {\n for (let j = 1; j <= N; j++) {\n dp[i][j] = Math.min(\n dp[i - 1][j] + costs[i + j - 1][0],\n dp[i][j - 1] + costs[i + j - 1][1]\n )\n }\n }\n return dp[N][N]\n}\n\n// another\n\n/**\n * @param {number[][]} costs\n * @return {number}\n */\nconst twoCitySchedCost = function(costs) {\n const N = costs.length\n let res = 0\n const refund = []\n for(let i = 0; i < N; i++) {\n refund[i] = costs[i][1] - costs[i][0]\n res += costs[i][0]\n }\n refund.sort((a, b) => a - b)\n for(let i = 0; i < N / 2; i++) {\n res += refund[i]\n }\n return res\n};\n\n// another\n\n/**\n * @param {number[][]} costs\n * @return {number}\n */\nconst twoCitySchedCost = function(costs) {\n const len = costs.length\n if(len === 0) return 0\n const N = len / 2\n costs.sort((a, b) => (a[0] - a[1]) - (b[0] - b[1]))\n let res = 0\n for(let i = 0; i < costs.length; i++) {\n if(i < N) {\n res += costs[i][0]\n } else {\n res += costs[i][1]\n }\n }\n return res\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720cfe", + "questionid": 563, + "title": "Minimum Score Triangulation of Polygon", + "slug": "minimum-score-triangulation-of-polygon", + "description": "You have a convex n-sided polygon where each vertex has an integer value. You are given an integer array values where values[i] is the value of the ith vertex (i.e., clockwise order). You will triangulate the polygon into n - 2 triangles. For each triangle, the value of that triangle is the product of the values of its vertices, and the total score of the triangulation is the sum of these values over all n - 2 triangles in the triangulation. Return the smallest possible total score that you can achieve with some triangulation of the polygon. ", + "category": [ + "Array", + "Dynamic Programming" + ], + "complexity": "Medium", + "successrate": 52.5, + "totalsubmissions": 42068, + "totalaccepted": 22074, + "likes": 991, + "dislikes": 113, + "hints": "Without loss of generality, there is a triangle that uses adjacent vertices A[0] and A[N-1] (where N = A.length). Depending on your choice K of it, this breaks down the triangulation into two subproblems A[1:K] and A[K+1:N-1].", + "deleted": false, + "examples": [], + "solution": "/**\n * @param {number[]} A\n * @return {number}\n */\nconst minScoreTriangulation = function(A) {\n if(A.length <= 2) return 0\n if(A.length === 3) return A[0] * A[1] * A[2]\n return chk(A, A.length)\n};\n\nfunction cost(points, i, j, k) {\n let p1 = points[i],\n p2 = points[j],\n p3 = points[k]\n return p1 * p2 * p3\n}\n\nfunction chk(points, n) {\n if (n < 3) return 0\n\n const table = Array.from({ length: n }, () => new Array(n).fill(0))\n\n for (let gap = 0; gap < n; gap++) {\n for (let i = 0, j = gap; j < n; i++, j++) {\n if (j < i + 2) table[i][j] = 0\n else {\n table[i][j] = Number.MAX_VALUE\n for (let k = i + 1; k < j; k++) {\n let val = table[i][k] + table[k][j] + cost(points, i, j, k)\n if (table[i][j] > val) table[i][j] = val\n }\n }\n }\n }\n return table[0][n - 1]\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720d01", + "questionid": 566, + "title": "Maximum Level Sum of a Binary Tree", + "slug": "maximum-level-sum-of-a-binary-tree", + "description": "Given the root of a binary tree, the level of its root is 1, the level of its children is 2, and so on. Return the smallest level x such that the sum of all the values of nodes at level x is maximal. ", + "category": [ + "Tree", + "Depth-First Search", + "Breadth-First Search", + "Binary Tree" + ], + "complexity": "Medium", + "successrate": 66.6, + "totalsubmissions": 152803, + "totalaccepted": 101752, + "likes": 1375, + "dislikes": 56, + "hints": "Calculate the sum for each level then find the level with the maximum sum. How can you traverse the tree ? How can you sum up the values for every level ? Use DFS or BFS to traverse the tree keeping the level of each node, and sum up those values with a map or a frequency array.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [1,7,0,7,-8,null,null]", + "expected_output": "2\nExplanation: \nLevel 1 sum = 1.\nLevel 2 sum = 7 + 0 = 7.\nLevel 3 sum = 7 + -8 = -1.\nSo we return the level with the maximum sum which is level 2.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "root = [989,null,10250,98693,-89388,null,null,null,-32127]", + "expected_output": "2", + "explanation": "" + } + ], + "solution": "/**\n * Definition for a binary tree node.\n * function TreeNode(val) {\n * this.val = val;\n * this.left = this.right = null;\n * }\n */\n/**\n * @param {TreeNode} root\n * @return {number}\n */\nconst maxLevelSum = function(root) {\n if (root == null) return 0\n let res = 1\n let cur = [root]\n let next = []\n let max = Number.MIN_SAFE_INTEGER\n let sum = 0\n let level = 1\n while (cur.length) {\n let node = cur.pop()\n if (node.left) next.push(node.left)\n if (node.right) next.push(node.right)\n sum += node.val\n if (cur.length === 0) {\n cur = next\n next = []\n if (sum > max) {\n res = level\n max = sum\n }\n sum = 0\n level++\n }\n }\n\n return res\n}\n\n// DFS\n\nconst maxLevelSum = function(root) {\n let result = {};\n let recursion = function(root, level) {\n if (result[level] !== undefined) {\n result[level] += root.val;\n } else {\n result[level] = root.val;\n }\n if (root.left !== null) {\n recursion(root.left, level + 1);\n }\n if (root.right !== null) {\n recursion(root.right, level + 1);\n }\n };\n recursion(root, 1);\n let resultkey = 1;\n let max = Number.MIN_VALUE;\n for (let key of Object.keys(result)) {\n if (result[key] > max) {\n max = result[key];\n resultkey = key;\n }\n }\n return Number(resultkey);\n};\n\n" + }, + { + "_id": "66f925ddfdfb8e1665720d09", + "questionid": 574, + "title": "Previous Permutation With One Swap", + "slug": "previous-permutation-with-one-swap", + "description": "Given an array of positive integers arr (not necessarily distinct), return the lexicographically largest permutation that is smaller than arr, that can be made with exactly one swap (A swap exchanges the positions of two numbers arr[i] and arr[j]). If it cannot be done, then return the same array. ", + "category": [ + "Array", + "Greedy" + ], + "complexity": "Medium", + "successrate": 51.8, + "totalsubmissions": 58931, + "totalaccepted": 30533, + "likes": 223, + "dislikes": 23, + "hints": "You need to swap two values, one larger than the other. Where is the larger one located?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "arr = [3,2,1]", + "expected_output": "[3,1,2]", + "explanation": "Swapping 2 and 1." + }, + { + "example_num": 2, + "expected_input": "arr = [1,1,5]", + "expected_output": "[1,1,5]", + "explanation": "This is already the smallest permutation." + }, + { + "example_num": 3, + "expected_input": "arr = [1,9,4,6,7]", + "expected_output": "[1,7,4,6,9]", + "explanation": "Swapping 9 and 7." + } + ], + "solution": "/**\n * @param {number[]} A\n * @return {number[]}\n */\nconst prevPermOpt1 = function(A) {\n let n = A.length, left = n - 2, right = n - 1;\n while (left >= 0 && A[left] <= A[left + 1]) left--;\n if (left < 0) return A;\n while (A[left] <= A[right]) right--;\n while (A[right - 1] == A[right]) right--;\n swap(A,left,right)\n return A;\n};\nfunction swap(a, i, j) {\n let tmp = a[i]\n a[i] = a[j]\n a[j] = tmp\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720ccc", + "questionid": 513, + "title": "Delete Columns to Make Sorted III", + "slug": "delete-columns-to-make-sorted-iii", + "description": "You are given an array of n strings strs, all of the same length. We may choose any deletion indices, and we delete all the characters in those indices for each string. For example, if we have strs = [\"abcdef\",\"uvwxyz\"] and deletion indices {0, 2, 3}, then the final array after deletions is [\"bef\", \"vyz\"]. Suppose we chose a set of deletion indices answer such that after deletions, the final array has every string (row) in lexicographic order. (i.e., (strs[0][0] <= strs[0][1] <= ... <= strs[0][strs[0].length - 1]), and (strs[1][0] <= strs[1][1] <= ... <= strs[1][strs[1].length - 1]), and so on). Return the minimum possible value of answer.length. ", + "category": [ + "Array", + "String", + "Dynamic Programming" + ], + "complexity": "Hard", + "successrate": 56.5, + "totalsubmissions": 18026, + "totalaccepted": 10191, + "likes": 421, + "dislikes": 11, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "strs = ["babca","bbazb"]", + "expected_output": "3", + "explanation": "After deleting columns 0, 1, and 4, the final array is strs = ["bc", "az"].\nBoth these rows are individually in lexicographic order (ie. strs[0][0] <= strs[0][1] and strs[1][0] <= strs[1][1]).\nNote that strs[0] > strs[1] - the array strs is not necessarily in lexicographic order." + }, + { + "example_num": 2, + "expected_input": "strs = ["edcba"]", + "expected_output": "4", + "explanation": "If we delete less than 4 columns, the only row will not be lexicographically sorted." + }, + { + "example_num": 3, + "expected_input": "strs = ["ghi","def","abc"]", + "expected_output": "0", + "explanation": "All rows are already lexicographically sorted." + } + ], + "solution": "/**\n * @param {string[]} A\n * @return {number}\n */\nconst minDeletionSize = function(A) {\n const dp = new Array(A[0].length).fill(1)\n for (let i = 0; i < A[0].length; i++) {\n for (let j = 0; j < i; j++) {\n for (let k = 0; k <= A.length; k++) {\n if (k === A.length) dp[i] = Math.max(dp[i], dp[j] + 1)\n else if (A[k][j] > A[k][i]) break\n }\n }\n }\n return A[0].length - Math.max(...dp)\n}\n\n// another\n\nconst minDeletionSize = function(A) {\n const rows = A.length\n const cols = A[0].length\n let res = cols - 1\n let k\n const dp = new Array(cols).fill(1)\n for (let i = 0; i < cols; i++) {\n for (let j = 0; j < i; j++) {\n for (k = 0; k < rows; k++) {\n if (A[k][j] > A[k][i]) break\n }\n if (k === rows && dp[j] + 1 > dp[i]) dp[i] = dp[j] + 1\n }\n res = Math.min(res, cols - dp[i])\n }\n return res\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720cd7", + "questionid": 524, + "title": "Squares of a Sorted Array", + "slug": "squares-of-a-sorted-array", + "description": "Given an integer array nums sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order. ", + "category": [ + "Array", + "Two Pointers", + "Sorting" + ], + "complexity": "Easy", + "successrate": 71.6, + "totalsubmissions": 1324165, + "totalaccepted": 948265, + "likes": 5114, + "dislikes": 150, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [-4,-1,0,3,10]", + "expected_output": "[0,1,9,16,100]", + "explanation": "After squaring, the array becomes [16,1,0,9,100].\nAfter sorting, it becomes [0,1,9,16,100]." + }, + { + "example_num": 2, + "expected_input": "nums = [-7,-3,2,3,11]", + "expected_output": "[4,9,9,49,121]", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} A\n * @return {number[]}\n */\nconst sortedSquares = function(A) {\n const result = [];\n let i = A.length - 1;\n let left = 0;\n let right = A.length -1;\n while (left <= right) {\n if (Math.abs(A[left]) < A[right]) {\n result.unshift(A[right] * A[right])\n right--;\n } else {\n result.unshift(A[left] * A[left])\n left++\n }\n }\n return result;\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720cdb", + "questionid": 528, + "title": "Vertical Order Traversal of a Binary Tree", + "slug": "vertical-order-traversal-of-a-binary-tree", + "description": "Given the root of a binary tree, calculate the vertical order traversal of the binary tree. For each node at position (row, col), its left and right children will be at positions (row + 1, col - 1) and (row + 1, col + 1) respectively. The root of the tree is at (0, 0). The vertical order traversal of a binary tree is a list of top-to-bottom orderings for each column index starting from the leftmost column and ending on the rightmost column. There may be multiple nodes in the same row and same column. In such a case, sort these nodes by their values. Return the vertical order traversal of the binary tree. ", + "category": [ + "Hash Table", + "Tree", + "Depth-First Search", + "Breadth-First Search", + "Binary Tree" + ], + "complexity": "Hard", + "successrate": 41.4, + "totalsubmissions": 520150, + "totalaccepted": 215521, + "likes": 3104, + "dislikes": 3293, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [3,9,20,null,null,15,7]", + "expected_output": "[[9],[3,15],[20],[7]]", + "explanation": "Column -1: Only node 9 is in this column.\nColumn 0: Nodes 3 and 15 are in this column in that order from top to bottom.\nColumn 1: Only node 20 is in this column.\nColumn 2: Only node 7 is in this column." + }, + { + "example_num": 2, + "expected_input": "root = [1,2,3,4,5,6,7]", + "expected_output": "[[4],[2],[1,5,6],[3],[7]]", + "explanation": "Column -2: Only node 4 is in this column.\nColumn -1: Only node 2 is in this column.\nColumn 0: Nodes 1, 5, and 6 are in this column.\n 1 is at the top, so it comes first.\n 5 and 6 are at the same position (2, 0), so we order them by their value, 5 before 6.\nColumn 1: Only node 3 is in this column.\nColumn 2: Only node 7 is in this column." + }, + { + "example_num": 3, + "expected_input": "root = [1,2,3,4,6,5,7]", + "expected_output": "[[4],[2],[1,5,6],[3],[7]]", + "explanation": "This case is the exact same as example 2, but with nodes 5 and 6 swapped.\nNote that the solution remains the same since 5 and 6 are in the same location and should be ordered by their values." + } + ], + "solution": "/**\n * Definition for a binary tree node.\n * function TreeNode(val, left, right) {\n * this.val = (val===undefined ? 0 : val)\n * this.left = (left===undefined ? null : left)\n * this.right = (right===undefined ? null : right)\n * }\n */\n/**\n * @param {TreeNode} root\n * @return {number[][]}\n */\nconst verticalTraversal = function(root) {\n const arr = []\n helper(root, 0, 0, arr)\n arr.sort((a, b) => a[0] - b[0] || b[1] - a[1] || a[2] - b[2])\n const res = new Map()\n\n for(let [x, y, val] of arr) {\n if(!res.has(x)) res.set(x, [])\n res.get(x).push(val)\n }\n return [...res.values()]\n};\n\nfunction helper(node, x, y, arr) {\n if(node) {\n helper(node.left, x - 1, y - 1, arr)\n arr.push([x, y, node.val])\n helper(node.right, x + 1, y - 1, arr)\n }\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720ce2", + "questionid": 535, + "title": "Available Captures for Rook", + "slug": "available-captures-for-rook", + "description": "On an 8 x 8 chessboard, there is exactly one white rook 'R' and some number of white bishops 'B', black pawns 'p', and empty squares '.'. When the rook moves, it chooses one of four cardinal directions (north, east, south, or west), then moves in that direction until it chooses to stop, reaches the edge of the board, captures a black pawn, or is blocked by a white bishop. A rook is considered attacking a pawn if the rook can capture the pawn on the rook's turn. The number of available captures for the white rook is the number of pawns that the rook is attacking. Return the number of available captures for the white rook. ", + "category": [ + "Array", + "Matrix", + "Simulation" + ], + "complexity": "Easy", + "successrate": 67.5, + "totalsubmissions": 73332, + "totalaccepted": 49531, + "likes": 443, + "dislikes": 560, + "hints": "", + "deleted": false, + "examples": [], + "solution": "/**\n * @param {character[][]} board\n * @return {number}\n */\nconst numRookCaptures = function(board) {\n for (let i = 0; i < board.length; ++i)\n for (let j = 0; j < board[i].length; ++j)\n if (board[i][j] == 'R') return cap(board,i,j,0,1)+cap(board,i,j,0,-1)+cap(board,i,j,1,0)+cap(board,i,j,-1,0);\n return 0; \n};\n\nfunction cap(b, x, y, dx, dy) {\n while (x >= 0 && x < b.length && y >= 0 && y < b[x].length && b[x][y] != 'B') {\n if (b[x][y] == 'p') return 1;\n x += dx; y += dy;\n }\n return 0;\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720cf0", + "questionid": 549, + "title": "Convert to Base -2", + "slug": "convert-to-base-2", + "description": "Given an integer n, return a binary string representing its representation in base -2. Note that the returned string should not have leading zeros unless the string is \"0\". ", + "category": [ + "Math" + ], + "complexity": "Medium", + "successrate": 60.2, + "totalsubmissions": 30310, + "totalaccepted": 18251, + "likes": 346, + "dislikes": 225, + "hints": "Figure out whether you need the ones digit placed or not, then shift by two.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 2", + "expected_output": ""110"\nExplantion: (-2)2 + (-2)1 = 2", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "n = 3", + "expected_output": ""111"\nExplantion: (-2)2 + (-2)1 + (-2)0 = 3", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "n = 4", + "expected_output": ""100"\nExplantion: (-2)2 = 4", + "explanation": "" + } + ], + "solution": "/**\n * @param {number} N\n * @return {string}\n */\nconst baseNeg2 = function(N) {\n return negBase(N, -2)\n};\n\nfunction negBase(val, base) {\n if(val === 0) return '0'\n\tlet result = '';\n\twhile (val !== 0) {\n\t\tlet remainder = val % base;\n\t\tval = Math.trunc(val / base);\n\t\tif (remainder < 0) {\n\t\t\tremainder += -base;\n\t\t\tval += 1;\n\t\t}\n\t\tresult = remainder + result;\n\t}\n\treturn result;\n}\n\n// another\n\n/**\n * @param {number} N\n * @return {string}\n */\nconst baseNeg2 = function(N) {\n if (N === 0) return \"0\"; \n let res = ''\n while(N !== 0) {\n res = (N & 1) + res\n N = -(N >> 1)\n }\n return res; \n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720d06", + "questionid": 571, + "title": "Last Substring in Lexicographical Order", + "slug": "last-substring-in-lexicographical-order", + "description": "Given a string s, return the last substring of s in lexicographical order. ", + "category": [ + "Two Pointers", + "String" + ], + "complexity": "Hard", + "successrate": 35.6, + "totalsubmissions": 82473, + "totalaccepted": 29361, + "likes": 435, + "dislikes": 406, + "hints": "Assume that the answer is a sub-string from index i to j. If you add the character at index j+1 you get a better answer. The answer is always a suffix of the given string. Since the limits are high, we need an efficient data structure. Use suffix array.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "abab"", + "expected_output": ""bab"", + "explanation": "The substrings are ["a", "ab", "aba", "abab", "b", "ba", "bab"]. The lexicographically maximum substring is "bab"." + }, + { + "example_num": 2, + "expected_input": "s = "leetcode"", + "expected_output": ""tcode"", + "explanation": "" + } + ], + "solution": "/**\n * @param {string} s\n * @return {string}\n */\nconst lastSubstring = function(s) {\n let ans = '',\n max = 'a'\n for (let i = 0; i < s.length; ) {\n let j = i,\n sub = s.slice(i)\n if (max < s[i] || ans < sub) {\n max = s[i]\n ans = sub\n }\n while (i < s.length && s[i + 1] === s[i]) {\n i++\n }\n if (j === i) {\n i++\n }\n }\n return ans\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720cce", + "questionid": 515, + "title": "Minimum Area Rectangle II", + "slug": "minimum-area-rectangle-ii", + "description": "You are given an array of points in the X-Y plane points where points[i] = [xi, yi]. Return the minimum area of any rectangle formed from these points, with sides not necessarily parallel to the X and Y axes. If there is not any such rectangle, return 0. Answers within 10-5 of the actual answer will be accepted. ", + "category": [ + "Array", + "Math", + "Geometry" + ], + "complexity": "Medium", + "successrate": 54.4, + "totalsubmissions": 41787, + "totalaccepted": 22753, + "likes": 302, + "dislikes": 400, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "points = [[1,2],[2,1],[1,0],[0,1]]", + "expected_output": "2.00000", + "explanation": "The minimum area rectangle occurs at [1,2],[2,1],[1,0],[0,1], with an area of 2." + }, + { + "example_num": 2, + "expected_input": "points = [[0,1],[2,1],[1,1],[1,0],[2,0]]", + "expected_output": "1.00000", + "explanation": "The minimum area rectangle occurs at [1,0],[1,1],[2,1],[2,0], with an area of 1." + }, + { + "example_num": 3, + "expected_input": "points = [[0,3],[1,2],[3,1],[1,3],[2,1]]", + "expected_output": "0", + "explanation": "There is no possible rectangle to form from these points." + } + ], + "solution": null + }, + { + "_id": "66f925ddfdfb8e1665720ccf", + "questionid": 516, + "title": "Univalued Binary Tree", + "slug": "univalued-binary-tree", + "description": "A binary tree is uni-valued if every node in the tree has the same value. Given the root of a binary tree, return true if the given tree is uni-valued, or false otherwise. ", + "category": [ + "Tree", + "Depth-First Search", + "Breadth-First Search", + "Binary Tree" + ], + "complexity": "Easy", + "successrate": 68.9, + "totalsubmissions": 227655, + "totalaccepted": 156880, + "likes": 1259, + "dislikes": 56, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [1,1,1,1,1,null,1]", + "expected_output": "true", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "root = [2,2,2,5,2]", + "expected_output": "false", + "explanation": "" + } + ], + "solution": "/**\n * Definition for a binary tree node.\n * function TreeNode(val) {\n * this.val = val;\n * this.left = this.right = null;\n * }\n */\n/**\n * @param {TreeNode} root\n * @return {boolean}\n */\nconst isUnivalTree = function(root) {\n const arr = []\n dfs(root, arr)\n for(let i = 1; i < arr.length; i++) {\n if(arr[i] !== arr[i- 1]) return false\n }\n return true\n};\n\nfunction dfs(node, arr) {\n if(node === null) return\n arr.push(node.val)\n dfs(node.left, arr)\n dfs(node.right, arr)\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720cd0", + "questionid": 517, + "title": "Numbers With Same Consecutive Differences", + "slug": "numbers-with-same-consecutive-differences", + "description": "Return all non-negative integers of length n such that the absolute difference between every two consecutive digits is k. Note that every number in the answer must not have leading zeros. For example, 01 has one leading zero and is invalid. You may return the answer in any order. ", + "category": [ + "Backtracking", + "Breadth-First Search" + ], + "complexity": "Medium", + "successrate": 47.2, + "totalsubmissions": 105324, + "totalaccepted": 49756, + "likes": 860, + "dislikes": 131, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 3, k = 7", + "expected_output": "[181,292,707,818,929]", + "explanation": "Note that 070 is not a valid number, because it has leading zeroes." + }, + { + "example_num": 2, + "expected_input": "n = 2, k = 1", + "expected_output": "[10,12,21,23,32,34,43,45,54,56,65,67,76,78,87,89,98]", + "explanation": "" + } + ], + "solution": "/**\n * @param {number} n\n * @param {number} k\n * @return {number[]}\n */\nconst numsSameConsecDiff = function (n, k) {\n const res = []\n \n for(let i = 1; i <= 9; i++) {\n dfs(n - 1, [i])\n }\n \n return res\n\n function dfs(num, arr) {\n if(num === 0) {\n res.push(+arr.join(''))\n return \n }\n\n for(let i = 0; i <= 9; i++) {\n if(Math.abs(i - arr[arr.length - 1]) === k) {\n arr.push(i)\n dfs(num - 1, arr)\n arr.pop()\n }\n }\n }\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720cd2", + "questionid": 519, + "title": "Powerful Integers", + "slug": "powerful-integers", + "description": "Given three integers x, y, and bound, return a list of all the powerful integers that have a value less than or equal to bound. An integer is powerful if it can be represented as xi + yj for some integers i >= 0 and j >= 0. You may return the answer in any order. In your answer, each value should occur at most once. ", + "category": [ + "Hash Table", + "Math" + ], + "complexity": "Medium", + "successrate": 43.6, + "totalsubmissions": 105922, + "totalaccepted": 46133, + "likes": 242, + "dislikes": 62, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "x = 2, y = 3, bound = 10", + "expected_output": "[2,3,4,5,7,9,10]", + "explanation": "2 = 20 + 30\n3 = 21 + 30\n4 = 20 + 31\n5 = 21 + 31\n7 = 22 + 31\n9 = 23 + 30\n10 = 20 + 32" + }, + { + "example_num": 2, + "expected_input": "x = 3, y = 5, bound = 15", + "expected_output": "[2,4,6,8,10,14]", + "explanation": "" + } + ], + "solution": null + }, + { + "_id": "66f925ddfdfb8e1665720cd5", + "questionid": 522, + "title": "Subarray Sums Divisible by K", + "slug": "subarray-sums-divisible-by-k", + "description": "Given an integer array nums and an integer k, return the number of non-empty subarrays that have a sum divisible by k. A subarray is a contiguous part of an array. ", + "category": [ + "Array", + "Hash Table", + "Prefix Sum" + ], + "complexity": "Medium", + "successrate": 53.2, + "totalsubmissions": 174162, + "totalaccepted": 92620, + "likes": 2709, + "dislikes": 133, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [4,5,0,-2,-3,1], k = 5", + "expected_output": "7", + "explanation": "There are 7 subarrays with a sum divisible by k = 5:\n[4, 5, 0, -2, -3, 1], [5], [5, 0], [5, 0, -2, -3], [0], [0, -2, -3], [-2, -3]" + }, + { + "example_num": 2, + "expected_input": "nums = [5], k = 9", + "expected_output": "0", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} nums\n * @param {number} k\n * @return {number}\n */\nconst subarraysDivByK = function (nums, k) {\n const memo = {0: 1}\n let sum = 0, res = 0\n for(const e of nums) {\n sum += e\n const remain = ( sum % k + k) % k\n res += memo[remain] ?? 0\n memo[remain] = (memo[remain] ?? 0) + 1 \n }\n return res\n}\n\n// another\n\n/**\n * @param {number[]} nums\n * @param {number} k\n * @return {number}\n */\nconst subarraysDivByK = function(nums, k) {\n const memo = {0: 1}\n let sum = 0, res = 0\n for(const e of nums) {\n sum += e\n const remain = (k - (sum % k)) % k\n res += memo[remain] ?? 0\n memo[remain] = (memo[remain] ?? 0) + 1 \n }\n return res\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720cdc", + "questionid": 529, + "title": "Smallest String Starting From Leaf", + "slug": "smallest-string-starting-from-leaf", + "description": "You are given the root of a binary tree where each node has a value in the range [0, 25] representing the letters 'a' to 'z'. Return the lexicographically smallest string that starts at a leaf of this tree and ends at the root. As a reminder, any shorter prefix of a string is lexicographically smaller. A leaf of a node is a node that has no children. ", + "category": [ + "String", + "Tree", + "Depth-First Search", + "Binary Tree" + ], + "complexity": "Medium", + "successrate": 48.6, + "totalsubmissions": 107393, + "totalaccepted": 52244, + "likes": 1046, + "dislikes": 168, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [0,1,2,3,4,3,4]", + "expected_output": ""dba"", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "root = [25,1,3,1,3,0,2]", + "expected_output": ""adz"", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "root = [2,2,1,null,1,0,null,0]", + "expected_output": ""abc"", + "explanation": "" + } + ], + "solution": "/**\n * Definition for a binary tree node.\n * function TreeNode(val) {\n * this.val = val;\n * this.left = this.right = null;\n * }\n */\n/**\n * @param {TreeNode} root\n * @return {string}\n */\nconst smallestFromLeaf = function(root) {\n const res = []\n chk(root, [], res)\n res.sort()\n return res[0]\n};\n\nfunction chk(node, path, res) {\n if(node == null) return\n path.push(node.val)\n if(node.left == null && node.right == null) {\n res.push(arrToStr( path.slice(0).reverse() ))\n return\n }\n chk(node.left, path.slice(0), res)\n chk(node.right, path.slice(0), res)\n}\n\nfunction numToChar(num) {\n const str = 'abcdefghijklmnopqrstuvwxyz'\n return str[num]\n}\n\nfunction arrToStr(arr) {\n let res = ''\n for(let i = 0; i < arr.length; i++) {\n res += numToChar(arr[i])\n }\n return res\n}\n\n// another\n\nconst smallestFromLeaf = function(root) {\n if (!root) return ''\n const char = String.fromCharCode(97 + root.val)\n let left = smallestFromLeaf(root.left)\n let right = smallestFromLeaf(root.right)\n if (!left) return right + char\n if (!right) return left + char\n return (left < right ? left : right) + char\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720ce0", + "questionid": 533, + "title": "Minimum Number of K Consecutive Bit Flips", + "slug": "minimum-number-of-k-consecutive-bit-flips", + "description": "You are given a binary array nums and an integer k. A k-bit flip is choosing a subarray of length k from nums and simultaneously changing every 0 in the subarray to 1, and every 1 in the subarray to 0. Return the minimum number of k-bit flips required so that there is no 0 in the array. If it is not possible, return -1. A subarray is a contiguous part of an array. ", + "category": [ + "Array", + "Bit Manipulation", + "Sliding Window", + "Prefix Sum" + ], + "complexity": "Hard", + "successrate": 50.7, + "totalsubmissions": 49867, + "totalaccepted": 25291, + "likes": 792, + "dislikes": 49, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [0,1,0], k = 1", + "expected_output": "2", + "explanation": "Flip nums[0], then flip nums[2]." + }, + { + "example_num": 2, + "expected_input": "nums = [1,1,0], k = 2", + "expected_output": "-1", + "explanation": "No matter how we flip subarrays of size 2, we cannot make the array become [1,1,1]." + }, + { + "example_num": 3, + "expected_input": "nums = [0,0,0,1,0,1,1,0], k = 3", + "expected_output": "3", + "explanation": "Flip nums[0],nums[1],nums[2]: nums becomes [1,1,1,1,0,1,1,0]\nFlip nums[4],nums[5],nums[6]: nums becomes [1,1,1,1,1,0,0,0]\nFlip nums[5],nums[6],nums[7]: nums becomes [1,1,1,1,1,1,1,1]" + } + ], + "solution": "/**\n * @param {number[]} nums\n * @param {number} k\n * @return {number}\n */\nconst minKBitFlips = function(nums, k) {\n let cur = 0, res = 0\n const n = nums.length\n for(let i = 0; i < n; i++) {\n if(i >= k && nums[i - k] === 2) cur--\n if(cur % 2 === nums[i]) {\n if(i + k > n) return -1\n nums[i] = 2\n cur++\n res++\n }\n }\n return res\n};\n\n// another\n\n/**\n * @param {number[]} A\n * @param {number} K\n * @return {number}\n */\nconst minKBitFlips = function(A, K) {\n let cur = 0, res = 0;\n for (let i = 0; i < A.length; ++i) {\n if (i >= K) cur -= (A[i - K] / 2) >> 0;\n if ((cur & 1 ^ A[i]) === 0) {\n if (i + K > A.length) return -1;\n A[i] += 2;\n cur++;\n res++;\n }\n }\n return res;\n};\n\n// another\n\n/**\n * @param {number[]} nums\n * @param {number} k\n * @return {number}\n */\nconst minKBitFlips = function(nums, k) {\n const n = nums.length, q = []\n let res = 0\n for(let i = 0; i < n; i++) {\n if(nums[i] === 0) {\n if(q.length === 0 || q.length % 2 === 0) {\n res++\n q.push(i + k - 1)\n }\n } else {\n if(q.length % 2 === 1) {\n res++\n q.push(i + k - 1)\n }\n }\n if(q.length && i >= q[0]) q.shift()\n }\n return q.length ? -1 : res\n};\n\n" + }, + { + "_id": "66f925ddfdfb8e1665720ce7", + "questionid": 540, + "title": "Clumsy Factorial", + "slug": "clumsy-factorial", + "description": "The factorial of a positive integer n is the product of all positive integers less than or equal to n. We make a clumsy factorial using the integers in decreasing order by swapping out the multiply operations for a fixed rotation of operations with multiply '*', divide '/', add '+', and subtract '-' in this order. However, these operations are still applied using the usual order of operations of arithmetic. We do all multiplication and division steps before any addition or subtraction steps, and multiplication and division steps are processed left to right. Additionally, the division that we use is floor division such that 10 * 9 / 8 = 90 / 8 = 11. Given an integer n, return the clumsy factorial of n. ", + "category": [ + "Math", + "Stack", + "Simulation" + ], + "complexity": "Medium", + "successrate": 54.7, + "totalsubmissions": 36299, + "totalaccepted": 19854, + "likes": 186, + "dislikes": 228, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 4", + "expected_output": "7", + "explanation": "7 = 4 * 3 / 2 + 1" + }, + { + "example_num": 2, + "expected_input": "n = 10", + "expected_output": "12", + "explanation": "12 = 10 * 9 / 8 + 7 - 6 * 5 / 4 + 3 - 2 * 1" + } + ], + "solution": "/**\n * @param {number} N\n * @return {number}\n */\nconst clumsy = function(N) {\n const ops = [\"*\", \"/\", \"+\", \"-\"];\n const arr = [];\n arr.push(N);\n for (let i = N - 1, idx = 0; i > 0; i--, idx++) {\n let op = ops[idx % 4];\n let arrIdx = arr.length - 1 < 0 ? 0 : arr.length - 1;\n switch (op) {\n case \"*\":\n arr[arrIdx] *= i;\n break;\n case \"/\":\n arr[arrIdx] = Math.floor(arr[arrIdx] / i);\n break;\n case \"+\":\n arr[0] += i;\n break;\n case \"-\":\n arr.push(i);\n break;\n }\n }\n\n let res = arr[0];\n for (let i = 1; i < arr.length; i++) {\n res -= arr[i];\n }\n return res;\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720ce8", + "questionid": 541, + "title": "Minimum Domino Rotations For Equal Row", + "slug": "minimum-domino-rotations-for-equal-row", + "description": "In a row of dominoes, tops[i] and bottoms[i] represent the top and bottom halves of the ith domino. (A domino is a tile with two numbers from 1 to 6 - one on each half of the tile.) We may rotate the ith domino, so that tops[i] and bottoms[i] swap values. Return the minimum number of rotations so that all the values in tops are the same, or all the values in bottoms are the same. If it cannot be done, return -1. ", + "category": [ + "Array", + "Greedy" + ], + "complexity": "Medium", + "successrate": 52.6, + "totalsubmissions": 337683, + "totalaccepted": 177735, + "likes": 2423, + "dislikes": 239, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "tops = [2,1,2,4,2,2], bottoms = [5,2,6,2,3,2]", + "expected_output": "2", + "explanation": "The first figure represents the dominoes as given by tops and bottoms: before we do any rotations.\nIf we rotate the second and fourth dominoes, we can make every value in the top row equal to 2, as indicated by the second figure." + }, + { + "example_num": 2, + "expected_input": "tops = [3,5,1,2,3], bottoms = [3,6,3,3,4]", + "expected_output": "-1", + "explanation": "In this case, it is not possible to rotate the dominoes to make one row of values equal." + } + ], + "solution": null + }, + { + "_id": "66f925ddfdfb8e1665720ce9", + "questionid": 542, + "title": "Construct Binary Search Tree from Preorder Traversal", + "slug": "construct-binary-search-tree-from-preorder-traversal", + "description": "Given an array of integers preorder, which represents the preorder traversal of a BST (i.e., binary search tree), construct the tree and return its root. It is guaranteed that there is always possible to find a binary search tree with the given requirements for the given test cases. A binary search tree is a binary tree where for every node, any descendant of Node.left has a value strictly less than Node.val, and any descendant of Node.right has a value strictly greater than Node.val. A preorder traversal of a binary tree displays the value of the node first, then traverses Node.left, then traverses Node.right. ", + "category": [ + "Array", + "Stack", + "Tree", + "Binary Search Tree", + "Monotonic Stack", + "Binary Tree" + ], + "complexity": "Medium", + "successrate": 80.2, + "totalsubmissions": 287043, + "totalaccepted": 230198, + "likes": 3543, + "dislikes": 60, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "preorder = [8,5,1,7,10,12]", + "expected_output": "[8,5,10,1,7,null,12]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "preorder = [1,3]", + "expected_output": "[1,null,3]", + "explanation": "" + } + ], + "solution": "/**\n * Definition for a binary tree node.\n * function TreeNode(val) {\n * this.val = val;\n * this.left = this.right = null;\n * }\n */\n/**\n * @param {number[]} preorder\n * @return {TreeNode}\n */\nconst bstFromPreorder = function(preorder) {\n let i = 0;\n return bstFromPreorder(preorder, Number.MAX_VALUE);\n function bstFromPreorder(A, bound) {\n if (i === A.length || A[i] > bound) return null;\n let root = new TreeNode(A[i++]);\n root.left = bstFromPreorder(A, root.val);\n root.right = bstFromPreorder(A, bound);\n return root;\n }\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720cec", + "questionid": 545, + "title": "Capacity To Ship Packages Within D Days", + "slug": "capacity-to-ship-packages-within-d-days", + "description": "A conveyor belt has packages that must be shipped from one port to another within days days. The ith package on the conveyor belt has a weight of weights[i]. Each day, we load the ship with packages on the conveyor belt (in the order given by weights). We may not load more weight than the maximum weight capacity of the ship. Return the least weight capacity of the ship that will result in all the packages on the conveyor belt being shipped within days days. ", + "category": [ + "Array", + "Binary Search", + "Greedy" + ], + "complexity": "Medium", + "successrate": 63.5, + "totalsubmissions": 225076, + "totalaccepted": 142938, + "likes": 4119, + "dislikes": 94, + "hints": "Binary search on the answer. We need a function possible(capacity) which returns true if and only if we can do the task in D days.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "weights = [1,2,3,4,5,6,7,8,9,10], days = 5", + "expected_output": "15", + "explanation": "A ship capacity of 15 is the minimum to ship all the packages in 5 days like this:\n1st day: 1, 2, 3, 4, 5\n2nd day: 6, 7\n3rd day: 8\n4th day: 9\n5th day: 10\n\nNote that the cargo must be shipped in the order given, so using a ship of capacity 14 and splitting the packages into parts like (2, 3, 4, 5), (1, 6, 7), (8), (9), (10) is not allowed." + }, + { + "example_num": 2, + "expected_input": "weights = [3,2,2,4,1,4], days = 3", + "expected_output": "6", + "explanation": "A ship capacity of 6 is the minimum to ship all the packages in 3 days like this:\n1st day: 3, 2\n2nd day: 2, 4\n3rd day: 1, 4" + }, + { + "example_num": 3, + "expected_input": "weights = [1,2,3,1,1], days = 4", + "expected_output": "3", + "explanation": "1st day: 1\n2nd day: 2\n3rd day: 3\n4th day: 1, 1" + } + ], + "solution": "/**\n * @param {number[]} weights\n * @param {number} days\n * @return {number}\n */\nconst shipWithinDays = function(weights, days) {\n let l = Math.max(...weights)\n let r = weights.reduce((ac, e) => ac + e, 0)\n while(l < r) {\n const mid = Math.floor((l + r) / 2)\n if(valid(mid)) {\n r = mid\n } else l = mid + 1\n }\n \n return l\n \n function valid(mid) {\n let res = 1, cur = 0\n for(let w of weights) {\n if(cur + w > mid) {\n cur = 0\n res++\n }\n cur += w\n }\n return res <= days\n }\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720cef", + "questionid": 548, + "title": "Binary String With Substrings Representing 1 To N", + "slug": "binary-string-with-substrings-representing-1-to-n", + "description": "Given a binary string s and a positive integer n, return true if the binary representation of all the integers in the range [1, n] are substrings of s, or false otherwise. A substring is a contiguous sequence of characters within a string. ", + "category": [ + "String" + ], + "complexity": "Medium", + "successrate": 57.9, + "totalsubmissions": 49096, + "totalaccepted": 28428, + "likes": 247, + "dislikes": 453, + "hints": "We only need to check substrings of length at most 30, because 10^9 has 30 bits.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = \"0110\", n = 3", + "expected_output": "true", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "s = \"0110\", n = 4", + "expected_output": "false", + "explanation": "" + } + ], + "solution": "/**\n * @param {string} S\n * @param {number} N\n * @return {boolean}\n */\nconst queryString = function(S, N) {\n for(let i = 1; i <= N; i++) {\n let tmp = bin(i)\n if(S.indexOf(tmp) === -1) return false\n }\n return true\n};\n\nfunction bin(num) {\n return (num >>> 0).toString(2)\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720cf3", + "questionid": 552, + "title": "Number of Enclaves", + "slug": "number-of-enclaves", + "description": "You are given an m x n binary matrix grid, where 0 represents a sea cell and 1 represents a land cell. A move consists of walking from one land cell to another adjacent (4-directionally) land cell or walking off the boundary of the grid. Return the number of land cells in grid for which we cannot walk off the boundary of the grid in any number of moves. ", + "category": [ + "Array", + "Depth-First Search", + "Breadth-First Search", + "Union Find", + "Matrix" + ], + "complexity": "Medium", + "successrate": 62.6, + "totalsubmissions": 82170, + "totalaccepted": 51438, + "likes": 1172, + "dislikes": 32, + "hints": "Can you model this problem as a graph problem? Create n * m + 1 nodes where n * m nodes represents each cell of the map and one extra node to represent the exterior of the map. In the map add edges between neighbors on land cells. And add edges between the exterior and land nodes which are in the boundary.\r\nReturn as answer the number of nodes that are not reachable from the exterior node.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "grid = [[0,0,0,0],[1,0,1,0],[0,1,1,0],[0,0,0,0]]", + "expected_output": "3", + "explanation": "There are three 1s that are enclosed by 0s, and one 1 that is not enclosed because its on the boundary." + }, + { + "example_num": 2, + "expected_input": "grid = [[0,1,1,0],[0,0,1,0],[0,0,1,0],[0,0,0,0]]", + "expected_output": "0", + "explanation": "All 1s are either on the boundary or can reach the boundary." + } + ], + "solution": "/**\n * @param {number[][]} A\n * @return {number}\n */\nconst numEnclaves = function(A) {\n let res = 0\n const dirs = [[-1, 0], [1, 0], [0, 1], [0, -1]]\n const visited = Array.from({ length: A.length }, () =>\n new Array(A[0].length).fill(false)\n )\n for (let row = 0; row < A.length; row++) {\n for (let col = 0; A[0] && col < A[0].length; col++) {\n if (\n (row === 0 ||\n col === 0 ||\n row === A.length - 1 ||\n col === A[0].length - 1) &&\n A[row][col] === 1\n ) {\n dfs(A, row, col, visited, dirs)\n }\n }\n }\n for (let row = 0; row < A.length; row++) {\n for (let col = 0; A[0] && col < A[0].length; col++) {\n if (A[row][col] === 1) {\n res += 1\n }\n }\n }\n return res\n}\n\nfunction dfs(A, row, col, v, dirs) {\n if (\n row < 0 ||\n row >= A.length ||\n col < 0 ||\n col >= A[0].length ||\n v[row][col] ||\n A[row][col] === 0\n )\n return\n\n v[row][col] = true\n A[row][col] = 0\n\n for (let dir of dirs) {\n dfs(A, row + dir[0], col + dir[1], v, dirs)\n }\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720cf6", + "questionid": 555, + "title": "Video Stitching", + "slug": "video-stitching", + "description": "You are given a series of video clips from a sporting event that lasted time seconds. These video clips can be overlapping with each other and have varying lengths. Each video clip is described by an array clips where clips[i] = [starti, endi] indicates that the ith clip started at starti and ended at endi. We can cut these clips into segments freely. Return the minimum number of clips needed so that we can cut the clips into segments that cover the entire sporting event [0, time]. If the task is impossible, return -1. ", + "category": [ + "Array", + "Dynamic Programming", + "Greedy" + ], + "complexity": "Medium", + "successrate": 50, + "totalsubmissions": 92645, + "totalaccepted": 46356, + "likes": 1179, + "dislikes": 47, + "hints": "What if we sort the intervals? Considering the sorted intervals, how can we solve the problem with dynamic programming? Let's consider a DP(pos, limit) where pos represents the position of the current interval we are gonna take the decision and limit is the current covered area from [0 - limit]. This DP returns the minimum number of taken intervals or infinite if it's not possible to cover the [0 - T] section.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "clips = [[0,2],[4,6],[8,10],[1,9],[1,5],[5,9]], time = 10", + "expected_output": "3", + "explanation": "We take the clips [0,2], [8,10], [1,9]; a total of 3 clips.\nThen, we can reconstruct the sporting event as follows:\nWe cut [1,9] into segments [1,2] + [2,8] + [8,9].\nNow we have segments [0,2] + [2,8] + [8,10] which cover the sporting event [0, 10]." + }, + { + "example_num": 2, + "expected_input": "clips = [[0,1],[1,2]], time = 5", + "expected_output": "-1", + "explanation": "We cannot cover [0,5] with only [0,1] and [1,2]." + }, + { + "example_num": 3, + "expected_input": "clips = [[0,1],[6,8],[0,2],[5,6],[0,4],[0,3],[6,7],[1,3],[4,7],[1,4],[2,5],[2,6],[3,4],[4,5],[5,7],[6,9]], time = 9", + "expected_output": "3", + "explanation": "We can take clips [0,4], [4,7], and [6,9]." + } + ], + "solution": "/**\n * @param {number[][]} clips\n * @param {number} time\n * @return {number}\n */\nconst videoStitching = function(clips, time) {\n const n = clips.length\n if(time === 0) return 0\n clips.sort((a, b) => a[0] === b[0] ? b[1] - a[1] : a[0] - b[0])\n let res = 0, start = 0, end = 0, nextEnd = 0, idx = 0\n\n while(idx < n) {\n nextEnd = end\n while(idx < n && clips[idx][0] <= end) {\n nextEnd = Math.max(nextEnd, clips[idx][1])\n idx++\n }\n res++\n if(nextEnd >= time) return res\n else if(nextEnd === end) return -1\n else {\n end = nextEnd \n }\n }\n\n return -1\n\n};\n\n// anonther\n\n/**\n * @param {number[][]} clips\n * @param {number} T\n * @return {number}\n */\nconst videoStitching = function (clips, T) {\n clips.sort((a, b) => a[0] - b[0])\n if(T === 0) return 0\n let laststart = -1,\n curend = 0,\n count = 0\n for (let i = 0; i < clips.length; ) {\n if (clips[i][0] > curend) return -1\n let maxend = curend\n // while one clip's start is before or equal to current end\n while (i < clips.length && clips[i][0] <= curend) {\n maxend = Math.max(maxend, clips[i][1])\n i++\n }\n count++\n curend = maxend\n if (curend >= T) return count\n }\n return -1\n}\n\n// another\n\n/**\n * @param {number[][]} clips\n * @param {number} T\n * @return {number}\n */\nconst videoStitching = function (clips, T) {\n clips.sort((a, b) => a[0] - b[0])\n let res = 0\n for(let i = 0, start = 0, end = 0, len = clips.length; start < T; start = end, res++) {\n for(; i < len && clips[i][0] <= start; i++) {\n end = Math.max(end, clips[i][1])\n }\n if(start === end) return -1\n }\n return res\n}\n\n\n// another\n\n/**\n * @param {number[][]} clips\n * @param {number} T\n * @return {number}\n */\nconst videoStitching = function (clips, T) {\n const dp = Array(T + 1).fill( T + 1 )\n dp[0] = 0\n for(let i = 0; i <= T; i++) {\n for(let c of clips) {\n if(i >= c[0] && i <= c[1]) dp[i] = Math.min(dp[i], dp[c[0]] + 1)\n }\n if(dp[i] === T + 1) return -1\n }\n return dp[T]\n}\n\n\n" + }, + { + "_id": "66f925ddfdfb8e1665720cf7", + "questionid": 556, + "title": "Longest Arithmetic Subsequence", + "slug": "longest-arithmetic-subsequence", + "description": "Given an array nums of integers, return the length of the longest arithmetic subsequence in nums. Recall that a subsequence of an array nums is a list nums[i1], nums[i2], ..., nums[ik] with 0 <= i1 < i2 < ... < ik <= nums.length - 1, and that a sequence seq is arithmetic if seq[i+1] - seq[i] are all the same value (for 0 <= i < seq.length - 1). ", + "category": [ + "Array", + "Hash Table", + "Binary Search", + "Dynamic Programming" + ], + "complexity": "Medium", + "successrate": 48.2, + "totalsubmissions": 175733, + "totalaccepted": 84715, + "likes": 2049, + "dislikes": 97, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [3,6,9,12]", + "expected_output": "4\nExplanation: The whole array is an arithmetic sequence with steps of length = 3.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "nums = [9,4,7,2,10]", + "expected_output": "3\nExplanation: The longest arithmetic subsequence is [4,7,10].", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "nums = [20,1,15,3,10,5,8]", + "expected_output": "4\nExplanation: The longest arithmetic subsequence is [20,15,10,5].", + "explanation": "" + } + ], + "solution": null + }, + { + "_id": "66f925ddfdfb8e1665720cfb", + "questionid": 560, + "title": "Maximum Sum of Two Non-Overlapping Subarrays", + "slug": "maximum-sum-of-two-non-overlapping-subarrays", + "description": "Given an integer array nums and two integers firstLen and secondLen, return the maximum sum of elements in two non-overlapping subarrays with lengths firstLen and secondLen. The array with length firstLen could occur before or after the array with length secondLen, but they have to be non-overlapping. A subarray is a contiguous part of an array. ", + "category": [ + "Array", + "Dynamic Programming", + "Sliding Window" + ], + "complexity": "Medium", + "successrate": 59.4, + "totalsubmissions": 82510, + "totalaccepted": 49020, + "likes": 1660, + "dislikes": 70, + "hints": "We can use prefix sums to calculate any subarray sum quickly.\r\nFor each L length subarray, find the best possible M length subarray that occurs before and after it.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [0,6,5,2,2,5,1,9,4], firstLen = 1, secondLen = 2", + "expected_output": "20", + "explanation": "One choice of subarrays is [9] with length 1, and [6,5] with length 2." + }, + { + "example_num": 2, + "expected_input": "nums = [3,8,1,3,2,1,8,9,0], firstLen = 3, secondLen = 2", + "expected_output": "29", + "explanation": "One choice of subarrays is [3,8,1] with length 3, and [8,9] with length 2." + }, + { + "example_num": 3, + "expected_input": "nums = [2,1,5,6,0,9,5,0,3,8], firstLen = 4, secondLen = 3", + "expected_output": "31", + "explanation": "One choice of subarrays is [5,6,0,9] with length 4, and [0,3,8] with length 3." + } + ], + "solution": "/**\n * @param {number[]} A\n * @param {number} L\n * @param {number} M\n * @return {number}\n */\nconst maxSumTwoNoOverlap = function(A, L, M) {\n for(let i = 1, len = A.length; i < len; i++) {\n A[i] += A[i - 1]\n }\n let LMax = A[L - 1], MMax = A[M - 1], res = A[L + M - 1]\n for(let i = L + M, len = A.length; i < len; i++) {\n LMax = Math.max(LMax, A[i - M] - A[i - M - L])\n MMax = Math.max(MMax, A[i - L] - A[i - M - L])\n res = Math.max(res, Math.max(LMax + A[i] - A[i - M], MMax + A[i] - A[i - L]))\n }\n return res\n}\n\n// another\n\nconst maxSumTwoNoOverlap = function(A, L, M) {\n let n = A.length\n let sum = []\n sum[0] = 0\n for (let i = 0; i < n; i++) sum[i + 1] = sum[i] + A[i]\n\n let ans = 0\n for (let i = L - 1; i + M < n; ++i) {\n for (let j = i + 1; j + M - 1 < n; ++j) {\n ans = Math.max(ans, sum[i + 1] - sum[i - L + 1] + sum[j + M] - sum[j])\n }\n }\n let tmp = L\n L = M\n M = tmp\n for (let i = L - 1; i + M < n; ++i) {\n for (let j = i + 1; j + M - 1 < n; ++j) {\n ans = Math.max(ans, sum[i + 1] - sum[i - L + 1] + sum[j + M] - sum[j])\n }\n }\n return ans\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720cff", + "questionid": 564, + "title": "Find Words That Can Be Formed by Characters", + "slug": "find-words-that-can-be-formed-by-characters", + "description": "You are given an array of strings words and a string chars. A string is good if it can be formed by characters from chars (each character can only be used once). Return the sum of lengths of all good strings in words. ", + "category": [ + "Array", + "Hash Table", + "String" + ], + "complexity": "Easy", + "successrate": 67.7, + "totalsubmissions": 165666, + "totalaccepted": 112147, + "likes": 959, + "dislikes": 120, + "hints": "Solve the problem for each string in words independently. Now try to think in frequency of letters. Count how many times each character occurs in string chars. To form a string using characters from chars, the frequency of each character in chars must be greater than or equal the frequency of that character in the string to be formed.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "words = ["cat","bt","hat","tree"], chars = "atach"", + "expected_output": "6", + "explanation": "The strings that can be formed are "cat" and "hat" so the answer is 3 + 3 = 6." + }, + { + "example_num": 2, + "expected_input": "words = ["hello","world","leetcode"], chars = "welldonehoneyr"", + "expected_output": "10", + "explanation": "The strings that can be formed are "hello" and "world" so the answer is 5 + 5 = 10." + } + ], + "solution": "/**\n * @param {string[]} words\n * @param {string} chars\n * @return {number}\n */\nconst countCharacters = function(words, chars) {\n let letters = new Array(26).fill(0),\n a = 'a'.charCodeAt(0),\n z = 'z'.charCodeAt(0)\n let count = 0\n for (let i = 0; i < chars.length; i++) {\n let l = chars[i].charCodeAt(0) - a\n letters[l]++\n }\n for (let i = 0; i < words.length; i++) {\n let word = words[i]\n let tmp = letters.slice()\n let tCount = 0\n for (let j = 0; j < word.length; j++) {\n let l = word[j].charCodeAt(0) - a\n tmp[l]--\n if (tmp[l] < 0) {\n break\n } else {\n tCount++\n }\n }\n if (tCount == word.length) {\n count += word.length\n }\n }\n return count\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720d05", + "questionid": 570, + "title": "Longest String Chain", + "slug": "longest-string-chain", + "description": "You are given an array of words where each word consists of lowercase English letters. wordA is a predecessor of wordB if and only if we can insert exactly one letter anywhere in wordA without changing the order of the other characters to make it equal to wordB. A word chain is a sequence of words [word1, word2, ..., wordk] with k >= 1, where word1 is a predecessor of word2, word2 is a predecessor of word3, and so on. A single word is trivially a word chain with k == 1. Return the length of the longest possible word chain with words chosen from the given list of words. ", + "category": [ + "Array", + "Hash Table", + "Two Pointers", + "String", + "Dynamic Programming" + ], + "complexity": "Medium", + "successrate": 57.8, + "totalsubmissions": 338994, + "totalaccepted": 195915, + "likes": 3279, + "dislikes": 161, + "hints": "Instead of adding a character, try deleting a character to form a chain in reverse. For each word in order of length, for each word2 which is word with one character removed, length[word2] = max(length[word2], length[word] + 1).", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "words = ["a","b","ba","bca","bda","bdca"]", + "expected_output": "4\nExplanation: One of the longest word chains is ["a","ba","bda","bdca"].", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "words = ["xbc","pcxbcf","xb","cxbc","pcxbc"]", + "expected_output": "5", + "explanation": "All the words can be put in a word chain ["xb", "xbc", "cxbc", "pcxbc", "pcxbcf"]." + }, + { + "example_num": 3, + "expected_input": "words = ["abcd","dbqca"]", + "expected_output": "1", + "explanation": "The trivial word chain ["abcd"] is one of the longest word chains.\n["abcd","dbqca"] is not a valid word chain because the ordering of the letters is changed." + } + ], + "solution": "/**\n * @param {string[]} words\n * @return {number}\n */\nconst longestStrChain = function(words) {\n words.sort((a, b) => a.length - b.length)\n const dp = {}\n for(let el of words) {\n dp[el] = 1\n }\n \n let res = Number.MIN_VALUE\n for(let w of words) {\n for(let i = 0; i < w.length; i++) {\n let prev = w.slice(0, i) + w.slice(i + 1)\n dp[w] = Math.max(dp[w], (dp[prev] || 0) + 1 )\n }\n if(dp[w] > res) res = dp[w]\n }\n return res\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720d07", + "questionid": 572, + "title": "Height Checker", + "slug": "height-checker", + "description": "A school is trying to take an annual photo of all the students. The students are asked to stand in a single file line in non-decreasing order by height. Let this ordering be represented by the integer array expected where expected[i] is the expected height of the ith student in line. You are given an integer array heights representing the current order that the students are standing in. Each heights[i] is the height of the ith student in line (0-indexed). Return the number of indices where heights[i] != expected[i]. ", + "category": [ + "Array", + "Sorting", + "Counting Sort" + ], + "complexity": "Easy", + "successrate": 74.3, + "totalsubmissions": 262388, + "totalaccepted": 194845, + "likes": 428, + "dislikes": 47, + "hints": "Build the correct order of heights by sorting another array, then compare the two arrays.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "heights = [1,1,4,2,1,3]", + "expected_output": "3", + "explanation": "heights: [1,1,4,2,1,3]\nexpected: [1,1,1,2,3,4]\nIndices 2, 4, and 5 do not match." + }, + { + "example_num": 2, + "expected_input": "heights = [5,1,2,3,4]", + "expected_output": "5", + "explanation": "heights: [5,1,2,3,4]\nexpected: [1,2,3,4,5]\nAll indices do not match." + }, + { + "example_num": 3, + "expected_input": "heights = [1,2,3,4,5]", + "expected_output": "0", + "explanation": "heights: [1,2,3,4,5]\nexpected: [1,2,3,4,5]\nAll indices match." + } + ], + "solution": "/**\n * @param {number[]} heights\n * @return {number}\n */\nconst heightChecker = function(heights) {\n const arr = heights.slice(0).sort((a, b) => a - b)\n let res = 0\n for(let i = 0, len = heights.length; i < len; i++) {\n if(arr[i] !== heights[i]) res++\n }\n \n return res\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720d0a", + "questionid": 575, + "title": "Distant Barcodes", + "slug": "distant-barcodes", + "description": "In a warehouse, there is a row of barcodes, where the ith barcode is barcodes[i]. Rearrange the barcodes so that no two adjacent barcodes are equal. You may return any answer, and it is guaranteed an answer exists. ", + "category": [ + "Array", + "Hash Table", + "Greedy", + "Sorting", + "Heap (Priority Queue)", + "Counting" + ], + "complexity": "Medium", + "successrate": 45.2, + "totalsubmissions": 65587, + "totalaccepted": 29644, + "likes": 828, + "dislikes": 36, + "hints": "We want to always choose the most common or second most common element to write next. What data structure allows us to query this effectively?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "barcodes = [1,1,1,2,2,2]", + "expected_output": "[2,1,2,1,2,1]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "barcodes = [1,1,1,1,2,2,3,3]", + "expected_output": "[1,3,1,3,1,2,1,2]", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} barcodes\n * @return {number[]}\n */\nconst rearrangeBarcodes = function(barcodes) {\n const hash = {}\n let maxFreq = 0, max = 0\n for(const e of barcodes) {\n if(hash[e] == null) hash[e] = 0\n hash[e]++\n if(hash[e] > maxFreq) {\n maxFreq = hash[e]\n max = e\n }\n }\n const n = barcodes.length\n const entries = Object.entries(hash)\n const res = Array(n)\n let idx = 0\n while(maxFreq) {\n res[idx] = max\n idx += 2\n maxFreq--\n }\n for(let [v, f] of entries) {\n if(+v === max) continue\n while(f) {\n if(idx >= n) idx = 1\n res[idx] = +v\n idx += 2\n f--\n }\n }\n \n return res\n};\n\n// another\n\n/**\n * @param {number[]} barcodes\n * @return {number[]}\n */\nconst rearrangeBarcodes = function(barcodes) {\n\tconst map = {};\n\tbarcodes.forEach(b => map[b] = (map[b] || 0) + 1);\n\tconst keys = Object.keys(map).sort((k1, k2) => map[k1] - map[k2]);\n\n\tlet idx = 1;\n\tfor (let k of keys) {\n\t\tlet t = map[k];\n\n\t\tfor (let i = 0; i < t; i++) {\n\t\t\tif (idx >= barcodes.length) idx = 0;\n\t\t\tbarcodes[idx] = k;\n\t\t\tidx += 2;\n\t\t}\n\t}\n\n\treturn barcodes;\n};\n\n// another\n\n/**\n * @param {number[]} barcodes\n * @return {number[]}\n */\nconst rearrangeBarcodes = function(barcodes) {\n const hash = {}, n = barcodes.length\n for(let e of barcodes) {\n if(hash[e] == null) hash[e] = 0\n hash[e]++\n }\n const res = Array(n)\n let max = 0, idx = -1\n for(let k in hash) {\n if(hash[k] > max) {\n max = hash[k]\n idx = +k\n }\n }\n let i = 0\n // max freq first\n while(max > 0) {\n res[i] = idx\n max--\n i += 2\n }\n // the rest\n const keys = Object.keys(hash).map(e => +e)\n for(let j = 0, len = keys.length; j < len; j++) {\n if(keys[j] !== idx) {\n const k = keys[j]\n let freq = hash[k]\n while(freq > 0) {\n if(i >= n) i = 1\n res[i] = k\n freq--\n i += 2\n }\n }\n }\n \n return res\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720d0f", + "questionid": 580, + "title": "Smallest Subsequence of Distinct Characters", + "slug": "smallest-subsequence-of-distinct-characters", + "description": "Given a string s, return the lexicographically smallest subsequence of s that contains all the distinct characters of s exactly once. ", + "category": [ + "String", + "Stack", + "Greedy", + "Monotonic Stack" + ], + "complexity": "Medium", + "successrate": 56.8, + "totalsubmissions": 66954, + "totalaccepted": 38059, + "likes": 1618, + "dislikes": 142, + "hints": "Greedily try to add one missing character. How to check if adding some character will not cause problems ? Use bit-masks to check whether you will be able to complete the sub-sequence if you add the character at some index i.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "bcabc"", + "expected_output": ""abc"", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "s = "cbacdcbc"", + "expected_output": ""acdb"", + "explanation": "" + } + ], + "solution": "/**\n * @param {string} text\n * @return {string}\n */\nconst smallestSubsequence = function(text) {\n if (text === '') return ''\n let counter = new Array(128).fill(0)\n for (let i = 0; i < text.length; i++) counter[text.charCodeAt(i)]++\n let minChar = 128\n let minIndex = 0\n for (let i = 0; i < text.length; i++) {\n let c = text.charCodeAt(i)\n if (c < minChar) {\n minChar = c\n minIndex = i\n }\n if (--counter[c] === 0) {\n return (\n String.fromCharCode(minChar) +\n smallestSubsequence(\n text\n .slice(minIndex + 1)\n .replace(new RegExp(String.fromCharCode(minChar), 'g'), '')\n )\n )\n }\n }\n return ''\n}\n\n// another\n\n/**\n * @param {string} text\n * @return {string}\n */\nconst smallestSubsequence = function(s) {\n let res = []\n const count = new Array(26).fill(0)\n const used = new Array(26).fill(0)\n const aCode = 'a'.charCodeAt(0)\n for (let el of s) count[el.charCodeAt(0) - aCode]++\n for (let el of s) {\n count[el.charCodeAt(0) - aCode]--\n if (used[el.charCodeAt(0) - aCode]++ > 0) continue\n while (\n res.length &&\n res[res.length - 1].charCodeAt(0) > el.charCodeAt(0) &&\n count[res[res.length - 1].charCodeAt(0) - aCode] > 0\n ) {\n used[res[res.length - 1].charCodeAt(0) - aCode] = 0\n res.pop()\n }\n res.push(el)\n }\n return res.join('') \n};\n\n// anoother\n\n\n/**\n * @param {string} text\n * @return {string}\n */\nconst smallestSubsequence = function(text) {\n const n = text.length, stack = [], last = {}, visited = {}\n for(let i = 0; i < n; i++) last[text[i]] = i\n for(let i = 0; i < n; i++) {\n const ch = text[i]\n if (visited[ch]) continue\n while(stack.length && stack[stack.length - 1] > ch && last[stack[stack.length - 1]] > i) {\n visited[stack[stack.length - 1]] = 0\n stack.pop()\n }\n visited[ch] = 1\n stack.push(ch)\n }\n\n return stack.join('')\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720d11", + "questionid": 582, + "title": "Duplicate Zeros", + "slug": "duplicate-zeros", + "description": "Given a fixed-length integer array arr, duplicate each occurrence of zero, shifting the remaining elements to the right. Note that elements beyond the length of the original array are not written. Do the above modifications to the input array in place and do not return anything. ", + "category": [ + "Array", + "Two Pointers" + ], + "complexity": "Easy", + "successrate": 51.1, + "totalsubmissions": 509601, + "totalaccepted": 260589, + "likes": 1624, + "dislikes": 522, + "hints": "This is a great introductory problem for understanding and working with the concept of in-place operations. The problem statement clearly states that we are to modify the array in-place. That does not mean we cannot use another array. We just don't have to return anything. A better way to solve this would be without using additional space. The only reason the problem statement allows you to make modifications in place is that it hints at avoiding any additional memory. The main problem with not using additional memory is that we might override elements due to the zero duplication requirement of the problem statement. How do we get around that? If we had enough space available, we would be able to accommodate all the elements properly. The new length would be the original length of the array plus the number of zeros. Can we use this information somehow to solve the problem?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "arr = [1,0,2,3,0,4,5,0]", + "expected_output": "[1,0,0,2,3,0,0,4]", + "explanation": "After calling your function, the input array is modified to: [1,0,0,2,3,0,0,4]" + }, + { + "example_num": 2, + "expected_input": "arr = [1,2,3]", + "expected_output": "[1,2,3]", + "explanation": "After calling your function, the input array is modified to: [1,2,3]" + } + ], + "solution": "/**\n * @param {number[]} arr\n * @return {void} Do not return anything, modify arr in-place instead.\n */\nconst duplicateZeros = function(arr) {\n const len = arr.length\n for (let i = len - 1; i >= 0; i--) {\n if (arr[i] === 0) arr.splice(i, 0, 0)\n }\n while (arr.length > len) {\n arr.pop()\n }\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720d14", + "questionid": 585, + "title": "Path In Zigzag Labelled Binary Tree", + "slug": "path-in-zigzag-labelled-binary-tree", + "description": "In an infinite binary tree where every node has two children, the nodes are labelled in row order. In the odd numbered rows (ie., the first, third, fifth,...), the labelling is left to right, while in the even numbered rows (second, fourth, sixth,...), the labelling is right to left. Given the label of a node in this tree, return the labels in the path from the root of the tree to the\u00a0node with that label. ", + "category": [ + "Math", + "Tree", + "Binary Tree" + ], + "complexity": "Medium", + "successrate": 74.5, + "totalsubmissions": 43751, + "totalaccepted": 32604, + "likes": 953, + "dislikes": 261, + "hints": "Based on the label of the current node, find what the label must be for the parent of that node.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "label = 14", + "expected_output": "[1,3,4,14]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "label = 26", + "expected_output": "[1,2,6,10,26]", + "explanation": "" + } + ], + "solution": null + }, + { + "_id": "66f925ddfdfb8e1665720d16", + "questionid": 587, + "title": "Defanging an IP Address", + "slug": "defanging-an-ip-address", + "description": "Given a valid (IPv4) IP address, return a defanged version of that IP address. A defanged\u00a0IP address\u00a0replaces every period \".\" with \"[.]\". ", + "category": [ + "String" + ], + "complexity": "Easy", + "successrate": 89, + "totalsubmissions": 450803, + "totalaccepted": 401039, + "likes": 1072, + "dislikes": 1457, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "address = \"1.1.1.1\"", + "expected_output": "\"1[.]1[.]1[.]1\"", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "address = \"255.100.50.0\"", + "expected_output": "\"255[.]100[.]50[.]0\"", + "explanation": "" + } + ], + "solution": "/**\n * @param {string} address\n * @return {string}\n */\nconst defangIPaddr = function(address) {\n return address.split('.').join('[.]')\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720d1d", + "questionid": 594, + "title": "Element Appearing More Than 25% In Sorted Array", + "slug": "element-appearing-more-than-25-in-sorted-array", + "description": "Given an integer array sorted in non-decreasing order, there is exactly one integer in the array that occurs more than 25% of the time, return that integer. ", + "category": [ + "Array" + ], + "complexity": "Easy", + "successrate": 59.5, + "totalsubmissions": 103670, + "totalaccepted": 61720, + "likes": 636, + "dislikes": 36, + "hints": "Divide the array in four parts [1 - 25%] [25 - 50 %] [50 - 75 %] [75% - 100%] The answer should be in one of the ends of the intervals. In order to check which is element is the answer we can count the frequency with binarySearch.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "arr = [1,2,2,6,6,6,6,7,10]", + "expected_output": "6", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "arr = [1,1]", + "expected_output": "1", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} arr\n * @return {number}\n */\nconst findSpecialInteger = function (arr) {\n const n = arr.length,\n { floor } = Math,\n { getWordIndexRange } = Search()\n const ticks = [n / 4, n / 2, (n * 3) / 4].map((e) => floor(e))\n for (const i of ticks) {\n const [s, e] = getWordIndexRange(arr, arr[i])\n if (e - s > n / 4) return arr[i]\n }\n return 0\n}\n\nfunction Search() {\n return { getWordIndexRange }\n\n /**\n * Searches for the first true value in the predicate.\n * Returns hi if not found.\n * [lo, hi)\n */\n function binarySearch(lo, hi, predicate) {\n while (lo != hi) {\n let mid = ((lo + hi) / 2) | 0\n if (predicate(mid)) {\n hi = mid\n } else {\n lo = mid + 1\n }\n }\n return lo\n }\n\n function getWordIndexRange(keys, word) {\n let lo = 0,\n hi = keys.length\n function greaterOrEqual(index) {\n return keys[index] >= word\n }\n function less(index) {\n return keys[index] > word\n }\n let lower_bound = binarySearch(0, keys.length, greaterOrEqual)\n let upper_bound = binarySearch(lower_bound, keys.length, less)\n return [lower_bound, upper_bound]\n }\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720d22", + "questionid": 599, + "title": "Sum of Mutated Array Closest to Target", + "slug": "sum-of-mutated-array-closest-to-target", + "description": "Given an integer array arr and a target value target, return the integer value such that when we change all the integers larger than value in the given array to be equal to value, the sum of the array gets as close as possible (in absolute difference) to target. In case of a tie, return the minimum such integer. Notice that the answer is not neccesarilly a number from arr. ", + "category": [ + "Array", + "Binary Search", + "Sorting" + ], + "complexity": "Medium", + "successrate": 42.5, + "totalsubmissions": 57122, + "totalaccepted": 24305, + "likes": 736, + "dislikes": 89, + "hints": "If you draw a graph with the value on one axis and the absolute difference between the target and the array sum, what will you get? That graph is uni-modal. Use ternary search on that graph to find the best value.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "arr = [4,9,3], target = 10", + "expected_output": "3", + "explanation": "When using 3 arr converts to [3, 3, 3] which sums 9 and that's the optimal answer." + }, + { + "example_num": 2, + "expected_input": "arr = [2,3,5], target = 10", + "expected_output": "5", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "arr = [60864,25176,27249,21296,20204], target = 56803", + "expected_output": "11361", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} arr\n * @param {number} target\n * @return {number}\n */\nconst findBestValue = function(arr, target) {\n let l, r, mi, s = 0, m = -1;\n for(let v of arr) { s += v; m = Math.max(m, v); }\n if(s <= target) return m; \n\n for(l = 1, r = m; l < r;) {\n mi = ~~((l+r)/2);\n s = 0;\n for(let v of arr) s += (v > mi) ? mi : v;\n if(s >= target) r = mi;\n else l = mi + 1;\n }\n // check if we are 1 step off the target \n let s1=0,s2=0;\n for(let v of arr) {\n s1 += (v>l)?(l):v;\n s2 += (v>l-1)?(l-1):v;\n }\n\n return (Math.abs(s2-target) <= Math.abs(s1-target)) ? l-1 : l;\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720d23", + "questionid": 600, + "title": "Largest 1-Bordered Square", + "slug": "largest-1-bordered-square", + "description": "Given a 2D grid of 0s and 1s, return the number of elements in\u00a0the largest square\u00a0subgrid that has all 1s on its border, or 0 if such a subgrid\u00a0doesn't exist in the grid. ", + "category": [ + "Array", + "Dynamic Programming", + "Matrix" + ], + "complexity": "Medium", + "successrate": 49.6, + "totalsubmissions": 36636, + "totalaccepted": 18158, + "likes": 492, + "dislikes": 82, + "hints": "For each square, know how many ones are up, left, down, and right of this square. You can find it in O(N^2) using dynamic programming. Now for each square ( O(N^3) ), we can evaluate whether that square is 1-bordered in O(1).", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "grid = [[1,1,1],[1,0,1],[1,1,1]]", + "expected_output": "9", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "grid = [[1,1,0,0]]", + "expected_output": "1", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[][]} grid\n * @return {number}\n */\nconst largest1BorderedSquare = function(grid) {\n let A = grid;\n let m = A.length,\n n = A[0].length;\n let max = 0;\n const hori = Array.from(Array(m)).map(() => Array(n).fill(0));\n const ver = Array.from(Array(m)).map(() => Array(n).fill(0));\n for (let i = 0; i < m; ++i) {\n for (let j = 0; j < n; ++j) {\n if (A[i][j] > 0) {\n hori[i][j] = j > 0 ? hori[i][j - 1] + 1 : 1;\n ver[i][j] = i > 0 ? ver[i - 1][j] + 1 : 1;\n }\n }\n }\n for (let i = m - 1; i >= 0; i--) {\n for (let j = n - 1; j >= 0; j--) {\n let small = Math.min(hori[i][j], ver[i][j]);\n while (small > max) {\n if (ver[i][j - small + 1] >= small && hori[i - small + 1][j] >= small) {\n max = small;\n break\n }\n small--;\n }\n }\n }\n return max * max;\n};\n\n" + }, + { + "_id": "66f925ddfdfb8e1665720d26", + "questionid": 603, + "title": "Sum of Nodes with Even-Valued Grandparent", + "slug": "sum-of-nodes-with-even-valued-grandparent", + "description": "Given the root of a binary tree, return the sum of values of nodes with an even-valued grandparent. If there are no nodes with an even-valued grandparent, return 0. A grandparent of a node is the parent of its parent if it exists. ", + "category": [ + "Tree", + "Depth-First Search", + "Breadth-First Search", + "Binary Tree" + ], + "complexity": "Medium", + "successrate": 85.2, + "totalsubmissions": 115315, + "totalaccepted": 98213, + "likes": 1697, + "dislikes": 56, + "hints": "Traverse the tree keeping the parent and the grandparent. If the grandparent of the current node is even-valued, add the value of this node to the answer.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [6,7,8,2,7,1,3,9,null,1,4,null,null,null,5]", + "expected_output": "18", + "explanation": "The red nodes are the nodes with even-value grandparent while the blue nodes are the even-value grandparents." + }, + { + "example_num": 2, + "expected_input": "root = [1]", + "expected_output": "0", + "explanation": "" + } + ], + "solution": "/**\n * Definition for a binary tree node.\n * function TreeNode(val, left, right) {\n * this.val = (val===undefined ? 0 : val)\n * this.left = (left===undefined ? null : left)\n * this.right = (right===undefined ? null : right)\n * }\n */\n/**\n * @param {TreeNode} root\n * @return {number}\n */\nconst sumEvenGrandparent = function(root) {\n let res = 0\n dfs(root, null, null)\n return res\n \n \n function dfs(node, parent, gp) {\n if(node == null) return\n if(parent && gp && gp.val % 2 === 0) {\n res += node.val\n }\n dfs(node.left, node, parent)\n dfs(node.right, node, parent)\n }\n \n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720d28", + "questionid": 605, + "title": "Binary Tree Coloring Game", + "slug": "binary-tree-coloring-game", + "description": "Two players play a turn based game on a binary tree. We are given the root of this binary tree, and the number of nodes n in the tree. n is odd, and each node has a distinct value from 1 to n. Initially, the first player names a value x with 1 <= x <= n, and the second player names a value y with 1 <= y <= n and y != x. The first player colors the node with value x red, and the second player colors the node with value y blue. Then, the players take turns starting with the first player. In each turn, that player chooses a node of their color (red if player 1, blue if player 2) and colors an uncolored neighbor of the chosen node (either the left child, right child, or parent of the chosen node.) If (and only if) a player cannot choose such a node in this way, they must pass their turn. If both players pass their turn, the game ends, and the winner is the player that colored more nodes. You are the second player. If it is possible to choose such a y to ensure you win the game, return true. If it is not possible, return false. ", + "category": [ + "Tree", + "Depth-First Search", + "Binary Tree" + ], + "complexity": "Medium", + "successrate": 51.2, + "totalsubmissions": 67331, + "totalaccepted": 34450, + "likes": 940, + "dislikes": 172, + "hints": "The best move y must be immediately adjacent to x, since it locks out that subtree. Can you count each of (up to) 3 different subtrees neighboring x?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [1,2,3,4,5,6,7,8,9,10,11], n = 11, x = 3", + "expected_output": "true\nExplanation: The second player can choose the node with value 2.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "root = [1,2,3], n = 3, x = 1", + "expected_output": "false", + "explanation": "" + } + ], + "solution": "/**\n * Definition for a binary tree node.\n * function TreeNode(val) {\n * this.val = val;\n * this.left = this.right = null;\n * }\n */\n/**\n * @param {TreeNode} root\n * @param {number} n\n * @param {number} x\n * @return {boolean}\n */\nconst btreeGameWinningMove = function(root, n, x) {\n let tl, tr;\n function dfs(node) {\n if (node == null) return 0;\n let l = dfs(node.left),\n r = dfs(node.right);\n if (node.val == x) (tl = l), (tr = r);\n return l + r + 1;\n }\n dfs(root);\n return Math.max(tl, tr, n - tl - tr - 1) > n / 2;\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720d2e", + "questionid": 611, + "title": "Swap For Longest Repeated Character Substring", + "slug": "swap-for-longest-repeated-character-substring", + "description": "You are given a string text. You can swap two of the characters in the text. Return the length of the longest substring with repeated characters. ", + "category": [ + "String", + "Sliding Window" + ], + "complexity": "Medium", + "successrate": 46.3, + "totalsubmissions": 48792, + "totalaccepted": 22568, + "likes": 694, + "dislikes": 63, + "hints": "There are two cases: a block of characters, or two blocks of characters between one different character. \r\n By keeping a run-length encoded version of the string, we can easily check these cases.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "text = "ababa"", + "expected_output": "3", + "explanation": "We can swap the first 'b' with the last 'a', or the last 'b' with the first 'a'. Then, the longest repeated character substring is "aaa" with length 3." + }, + { + "example_num": 2, + "expected_input": "text = "aaabaaa"", + "expected_output": "6", + "explanation": "Swap 'b' with the last 'a' (or the first 'a'), and we get longest repeated character substring "aaaaaa" with length 6." + }, + { + "example_num": 3, + "expected_input": "text = "aaaaa"", + "expected_output": "5", + "explanation": "No need to swap, longest repeated character substring is "aaaaa" with length is 5." + } + ], + "solution": "/**\n * @param {string} text\n * @return {number}\n */\nconst maxRepOpt1 = function(text) {\n const count = [...text].reduce((a, c) => {\n a[c] = a[c] || 0;\n a[c]++;\n return a;\n }, {});\n let ans = 0;\n let i = 0;\n while (i < text.length) {\n let j = i;\n const c = text.charAt(i);\n while (j < text.length && text.charAt(j) === c) j++;\n if (j - i < count[c]) {\n let k = j + 1;\n while (k < text.length && text.charAt(k) === c && k - i < count[c]) k++;\n ans = Math.max(k - i, ans);\n } else ans = Math.max(j - i, ans);\n i = j;\n }\n return ans;\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720d30", + "questionid": 613, + "title": "Maximum Number of Words You Can Type", + "slug": "maximum-number-of-words-you-can-type", + "description": "There is a malfunctioning keyboard where some letter keys do not work. All other keys on the keyboard work properly. Given a string text of words separated by a single space (no leading or trailing spaces) and a string brokenLetters of all distinct letter keys that are broken, return the number of words in text you can fully type using this keyboard. ", + "category": [ + "Hash Table", + "String" + ], + "complexity": "Easy", + "successrate": 71.4, + "totalsubmissions": 39791, + "totalaccepted": 28416, + "likes": 273, + "dislikes": 13, + "hints": "Check each word separately if it can be typed. A word can be typed if all its letters are not broken.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "text = "hello world", brokenLetters = "ad"", + "expected_output": "1", + "explanation": "We cannot type "world" because the 'd' key is broken." + }, + { + "example_num": 2, + "expected_input": "text = "leet code", brokenLetters = "lt"", + "expected_output": "1", + "explanation": "We cannot type "leet" because the 'l' and 't' keys are broken." + }, + { + "example_num": 3, + "expected_input": "text = "leet code", brokenLetters = "e"", + "expected_output": "0", + "explanation": "We cannot type either word because the 'e' key is broken." + } + ], + "solution": "/**\n * @param {string} text\n * @param {string} brokenLetters\n * @return {number}\n */\nconst canBeTypedWords = function(text, brokenLetters) {\n const set = new Set(brokenLetters.split(''))\n const arr = text.split(' ')\n let res = 0\n for(let e of arr) {\n let ok = true\n for(let c of e) {\n if(set.has(c)) {\n ok = false\n break\n }\n }\n if(ok) res++\n }\n \n return res\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720d33", + "questionid": 616, + "title": "Number of Days Between Two Dates", + "slug": "number-of-days-between-two-dates", + "description": "Write a program to count the number of days between two dates. The two dates are given as strings, their format is YYYY-MM-DD\u00a0as shown in the examples. ", + "category": [ + "Math", + "String" + ], + "complexity": "Easy", + "successrate": 46.7, + "totalsubmissions": 61154, + "totalaccepted": 28582, + "likes": 184, + "dislikes": 802, + "hints": "Create a function f(date) that counts the number of days from 1900-01-01 to date. How can we calculate the answer ? The answer is just |f(date1) - f(date2)|. How to construct f(date) ? For each year from 1900 to year - 1 sum up 365 or 366 in case of leap years. Then sum up for each month the number of days, consider the case when the current year is leap, finally sum up the days.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "date1 = \"2019-06-29\", date2 = \"2019-06-30\"", + "expected_output": "1", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "date1 = \"2020-01-15\", date2 = \"2019-12-31\"", + "expected_output": "15", + "explanation": "" + } + ], + "solution": "/**\n * @param {string} date1\n * @param {string} date2\n * @return {number}\n */\nconst daysBetweenDates = function(date1, date2) {\n const d1 = new Date(date1)\n const d2 = new Date(date2)\n return Math.abs((d1.getTime() - d2.getTime()) / (1000 * 60 * 60 * 24))\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720d34", + "questionid": 617, + "title": "Validate Binary Tree Nodes", + "slug": "validate-binary-tree-nodes", + "description": "You have n binary tree nodes numbered from 0 to n - 1 where node i has two children leftChild[i] and rightChild[i], return true if and only if all the given nodes form exactly one valid binary tree. If node i has no left child then leftChild[i] will equal -1, similarly for the right child. Note that the nodes have no values and that we only use the node numbers in this problem. ", + "category": [ + "Tree", + "Depth-First Search", + "Breadth-First Search", + "Union Find", + "Graph", + "Binary Tree" + ], + "complexity": "Medium", + "successrate": 41.5, + "totalsubmissions": 82677, + "totalaccepted": 34281, + "likes": 742, + "dislikes": 247, + "hints": "Find the parent of each node. A valid tree must have nodes with only one parent and exactly one node with no parent.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 4, leftChild = [1,-1,3,-1], rightChild = [2,-1,-1,-1]", + "expected_output": "true", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "n = 4, leftChild = [1,-1,3,-1], rightChild = [2,3,-1,-1]", + "expected_output": "false", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "n = 2, leftChild = [1,0], rightChild = [-1,-1]", + "expected_output": "false", + "explanation": "" + } + ], + "solution": null + }, + { + "_id": "66f925ddfdfb8e1665720d35", + "questionid": 618, + "title": "Closest Divisors", + "slug": "closest-divisors", + "description": "Given an integer num, find the closest two integers in absolute difference whose product equals\u00a0num + 1\u00a0or num + 2. Return the two integers in any order. ", + "category": [ + "Math" + ], + "complexity": "Medium", + "successrate": 59.1, + "totalsubmissions": 26132, + "totalaccepted": 15456, + "likes": 186, + "dislikes": 81, + "hints": "Find the divisors of n+1 and n+2. To find the divisors of a number, you only need to iterate to the square root of that number.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "num = 8", + "expected_output": "[3,3]", + "explanation": "For num + 1 = 9, the closest divisors are 3 & 3, for num + 2 = 10, the closest divisors are 2 & 5, hence 3 & 3 is chosen." + }, + { + "example_num": 2, + "expected_input": "num = 123", + "expected_output": "[5,25]", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "num = 999", + "expected_output": "[40,25]", + "explanation": "" + } + ], + "solution": null + }, + { + "_id": "66f925ddfdfb8e1665720d36", + "questionid": 619, + "title": "Largest Multiple of Three", + "slug": "largest-multiple-of-three", + "description": "Given an array of digits digits, return the largest multiple of three that can be formed by concatenating some of the given digits in any order. If there is no answer return an empty string. Since the answer may not fit in an integer data type, return the answer as a string. Note that the returning answer must not contain unnecessary leading zeros. ", + "category": [ + "Array", + "Dynamic Programming", + "Greedy" + ], + "complexity": "Hard", + "successrate": 34.2, + "totalsubmissions": 39968, + "totalaccepted": 13666, + "likes": 390, + "dislikes": 55, + "hints": "A number is a multiple of three if and only if its sum of digits is a multiple of three. Use dynamic programming. To find the maximum number, try to maximize the number of digits of the number. Sort the digits in descending order to find the maximum number.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "digits = [8,1,9]", + "expected_output": ""981"", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "digits = [8,6,7,1,0]", + "expected_output": ""8760"", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "digits = [1]", + "expected_output": """", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} digits\n * @return {string}\n */\nconst largestMultipleOfThree = function (digits) {\n const sum = digits.reduce((a, c) => a + c)\n if (sum === 0) return '0'\n const remainder = sum % 3\n digits.sort((a, b) => b - a)\n if (remainder === 0) return digits.join('')\n const doubleRemainder = remainder === 1 ? 2 : 1\n const idxs = []\n for (let i = digits.length - 1; i >= 0; i--) {\n const numRemainder = digits[i] % 3\n if (numRemainder === remainder) {\n digits[i] = ''\n return digits.join('')\n } else if (numRemainder === doubleRemainder) {\n idxs.push(i)\n }\n }\n const [idx1, idx2] = idxs\n if (idx2 === undefined) return ''\n\n digits[idx1] = ''\n digits[idx2] = ''\n return digits.join('')\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720d40", + "questionid": 629, + "title": "Reverse Substrings Between Each Pair of Parentheses", + "slug": "reverse-substrings-between-each-pair-of-parentheses", + "description": "You are given a string s that consists of lower case English letters and brackets. Reverse the strings in each pair of matching parentheses, starting from the innermost one. Your result should not contain any brackets. ", + "category": [ + "String", + "Stack" + ], + "complexity": "Medium", + "successrate": 65.7, + "totalsubmissions": 72801, + "totalaccepted": 47800, + "likes": 1269, + "dislikes": 34, + "hints": "Find all brackets in the string. Does the order of the reverse matter ? The order does not matter.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "(abcd)"", + "expected_output": ""dcba"", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "s = "(u(love)i)"", + "expected_output": ""iloveu"", + "explanation": "The substring "love" is reversed first, then the whole string is reversed." + }, + { + "example_num": 3, + "expected_input": "s = "(ed(et(oc))el)"", + "expected_output": ""leetcode"", + "explanation": "First, we reverse the substring "oc", then "etco", and finally, the whole string." + } + ], + "solution": "/**\n * @param {string} s\n * @return {string}\n */\nconst reverseParentheses = function(s) {\n const res = ['']\n let control = 0\n let order = 1\n for (let i = 0; i < s.length; i++) {\n if (s[i] === '(') {\n control++\n order = order ? 0 : 1\n res.push('')\n } else if (s[i] === ')') {\n if (order) res[control - 1] = res.pop() + res[control - 1]\n else res[control - 1] = res[control - 1] + res.pop()\n order = order ? 0 : 1\n control--\n } else {\n if (order) res[control] = res[control] + s[i]\n else res[control] = s[i] + res[control]\n }\n }\n return res[0]\n}\n\n// another\n\n/**\n * @param {string} s\n * @return {string}\n */\nconst reverseParentheses = function(s) {\n const n = s.length\n const stack = []\n const pair = []\n for(let i = 0; i < n; i++) {\n if(s[i] === '(') stack.push(i)\n else if(s[i] === ')') {\n const tmp = stack.pop()\n pair[i] = tmp\n pair[tmp] = i\n }\n }\n let res = ''\n for(let i = 0, d = 1; i < n; i += d) {\n if(s[i] === '(' || s[i] ===')') {\n i = pair[i]\n d = -d\n } else {\n res += s[i]\n }\n }\n return res\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720d42", + "questionid": 631, + "title": "Critical Connections in a Network", + "slug": "critical-connections-in-a-network", + "description": "There are n servers numbered from 0 to n - 1 connected by undirected server-to-server connections forming a network where connections[i] = [ai, bi] represents a connection between servers ai and bi. Any server can reach other servers directly or indirectly through the network. A critical connection is a connection that, if removed, will make some servers unable to reach some other server. Return all critical connections in the network in any order. ", + "category": [ + "Depth-First Search", + "Graph", + "Biconnected Component" + ], + "complexity": "Hard", + "successrate": 52, + "totalsubmissions": 278178, + "totalaccepted": 144789, + "likes": 3465, + "dislikes": 140, + "hints": "Use Tarjan's algorithm.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 4, connections = [[0,1],[1,2],[2,0],[1,3]]", + "expected_output": "[[1,3]]", + "explanation": "[[3,1]] is also accepted." + }, + { + "example_num": 2, + "expected_input": "n = 2, connections = [[0,1]]", + "expected_output": "[[0,1]]", + "explanation": "" + } + ], + "solution": "/**\n * @param {number} n\n * @param {number[][]} connections\n * @return {number[][]}\n */\nconst criticalConnections = function(n, connections) {\n const g = [],\n low = Array(n),\n res = []\n low.fill(0)\n for (let con of connections) {\n g[con[0]] = g[con[0]] || []\n g[con[1]] = g[con[1]] || []\n g[con[0]].push(con[1])\n g[con[1]].push(con[0])\n }\n const dfs = function(cur, v, p) {\n let dfn = cur\n low[v] = cur\n for (let i of g[v]) {\n if (i != p) {\n if (low[i] == 0) {\n cur++\n dfs(cur, i, v)\n if (low[i] > dfn) {\n res.push([i, v])\n }\n }\n low[v] = Math.min(low[v], low[i])\n }\n }\n }\n dfs(1, 0, -1)\n return res\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720d44", + "questionid": 633, + "title": "Number of Visible People in a Queue", + "slug": "number-of-visible-people-in-a-queue", + "description": "There are n people standing in a queue, and they numbered from 0 to n - 1 in left to right order. You are given an array heights of distinct integers where heights[i] represents the height of the ith person. A person can see another person to their right in the queue if everybody in between is shorter than both of them. More formally, the ith person can see the jth person if i < j and min(heights[i], heights[j]) > max(heights[i+1], heights[i+2], ..., heights[j-1]). Return an array answer of length n where answer[i] is the number of people the ith person can see to their right in the queue. ", + "category": [ + "Array", + "Stack", + "Monotonic Stack" + ], + "complexity": "Hard", + "successrate": 70.2, + "totalsubmissions": 25244, + "totalaccepted": 17721, + "likes": 742, + "dislikes": 14, + "hints": "How to solve this problem in quadratic complexity ? For every subarray start at index i, keep finding new maximum values until a value larger than arr[i] is found. Since the limits are high, you need a linear solution. Use a stack to keep the values of the array sorted as you iterate the array from the end to the start. Keep popping from the stack the elements in sorted order until a value larger than arr[i] is found, these are the ones that person i can see.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "heights = [10,6,8,5,11,9]", + "expected_output": "[3,1,2,1,1,0]", + "explanation": "Person 0 can see person 1, 2, and 4.\nPerson 1 can see person 2.\nPerson 2 can see person 3 and 4.\nPerson 3 can see person 4.\nPerson 4 can see person 5.\nPerson 5 can see no one since nobody is to the right of them." + }, + { + "example_num": 2, + "expected_input": "heights = [5,1,2,3,10]", + "expected_output": "[4,1,1,1,0]", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} heights\n * @return {number[]}\n */\nconst canSeePersonsCount = function(heights) {\n const n = heights.length\n const res = Array(n).fill(0)\n const stk = []\n for(let i = n - 1; i >= 0; i--) {\n const cur = heights[i]\n let del = 0\n while(stk.length && cur > heights[stk.at(-1)]) {\n del++\n stk.pop()\n }\n res[i] = del + (stk.length ? 1 : 0)\n stk.push(i)\n }\n \n return res\n};\n\n// another\n\n/**\n * @param {number[]} heights\n * @return {number[]}\n */\nconst canSeePersonsCount = function(heights) {\n const res = []\n if(heights.length === 0) return res\n \n const n = heights.length\n const stk = []\n for(let i = n - 1; i >= 0; i--) {\n let del = 0\n while(stk.length && heights[i] > heights[stk[stk.length - 1]]) {\n stk.pop()\n del++\n }\n res.push(del + (stk.length ? 1 : 0))\n stk.push(i)\n }\n \n return res.reverse()\n};\n\n// another\n\n\n/**\n * @param {number[]} heights\n * @return {number[]}\n */\nconst canSeePersonsCount = function(heights) {\n const ans = new Uint32Array(heights.length);\n \n const stack = [];\n for (let i = heights.length - 1; i >= 0; i--) {\n const h = heights[i];\n \n let del = 0;\n while (stack.length && stack[stack.length - 1] <= h) {\n del++;\n stack.pop();\n }\n \n ans[i] = del + (stack.length ? 1 : 0);\n stack.push(h);\n }\n\n return ans;\n};\n\n// another\n\n/**\n * @param {number[]} heights\n * @return {number[]}\n */\nconst canSeePersonsCount = function(heights) {\n const stack = [], n = heights.length, res = Array(n)\n for(let i = n - 1; i >= 0; i--) {\n const h = heights[i]\n let del = 0\n while(stack.length && stack[stack.length - 1] <= h) {\n stack.pop()\n del++\n }\n res[i] = stack.length ? del + 1 : del\n stack.push(h)\n }\n\n return res\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720d48", + "questionid": 637, + "title": "Largest Magic Square", + "slug": "largest-magic-square", + "description": "A k x k magic square is a k x k grid filled with integers such that every row sum, every column sum, and both diagonal sums are all equal. The integers in the magic square do not have to be distinct. Every 1 x 1 grid is trivially a magic square. Given an m x n integer grid, return the size (i.e., the side length k) of the largest magic square that can be found within this grid. ", + "category": [ + "Array", + "Matrix", + "Prefix Sum" + ], + "complexity": "Medium", + "successrate": 51.2, + "totalsubmissions": 14499, + "totalaccepted": 7426, + "likes": 186, + "dislikes": 199, + "hints": "Check all squares in the matrix and find the largest one.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "grid = [[7,1,4,5,6],[2,5,1,6,4],[1,5,4,3,2],[1,2,7,3,4]]", + "expected_output": "3", + "explanation": "The largest magic square has a size of 3.\nEvery row sum, column sum, and diagonal sum of this magic square is equal to 12.\n- Row sums: 5+1+6 = 5+4+3 = 2+7+3 = 12\n- Column sums: 5+5+2 = 1+4+7 = 6+3+3 = 12\n- Diagonal sums: 5+4+3 = 6+4+2 = 12" + }, + { + "example_num": 2, + "expected_input": "grid = [[5,1,3,1],[9,3,3,1],[1,3,3,8]]", + "expected_output": "2", + "explanation": "" + } + ], + "solution": null + }, + { + "_id": "66f925ddfdfb8e1665720d49", + "questionid": 638, + "title": "Count Ways to Build Rooms in an Ant Colony", + "slug": "count-ways-to-build-rooms-in-an-ant-colony", + "description": "You are an ant tasked with adding n new rooms numbered 0 to n-1 to your colony. You are given the expansion plan as a 0-indexed integer array of length n, prevRoom, where prevRoom[i] indicates that you must build room prevRoom[i] before building room i, and these two rooms must be connected directly. Room 0 is already built, so prevRoom[0] = -1. The expansion\u00a0plan is given such that once all the rooms are built, every room will be reachable from room 0. You can only build one room at a time, and you can travel freely between rooms you have already built only if they are connected.\u00a0You can choose to build any room as long as its previous room\u00a0is already built. Return the number of different orders you can build all the rooms in. Since the answer may be large, return it modulo 109 + 7. ", + "category": [ + "Math", + "Dynamic Programming", + "Tree", + "Graph", + "Topological Sort", + "Combinatorics" + ], + "complexity": "Hard", + "successrate": 48.2, + "totalsubmissions": 7427, + "totalaccepted": 3579, + "likes": 247, + "dislikes": 34, + "hints": "Use dynamic programming. Let dp[i] be the number of ways to solve the problem for the subtree of node i. Imagine you are trying to fill an array with the order of traversal, dp[i] equals the multiplications of the number of ways to distribute the subtrees of the children of i on the array using combinatorics, multiplied bu their dp values.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "prevRoom = [-1,0,1]", + "expected_output": "1", + "explanation": " There is only one way to build the additional rooms: 0 → 1 → 2" + }, + { + "example_num": 2, + "expected_input": "prevRoom = [-1,0,0,1,2]", + "expected_output": "6\r\nExplanation:\r\nThe 6 ways are:\r\n0 → 1 → 3 → 2 → 4\r\n0 → 2 → 4 → 1 → 3\r\n0 → 1 → 2 → 3 → 4\r\n0 → 1 → 2 → 4 → 3\r\n0 → 2 → 1 → 3 → 4\r\n0 → 2 → 1 → 4 → 3", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} prevRoom\n * @return {number}\n */\nconst waysToBuildRooms = function (prevRoom) {\n return brute(prevRoom);\n};\nfunction brute(prevRoom) {\n const power = function (a, b, n) {\n a = a % n;\n let result = 1n;\n let x = a;\n while (b > 0) {\n let leastSignificantBit = b % 2n;\n b = b / 2n;\n if (leastSignificantBit == 1n) {\n result = result * x;\n result = result % n;\n }\n x = x * x;\n x = x % n;\n }\n return result;\n };\n const modInverse = function (aa, mm) {\n return power(BigInt(aa), BigInt(mm - 2), BigInt(mm));\n };\n const mod = Math.pow(10, 9) + 7;\n let nodes = {};\n for (let i = 0; i < prevRoom.length; i++) {\n nodes[i] = { val: i, edges: {} };\n }\n for (let i = 1; i < prevRoom.length; i++) {\n nodes[prevRoom[i]].edges[i] = true;\n }\n let memo = {};\n const numNodes = function (root) {\n var key = root.val;\n if (memo[key] !== undefined) {\n return memo[key];\n }\n var res = 1;\n for (var x in root.edges) {\n res += numNodes(nodes[x]);\n }\n memo[key] = res;\n return res;\n };\n let den = 1;\n for (let x in nodes) {\n let size = numNodes(nodes[x]);\n den = (den * size) % mod;\n }\n let numerator = 1;\n for (let i = 1; i < prevRoom.length; i++) {\n numerator = (numerator * (i + 1)) % mod;\n }\n let denInverse = modInverse(den, mod);\n return (BigInt(numerator) * denInverse) % BigInt(mod);\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720d0d", + "questionid": 578, + "title": "Occurrences After Bigram", + "slug": "occurrences-after-bigram", + "description": "Given two strings first and second, consider occurrences in some text of the form \"first second third\", where second comes immediately after first, and third comes immediately after second. Return an array of all the words third for each occurrence of \"first second third\". ", + "category": [ + "String" + ], + "complexity": "Easy", + "successrate": 64.2, + "totalsubmissions": 79598, + "totalaccepted": 51126, + "likes": 319, + "dislikes": 289, + "hints": "Split the string into words, then look at adjacent triples of words.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "text = \"alice is a good girl she is a good student\", first = \"a\", second = \"good\"", + "expected_output": "[\"girl\",\"student\"]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "text = \"we will we will rock you\", first = \"we\", second = \"will\"", + "expected_output": "[\"we\",\"rock\"]", + "explanation": "" + } + ], + "solution": "/**\n * @param {string} text\n * @param {string} first\n * @param {string} second\n * @return {string[]}\n */\nconst findOcurrences = function(text, first, second) {\n const res = []\n let arr = text.split(' ')\n for(let i = 1, len = arr.length; i < len; i++) {\n if(arr[i] === second && arr[i - 1] === first) {\n if(i + 1 < len) res.push(arr[i + 1])\n }\n }\n return res\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720d12", + "questionid": 583, + "title": "Shortest Common Supersequence ", + "slug": "shortest-common-supersequence", + "description": "Given two strings str1 and str2, return the shortest string that has both str1 and str2 as subsequences. If there are multiple valid strings, return any of them. A string s is a subsequence of string t if deleting some number of characters from t (possibly 0) results in the string s. ", + "category": [ + "String", + "Dynamic Programming" + ], + "complexity": "Hard", + "successrate": 55.9, + "totalsubmissions": 78404, + "totalaccepted": 43824, + "likes": 2133, + "dislikes": 41, + "hints": "We can find the length of the longest common subsequence between str1[i:] and str2[j:] (for all (i, j)) by using dynamic programming. We can use this information to recover the longest common supersequence.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "str1 = "abac", str2 = "cab"", + "expected_output": ""cabac"", + "explanation": "str1 = "abac" is a subsequence of "cabac" because we can delete the first "c".\nstr2 = "cab" is a subsequence of "cabac" because we can delete the last "ac".\nThe answer provided is the shortest such string that satisfies these properties." + }, + { + "example_num": 2, + "expected_input": "str1 = "aaaaaaaa", str2 = "aaaaaaaa"", + "expected_output": ""aaaaaaaa"", + "explanation": "" + } + ], + "solution": "/**\n * @param {string} str1\n * @param {string} str2\n * @return {string}\n */\nconst shortestCommonSupersequence = function(str1, str2) {\n const len1 = str1.length\n const len2 = str2.length\n const mat = Array.from({ length: len1 + 1 }, () =>\n new Array(len2 + 1).fill(0)\n )\n for (let i = 0; i <= len1; i++) {\n for (let j = 0; j <= len2; j++) {\n if (i == 0) {\n mat[i][j] = str2.slice(0, j)\n continue\n }\n if (j == 0) {\n mat[i][j] = str1.slice(0, i)\n continue\n }\n mat[i][j] = mat[i - 1][j] + str1[i - 1]\n let cand1 = mat[i][j - 1] + str2[j - 1]\n if (cand1.length < mat[i][j].length) mat[i][j] = cand1\n if (str1[i - 1] === str2[j - 1]) {\n let cand2 = mat[i - 1][j - 1] + str1[i - 1]\n if (cand2.length < mat[i][j].length) mat[i][j] = cand2\n }\n }\n }\n return mat[len1][len2]\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720d17", + "questionid": 588, + "title": "Corporate Flight Bookings", + "slug": "corporate-flight-bookings", + "description": "There are n flights that are labeled from 1 to n. You are given an array of flight bookings bookings, where bookings[i] = [firsti, lasti, seatsi] represents a booking for flights firsti through lasti (inclusive) with seatsi seats reserved for each flight in the range. Return an array answer of length n, where answer[i] is the total number of seats reserved for flight i. ", + "category": [ + "Array", + "Prefix Sum" + ], + "complexity": "Medium", + "successrate": 58.5, + "totalsubmissions": 65368, + "totalaccepted": 38231, + "likes": 1002, + "dislikes": 141, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "bookings = [[1,2,10],[2,3,20],[2,5,25]], n = 5", + "expected_output": "[10,55,45,25,25]", + "explanation": "Flight labels: 1 2 3 4 5\nBooking 1 reserved: 10 10\nBooking 2 reserved: 20 20\nBooking 3 reserved: 25 25 25 25\nTotal seats: 10 55 45 25 25\nHence, answer = [10,55,45,25,25]" + }, + { + "example_num": 2, + "expected_input": "bookings = [[1,2,10],[2,2,15]], n = 2", + "expected_output": "[10,25]", + "explanation": "Flight labels: 1 2\nBooking 1 reserved: 10 10\nBooking 2 reserved: 15\nTotal seats: 10 25\nHence, answer = [10,25]" + } + ], + "solution": "/**\n * @param {number[][]} bookings\n * @param {number} n\n * @return {number[]}\n */\nconst corpFlightBookings = function(bookings, n) {\n const arr = Array(n + 2).fill(0)\n for(const [s, e, num] of bookings) {\n arr[s] += num\n arr[e + 1] -= num\n }\n for(let i = 1; i < n + 2; i++) {\n arr[i] += arr[i - 1]\n }\n arr.pop()\n arr.shift()\n return arr\n};\n\n// another\n\n/**\n * @param {number[][]} bookings\n * @param {number} n\n * @return {number[]}\n */\nconst corpFlightBookings = function(bookings, n) {\n let res = new Array(n).fill(0)\n for (let v of bookings) {\n res[v[0] - 1] += v[2]\n if (v[1] < n) res[v[1]] -= v[2]\n }\n for (let i = 1; i < n; ++i) res[i] += res[i - 1]\n return res\n}\n\n// another\n\n/**\n * @param {number[][]} bookings\n * @param {number} n\n * @return {number[]}\n */\nconst corpFlightBookings = function(bookings, n) {\n const arr = Array(n + 2).fill(0)\n for(let [s, e, num] of bookings) {\n arr[s] += num\n arr[e + 1] -= num\n }\n for(let i = 1; i <= n; i++) {\n if(arr[i] !== 0) arr[i] += arr[i - 1]\n else arr[i] = arr[i - 1]\n }\n return arr.slice(1, n + 1)\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720d19", + "questionid": 590, + "title": "Mean of Array After Removing Some Elements", + "slug": "mean-of-array-after-removing-some-elements", + "description": "Given an integer array arr, return the mean of the remaining integers after removing the smallest 5% and the largest 5% of the elements. Answers within 10-5 of the actual answer will be considered accepted. ", + "category": [ + "Array", + "Sorting" + ], + "complexity": "Easy", + "successrate": 64.6, + "totalsubmissions": 49041, + "totalaccepted": 31657, + "likes": 265, + "dislikes": 76, + "hints": "Sort the given array. Remove the first and last 5% of the sorted array.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "arr = [1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3]", + "expected_output": "2.00000", + "explanation": "After erasing the minimum and the maximum values of this array, all elements are equal to 2, so the mean is 2." + }, + { + "example_num": 2, + "expected_input": "arr = [6,2,7,5,1,2,0,3,10,2,5,0,5,5,0,8,7,6,8,0]", + "expected_output": "4.00000", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "arr = [6,0,7,0,7,5,7,8,3,4,0,7,8,1,6,8,1,1,2,4,8,1,9,5,4,3,8,5,10,8,6,6,1,0,6,10,8,2,3,4]", + "expected_output": "4.77778", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} arr\n * @return {number}\n */\nconst trimMean = function(arr) {\n const n = arr.length\n arr.sort((a, b) => a - b)\n const idx = n / 20\n let tmp = arr.slice(idx, n - idx)\n const sum = tmp.reduce((ac, cur) => ac + cur, 0)\n return sum / (n -idx * 2)\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720d1a", + "questionid": 591, + "title": "Sequential Digits", + "slug": "sequential-digits", + "description": "An\u00a0integer has sequential digits if and only if each digit in the number is one more than the previous digit. Return a sorted list of all the integers\u00a0in the range [low, high]\u00a0inclusive that have sequential digits. ", + "category": [ + "Enumeration" + ], + "complexity": "Medium", + "successrate": 60.9, + "totalsubmissions": 124148, + "totalaccepted": 75563, + "likes": 1588, + "dislikes": 98, + "hints": "Generate all numbers with sequential digits and check if they are in the given range. Fix the starting digit then do a recursion that tries to append all valid digits.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "low = 100, high = 300", + "expected_output": "[123,234]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "low = 1000, high = 13000", + "expected_output": "[1234,2345,3456,4567,5678,6789,12345]", + "explanation": "" + } + ], + "solution": "/**\n * @param {number} low\n * @param {number} high\n * @return {number[]}\n */\nconst sequentialDigits = function(low, high) {\n const res = []\n \n let q = []\n for(let i = 1; i <= 9; i++) q.push(i)\n \n while(q.length) {\n const tmp = []\n const size = q.length\n for(let i = 0; i < size; i++) {\n const cur = q[i]\n if(cur >= low && cur <= high) {\n res.push(cur)\n }\n if(cur > high) break\n const last = cur % 10\n if(last === 9) continue\n tmp.push(cur * 10 + last + 1)\n }\n \n q = tmp\n }\n \n return res\n};\n\n// another\n\n/**\n * @param {number} low\n * @param {number} high\n * @return {number[]}\n */\nconst sequentialDigits = function(low, high) {\n const set = new Set()\n let start = 0, end = 0\n for(let i = 10; i >= 0; i--) {\n if (low / (10 ** i) >= 1) {\n start = ~~(low / (10 ** i))\n break\n }\n }\n for(let i = 10; i >= 0; i--) {\n if (high / (10 ** i) >= 1) {\n end = ~~(high / (10 ** i))\n break\n }\n }\n for(let i = 1; i <= 9; i++) {\n helper(`${i}`) \n }\n\n const res = Array.from(set)\n res.sort((a, b) => a- b)\n return res\n \n function helper(s) {\n // console.log(s)\n if(+s > high) return\n if(+s >= low && +s <= high) {\n set.add(+s)\n }\n if(s[s.length - 1] === '9') return\n helper(`${s}${+s[s.length - 1] + 1}`)\n }\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720d1c", + "questionid": 593, + "title": "Longest Well-Performing Interval", + "slug": "longest-well-performing-interval", + "description": "We are given hours, a list of the number of hours worked per day for a given employee. A day is considered to be a tiring day if and only if the number of hours worked is (strictly) greater than 8. A well-performing interval is an interval of days for which the number of tiring days is strictly larger than the number of non-tiring days. Return the length of the longest well-performing interval. ", + "category": [ + "Array", + "Hash Table", + "Stack", + "Monotonic Stack", + "Prefix Sum" + ], + "complexity": "Medium", + "successrate": 34.2, + "totalsubmissions": 62835, + "totalaccepted": 21507, + "likes": 944, + "dislikes": 95, + "hints": "Make a new array A of +1/-1s corresponding to if hours[i] is > 8 or not. The goal is to find the longest subarray with positive sum. Using prefix sums (PrefixSum[i+1] = A[0] + A[1] + ... + A[i]), you need to find for each j, the smallest i < j with PrefixSum[i] + 1 == PrefixSum[j].", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "hours = [9,9,6,0,6,6,9]", + "expected_output": "3\nExplanation: The longest well-performing interval is [9,9,6].", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "hours = [6,6,6]", + "expected_output": "0", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} hours\n * @return {number}\n */\nconst longestWPI = function(hours) {\n const N = hours.length;\n const seen = new Map();\n let res = 0;\n let score = 0;\n for (let i = 0; i < N; i++) {\n score += hours[i] > 8 ? 1 : -1;\n if (score > 0) {\n res = i + 1;\n } else {\n if (!seen.has(score)) {\n seen.set(score, i);\n }\n if (seen.has(score - 1)) {\n res = Math.max(res, i - seen.get(score - 1));\n }\n }\n }\n return res;\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720d1f", + "questionid": 596, + "title": "Minimum Falling Path Sum II", + "slug": "minimum-falling-path-sum-ii", + "description": "Given an n x n integer matrix grid, return the minimum sum of a falling path with non-zero shifts. A falling path with non-zero shifts is a choice of exactly one element from each row of grid such that no two elements chosen in adjacent rows are in the same column. ", + "category": [ + "Array", + "Dynamic Programming", + "Matrix" + ], + "complexity": "Hard", + "successrate": 61.2, + "totalsubmissions": 44781, + "totalaccepted": 27426, + "likes": 761, + "dislikes": 65, + "hints": "Use dynamic programming. Let dp[i][j] be the answer for the first i rows such that column j is chosen from row i. Use the concept of cumulative array to optimize the complexity of the solution.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "grid = [[1,2,3],[4,5,6],[7,8,9]]", + "expected_output": "13", + "explanation": "The possible falling paths are:\n[1,5,9], [1,5,7], [1,6,7], [1,6,8],\n[2,4,8], [2,4,9], [2,6,7], [2,6,8],\n[3,4,8], [3,4,9], [3,5,7], [3,5,9]\nThe falling path with the smallest sum is [1,5,7], so the answer is 13." + }, + { + "example_num": 2, + "expected_input": "grid = [[7]]", + "expected_output": "7", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[][]} arr\n * @return {number}\n */\nconst minFallingPathSum = function (arr) {\n const n = arr.length\n for (let i = 1; i < n; i++) {\n const [m1, m2] = min2(arr[i - 1])\n for (j = 0; j < n; j++) {\n arr[i][j] += arr[i - 1][j] !== m1 ? m1 : m2\n }\n }\n return Math.min(...arr[n - 1])\n}\n\nfunction min2(arr) {\n let m1 = Infinity, m2 = Infinity\n arr.forEach(e => {\n if(e < m1) m2 = m1, m1 = e\n else if(e < m2) m2 = e\n })\n return [m1, m2]\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720d2a", + "questionid": 607, + "title": "Break a Palindrome", + "slug": "break-a-palindrome", + "description": "Given a palindromic string of lowercase English letters palindrome, replace exactly one character with any lowercase English letter so that the resulting string is not a palindrome and that it is the lexicographically smallest one possible. Return the resulting string. If there is no way to replace a character to make it not a palindrome, return an empty string. A string a is lexicographically smaller than a string b (of the same length) if in the first position where a and b differ, a has a character strictly smaller than the corresponding character in b. For example, \"abcc\" is lexicographically smaller than \"abcd\" because the first position they differ is at the fourth character, and 'c' is smaller than 'd'. ", + "category": [ + "String", + "Greedy" + ], + "complexity": "Medium", + "successrate": 52.3, + "totalsubmissions": 129419, + "totalaccepted": 67722, + "likes": 730, + "dislikes": 433, + "hints": "How to detect if there is impossible to perform the replacement? Only when the length = 1. Change the first non 'a' character to 'a'. What if the string has only 'a'? Change the last character to 'b'.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "palindrome = "abccba"", + "expected_output": ""aaccba"", + "explanation": "There are many ways to make "abccba" not a palindrome, such as "zbccba", "aaccba", and "abacba".\nOf all the ways, "aaccba" is the lexicographically smallest." + }, + { + "example_num": 2, + "expected_input": "palindrome = "a"", + "expected_output": """", + "explanation": "There is no way to replace a single character to make "a" not a palindrome, so return an empty string." + } + ], + "solution": null + }, + { + "_id": "66f925ddfdfb8e1665720d2c", + "questionid": 609, + "title": "Reverse Subarray To Maximize Array Value", + "slug": "reverse-subarray-to-maximize-array-value", + "description": "You are given an integer array nums. The value of this array is defined as the sum of |nums[i] - nums[i + 1]| for all 0 <= i < nums.length - 1. You are allowed to select any subarray of the given array and reverse it. You can perform this operation only once. Find maximum possible value of the final array. ", + "category": [ + "Array", + "Math", + "Greedy" + ], + "complexity": "Hard", + "successrate": 38.9, + "totalsubmissions": 9846, + "totalaccepted": 3833, + "likes": 330, + "dislikes": 34, + "hints": "What's the score after reversing a sub-array [L, R] ? It's the score without reversing it + abs(a[R] - a[L-1]) + abs(a[L] - a[R+1]) - abs(a[L] - a[L-1]) - abs(a[R] - a[R+1]) How to maximize that formula given that abs(x - y) = max(x - y, y - x) ? This can be written as max(max(a[R] - a[L - 1], a[L - 1] - a[R]) + max(a[R + 1] - a[L], a[L] - a[R + 1]) - value(L) - value(R + 1)) over all L < R where value(i) = abs(a[i] - a[i-1]) This can be divided into 4 cases.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [2,3,1,5,4]", + "expected_output": "10\nExplanation: By reversing the subarray [3,1,5] the array becomes [2,5,1,3,4] whose value is 10.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "nums = [2,4,9,24,2,1,10]", + "expected_output": "68", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} nums\n * @return {number}\n */\nconst maxValueAfterReverse = function (nums) {\n let minOfMaxPair = -Infinity\n let maxOfMinPair = Infinity\n let originalTotal = 0\n let maximumBenefit = 0\n for (let i = 1; i < nums.length; i++) {\n const [left, right] = [nums[i - 1], nums[i]]\n const diff = Math.abs(right - left)\n originalTotal += diff\n maximumBenefit = Math.max(\n maximumBenefit,\n Math.abs(right - nums[0]) - diff,\n Math.abs(left - nums[nums.length - 1]) - diff\n )\n minOfMaxPair = Math.max(minOfMaxPair, Math.min(left, right))\n maxOfMinPair = Math.min(maxOfMinPair, Math.max(left, right))\n }\n maximumBenefit = Math.max(maximumBenefit, 2 * (minOfMaxPair - maxOfMinPair))\n return originalTotal + maximumBenefit\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720d2f", + "questionid": 612, + "title": "Number of Dice Rolls With Target Sum", + "slug": "number-of-dice-rolls-with-target-sum", + "description": "You have n dice and each die has k faces numbered from 1 to k. Given three integers n, k, and target, return the number of possible ways (out of the kn total ways) to roll the dice so the sum of the face-up numbers equals target. Since the answer may be too large, return it modulo 109 + 7. ", + "category": [ + "Dynamic Programming" + ], + "complexity": "Medium", + "successrate": 47.7, + "totalsubmissions": 212292, + "totalaccepted": 101295, + "likes": 1942, + "dislikes": 85, + "hints": "Use dynamic programming. The states are how many dice are remaining, and what sum total you have rolled so far.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 1, k = 6, target = 3", + "expected_output": "1", + "explanation": "You throw one die with 6 faces.\nThere is only one way to get a sum of 3." + }, + { + "example_num": 2, + "expected_input": "n = 2, k = 6, target = 7", + "expected_output": "6", + "explanation": "You throw two dice, each with 6 faces.\nThere are 6 ways to get a sum of 7: 1+6, 2+5, 3+4, 4+3, 5+2, 6+1." + }, + { + "example_num": 3, + "expected_input": "n = 30, k = 30, target = 500", + "expected_output": "222616187", + "explanation": "The answer must be returned modulo 109 + 7." + } + ], + "solution": "/**\n * @param {number} d\n * @param {number} f\n * @param {number} target\n * @return {number}\n */\nconst numRollsToTarget = function(d, f, target) {\n const mod = 10 ** 9 + 7\n if (target > d * f || target < d) {\n return 0\n }\n const dp = new Array(target + 1).fill(0)\n for (let i = 1; i < Math.min(f + 1, target + 1); i++) {\n dp[i] = 1\n }\n for (let i = 2; i < d + 1; i++) {\n for (let j = Math.min(target, i * f); j > i - 1; j--) {\n dp[j] = 0\n for (let k = Math.max(i - 1, j - f); k < j; k++) {\n dp[j] = (dp[j] + dp[k]) % mod\n }\n }\n }\n\n return dp[target]\n}\n\n// another\n\nconst numRollsToTarget = function(d, f, target) {\n const MOD = 10 ** 9 + 7;\n const dp = Array.from({ length: d + 1 }, () => new Array(target + 1).fill(0));\n dp[0][0] = 1;\n for (let i = 1; i <= d; i++) {\n for (let j = 1; j <= target; j++) {\n if (j > i * f) {\n continue;\n } else {\n for (let k = 1; k <= f && k <= j; k++) {\n dp[i][j] = (dp[i][j] + dp[i - 1][j - k]) % MOD;\n }\n }\n }\n }\n return dp[d][target];\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720d3a", + "questionid": 623, + "title": "Constrained Subsequence Sum", + "slug": "constrained-subsequence-sum", + "description": "Given an integer array nums and an integer k, return the maximum sum of a non-empty subsequence of that array such that for every two consecutive integers in the subsequence, nums[i] and nums[j], where i < j, the condition j - i <= k is satisfied. A subsequence of an array is obtained by deleting some number of elements (can be zero) from the array, leaving the remaining elements in their original order. ", + "category": [ + "Array", + "Dynamic Programming", + "Queue", + "Sliding Window", + "Heap (Priority Queue)", + "Monotonic Queue" + ], + "complexity": "Hard", + "successrate": 46.6, + "totalsubmissions": 38558, + "totalaccepted": 17955, + "likes": 770, + "dislikes": 31, + "hints": "Use dynamic programming. Let dp[i] be the solution for the prefix of the array that ends at index i, if the element at index i is in the subsequence. dp[i] = nums[i] + max(0, dp[i-k], dp[i-k+1], ..., dp[i-1]) Use a heap with the sliding window technique to optimize the dp.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [10,2,-10,5,20], k = 2", + "expected_output": "37\nExplanation: The subsequence is [10, 2, 5, 20].", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "nums = [-1,-2,-3], k = 1", + "expected_output": "-1\nExplanation: The subsequence must be non-empty, so we choose the largest number.", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "nums = [10,-2,-10,-5,20], k = 2", + "expected_output": "23\nExplanation: The subsequence is [10, -2, -5, 20].", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} nums\n * @param {number} k\n * @return {number}\n */\nconst constrainedSubsetSum = function(nums, k) {\n const window = [[0,nums[0]]];\n let max = nums[0];\n for(let i=1; i0 && window[window.length-1][1] < sum){\n window.pop();\n }\n window.push([i,sum]);\n }\n return max;\n};\n\n// another\n\n/**\n * @param {number[]} nums\n * @param {number} k\n * @return {number}\n */\nconst constrainedSubsetSum = function (nums, k) {\n const dll = new DLL()\n dll.push([0, nums[0]])\n let max = nums[0]\n for (let i = 1; i < nums.length; i++) {\n if (!dll.isEmpty() && i - dll.peek().val[0] > k) {\n dll.shift()\n }\n const sum = Math.max(dll.peek().val[1], 0) + nums[i]\n max = Math.max(max, sum)\n while (!dll.isEmpty() && dll.peekLast().val[1] < sum) {\n dll.pop()\n }\n dll.push([i, sum])\n }\n return max\n}\n\nclass Node {\n constructor(val) {\n this.val = val\n this.prev = null\n this.next = null\n }\n}\nclass DLL {\n constructor() {\n this.head = new Node()\n this.tail = null\n this.size = 0\n }\n peek() {\n return this.head.next\n }\n peekLast() {\n return this.tail\n }\n isEmpty() {\n return this.head.next == null\n }\n shift() {\n const h = this.head.next\n if (h) {\n this.head.next = h.next\n if (h.next) {\n h.next.prev = this.head\n } else {\n this.tail = null\n }\n this.size--\n }\n }\n pop() {\n if (this.tail == null) return\n const newTail = this.tail.prev\n if (newTail) {\n newTail.next = null\n this.tail.prev = null\n this.tail = newTail\n this.size--\n }\n\n }\n push(val) {\n const node = new Node(val)\n node.prev = this.tail ?? this.head\n node.prev.next = node\n this.tail = node\n this.size++\n }\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720d3c", + "questionid": 625, + "title": "Maximum Subarray Sum with One Deletion", + "slug": "maximum-subarray-sum-with-one-deletion", + "description": "Given an array of integers, return the maximum sum for a non-empty\u00a0subarray (contiguous elements) with at most one element deletion.\u00a0In other words, you want to choose a subarray and optionally delete one element from it so that there is still at least one element left and the\u00a0sum of the remaining elements is maximum possible. Note that the subarray needs to be non-empty after deleting one element. ", + "category": [ + "Array", + "Dynamic Programming" + ], + "complexity": "Medium", + "successrate": 40.6, + "totalsubmissions": 77540, + "totalaccepted": 31492, + "likes": 1222, + "dislikes": 42, + "hints": "How to solve this problem if no deletions are allowed ? Try deleting each element and find the maximum subarray sum to both sides of that element. To do that efficiently, use the idea of Kadane's algorithm.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "arr = [1,-2,0,3]", + "expected_output": "4\nExplanation: Because we can choose [1, -2, 0, 3] and drop -2, thus the subarray [1, 0, 3] becomes the maximum value.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "arr = [1,-2,-2,3]", + "expected_output": "3\nExplanation: We just choose [3] and it's the maximum sum.", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "arr = [-1,-1,-1,-1]", + "expected_output": "-1", + "explanation": " The final subarray needs to be non-empty. You can't choose [-1] and delete -1 from it, then get an empty subarray to make the sum equals to 0." + } + ], + "solution": "/**\n * @param {number[]} arr\n * @return {number}\n */\nconst maximumSum = function (arr) {\n const n = arr.length\n let oneDel = 0, noDel = arr[0], res = arr[0]\n\n for(let i = 1; i < n; i++) {\n oneDel = Math.max(noDel, oneDel + arr[i])\n noDel = Math.max(arr[i], noDel + arr[i])\n res = Math.max(res, oneDel, noDel)\n }\n\n return res\n}\n\n// another\n\n/**\n * @param {number[]} arr\n * @return {number}\n */\nconst maximumSum = function (arr) {\n const n = arr.length\n let max = arr[0]\n const maxEndAt = Array(n), maxStartAt = Array(n)\n maxEndAt[0] = arr[0]\n for(let i = 1; i < n; i++) {\n maxEndAt[i] = Math.max(arr[i], maxEndAt[i - 1] + arr[i])\n max = Math.max(max, maxEndAt[i])\n }\n maxStartAt[n - 1] = arr[n - 1]\n for(let i = n - 2; i >= 0; i--) {\n maxStartAt[i] = Math.max(arr[i], maxStartAt[i + 1] + arr[i])\n }\n let res = Math.max(maxStartAt[0], maxEndAt[n - 1])\n for(let i = 1; i < n - 1; i++) {\n res = Math.max(max, res, maxEndAt[i - 1] + maxStartAt[i + 1])\n }\n return res\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720d3d", + "questionid": 626, + "title": "Day of the Week", + "slug": "day-of-the-week", + "description": "Given a date, return the corresponding day of the week for that date. The input is given as three integers representing the day, month and year respectively. Return the answer as one of the following values\u00a0{\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\"}. ", + "category": [ + "Math" + ], + "complexity": "Easy", + "successrate": 58.4, + "totalsubmissions": 73088, + "totalaccepted": 42700, + "likes": 229, + "dislikes": 1875, + "hints": "Sum up the number of days for the years before the given year. Handle the case of a leap year. Find the number of days for each month of the given year.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "day = 31, month = 8, year = 2019", + "expected_output": ""Saturday"", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "day = 18, month = 7, year = 1999", + "expected_output": ""Sunday"", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "day = 15, month = 8, year = 1993", + "expected_output": ""Sunday"", + "explanation": "" + } + ], + "solution": "/**\n * @param {number} day\n * @param {number} month\n * @param {number} year\n * @return {string}\n */\nconst dayOfTheWeek = function(day, month, year) {\n const weekdays = [\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\"];\n const date = new Date(year,month-1,day).getDay();\n return weekdays[date];\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720d47", + "questionid": 636, + "title": "Smallest String With Swaps", + "slug": "smallest-string-with-swaps", + "description": "You are given a string s, and an array of pairs of indices in the string\u00a0pairs\u00a0where\u00a0pairs[i] =\u00a0[a, b]\u00a0indicates 2 indices(0-indexed) of the string. You can\u00a0swap the characters at any pair of indices in the given\u00a0pairs\u00a0any number of times. Return the\u00a0lexicographically smallest string that s\u00a0can be changed to after using the swaps. ", + "category": [ + "Hash Table", + "String", + "Depth-First Search", + "Breadth-First Search", + "Union Find" + ], + "complexity": "Medium", + "successrate": 52.7, + "totalsubmissions": 87654, + "totalaccepted": 46225, + "likes": 1506, + "dislikes": 51, + "hints": "Think of it as a graph problem. Consider the pairs as connected nodes in the graph, what can you do with a connected component of indices ? We can sort each connected component alone to get the lexicographically minimum string.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "dcab", pairs = [[0,3],[1,2]]", + "expected_output": ""bacd"\nExplaination: \nSwap s[0] and s[3], s = "bcad"\nSwap s[1] and s[2], s = "bacd"", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "s = "dcab", pairs = [[0,3],[1,2],[0,2]]", + "expected_output": ""abcd"\nExplaination: \nSwap s[0] and s[3], s = "bcad"\nSwap s[0] and s[2], s = "acbd"\nSwap s[1] and s[2], s = "abcd"", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "s = "cba", pairs = [[0,1],[1,2]]", + "expected_output": ""abc"\nExplaination: \nSwap s[0] and s[1], s = "bca"\nSwap s[1] and s[2], s = "bac"\nSwap s[0] and s[1], s = "abc"", + "explanation": "" + } + ], + "solution": "/**\n * @param {string} s\n * @param {number[][]} pairs\n * @return {string}\n */\nconst smallestStringWithSwaps = function(s, pairs) {\n let set = Array(s.length).fill(-1)\n function union(a, b) {\n let root1 = find(a)\n let root2 = find(b)\n if (root1 !== root2) {\n set[root2] = root1\n }\n }\n function find(a) {\n if (set[a] < 0) {\n return a\n } else {\n return (set[a] = find(set[a]))\n }\n }\n for (let pair of pairs) {\n union(pair[0], pair[1])\n }\n let groups = []\n for (let i = 0; i < s.length; i++) {\n groups[i] = []\n }\n for (let i = 0; i < s.length; i++) {\n groups[find(i)].push(i)\n }\n let sArr = s.split('')\n for (let i = 0; i < s.length; i++) {\n if (groups[i].length > 1) {\n let chars = groups[i].map(idx => s[idx])\n chars.sort()\n for (let k = 0; k < groups[i].length; k++) {\n sArr[groups[i][k]] = chars[k]\n }\n }\n }\n return sArr.join('')\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720d4b", + "questionid": 640, + "title": "Remove All Adjacent Duplicates in String II", + "slug": "remove-all-adjacent-duplicates-in-string-ii", + "description": "You are given a string s and an integer k, a k duplicate removal consists of choosing k adjacent and equal letters from s and removing them, causing the left and the right side of the deleted substring to concatenate together. We repeatedly make k duplicate removals on s until we no longer can. Return the final string after all such duplicate removals have been made. It is guaranteed that the answer is unique. ", + "category": [ + "String", + "Stack" + ], + "complexity": "Medium", + "successrate": 56, + "totalsubmissions": 279451, + "totalaccepted": 156418, + "likes": 2575, + "dislikes": 49, + "hints": "Use a stack to store the characters, when there are k same characters, delete them. To make it more efficient, use a pair to store the value and the count of each character.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "abcd", k = 2", + "expected_output": ""abcd"\nExplanation: There's nothing to delete.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "s = "deeedbbcccbdaa", k = 3", + "expected_output": ""aa"\nExplanation: \nFirst delete "eee" and "ccc", get "ddbbbdaa"\nThen delete "bbb", get "dddaa"\nFinally delete "ddd", get "aa"", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "s = "pbbcggttciiippooaais", k = 2", + "expected_output": ""ps"", + "explanation": "" + } + ], + "solution": "/**\n * @param {string} s\n * @param {number} k\n * @return {string}\n */\nconst removeDuplicates = function (s, k) {\n const stack = [];\n const arr = s.split('')\n for(let i = 0; i < arr.length; i++) {\n if(i === 0 || arr[i] !== arr[i - 1]) {\n stack.push(1)\n } else {\n stack[stack.length - 1]++\n if(stack[stack.length - 1] === k) {\n stack.pop()\n arr.splice(i - k + 1, k)\n i -= k\n }\n }\n \n }\n return arr.join('')\n};\n\n// another\n\n/**\n * @param {string} s\n * @param {number} k\n * @return {string}\n */\nconst removeDuplicates = function (s, k) {\n const stack = [];\n s = s.split('');\n for (let i = 0; i < s.length;) {\n if (i === 0 || s[i] !== s[i - 1]) {\n stack.push(1);\n i++\n } else {\n stack[stack.length - 1]++;\n if (stack[stack.length - 1] === k) {\n stack.pop();\n s.splice(i - k + 1, k);\n i = i - k + 1;\n } else {\n i++\n }\n }\n }\n return s.join('');\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720d0c", + "questionid": 577, + "title": "Flip Columns For Maximum Number of Equal Rows", + "slug": "flip-columns-for-maximum-number-of-equal-rows", + "description": "You are given an m x n binary matrix matrix. You can choose any number of columns in the matrix and flip every cell in that column (i.e., Change the value of the cell from 0 to 1 or vice versa). Return the maximum number of rows that have all values equal after some number of flips. ", + "category": [ + "Array", + "Hash Table", + "Matrix" + ], + "complexity": "Medium", + "successrate": 63.1, + "totalsubmissions": 26409, + "totalaccepted": 16653, + "likes": 523, + "dislikes": 36, + "hints": "Flipping a subset of columns is like doing a bitwise XOR of some number K onto each row. We want rows X with X ^ K = all 0s or all 1s. This is the same as X = X^K ^K = (all 0s or all 1s) ^ K, so we want to count rows that have opposite bits set. For example, if K = 1, then we count rows X = (00000...001, or 1111....110).", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "matrix = [[0,1],[1,1]]", + "expected_output": "1", + "explanation": "After flipping no values, 1 row has all values equal." + }, + { + "example_num": 2, + "expected_input": "matrix = [[0,1],[1,0]]", + "expected_output": "2", + "explanation": "After flipping values in the first column, both rows have equal values." + }, + { + "example_num": 3, + "expected_input": "matrix = [[0,0,0],[0,0,1],[1,1,0]]", + "expected_output": "2", + "explanation": "After flipping values in the first two columns, the last two rows have equal values." + } + ], + "solution": "/**\n * @param {number[][]} matrix\n * @return {number}\n */\nconst maxEqualRowsAfterFlips = function(matrix) {\n let n = matrix.length,\n m = matrix[0].length;\n let ret = 0;\n for (let i = 0; i < n; i++) {\n let ct = 0;\n inner: for (let j = i; j < n; j++) {\n if (ae(matrix[i], matrix[j])) {\n ct++;\n } else {\n for (let k = 0; k < m; k++) {\n if (matrix[i][k] + matrix[j][k] !== 1) continue inner;\n }\n ct++;\n }\n }\n ret = Math.max(ret, ct);\n }\n return ret;\n};\n\nfunction ae(a1, a2) {\n if (a1.length !== a2.length) return false;\n for (let i = 0; i < a1.length; i++) {\n if (a1[i] !== a2[i]) return false;\n }\n return true;\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720d0e", + "questionid": 579, + "title": "Insufficient Nodes in Root to Leaf Paths", + "slug": "insufficient-nodes-in-root-to-leaf-paths", + "description": "Given the root of a binary tree and an integer limit, delete all insufficient nodes in the tree simultaneously, and return the root of the resulting binary tree. A node is insufficient if every root to leaf path intersecting this node has a sum strictly less than limit. A leaf is a node with no children. ", + "category": [ + "Tree", + "Depth-First Search", + "Binary Tree" + ], + "complexity": "Medium", + "successrate": 51.9, + "totalsubmissions": 48380, + "totalaccepted": 25100, + "likes": 407, + "dislikes": 547, + "hints": "Consider a DFS traversal of the tree. You can keep track of the current path sum from root to this node, and you can also use DFS to return the minimum value of any path from this node to the leaf. This will tell you if this node is insufficient.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [1,2,3,4,-99,-99,7,8,9,-99,-99,12,13,-99,14], limit = 1", + "expected_output": "[1,2,3,4,null,null,7,8,9,null,14]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "root = [5,4,8,11,null,17,4,7,1,null,null,5,3], limit = 22", + "expected_output": "[5,4,8,11,null,17,4,7,null,null,null,5]", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "root = [1,2,-3,-5,null,4,null], limit = -1", + "expected_output": "[1,null,-3,4]", + "explanation": "" + } + ], + "solution": "/**\n * Definition for a binary tree node.\n * function TreeNode(val) {\n * this.val = val;\n * this.left = this.right = null;\n * }\n */\n/**\n * @param {TreeNode} root\n * @param {number} limit\n * @return {TreeNode}\n */\nconst sufficientSubset = function(root, limit) {\n if (root.left == root.right)\n return root.val < limit ? null : root;\n if (root.left != null)\n root.left = sufficientSubset(root.left, limit - root.val);\n if (root.right != null)\n root.right = sufficientSubset(root.right, limit - root.val);\n return root.left == root.right ? null : root;\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720d10", + "questionid": 581, + "title": "Letter Tile Possibilities", + "slug": "letter-tile-possibilities", + "description": "You have n\u00a0\u00a0tiles, where each tile has one letter tiles[i] printed on it. Return the number of possible non-empty sequences of letters you can make using the letters printed on those tiles. ", + "category": [ + "String", + "Backtracking" + ], + "complexity": "Medium", + "successrate": 76.2, + "totalsubmissions": 87888, + "totalaccepted": 66986, + "likes": 1609, + "dislikes": 46, + "hints": "Try to build the string with a backtracking DFS by considering what you can put in every position.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "tiles = "AAB"", + "expected_output": "8\nExplanation: The possible sequences are "A", "B", "AA", "AB", "BA", "AAB", "ABA", "BAA".", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "tiles = "AAABBC"", + "expected_output": "188", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "tiles = "V"", + "expected_output": "1", + "explanation": "" + } + ], + "solution": "/**\n * @param {string} tiles\n * @return {number}\n */\nconst numTilePossibilities = function(tiles) {\n const obj = { count: 0 };\n dfs(tiles, new Array(tiles.length).fill(false), new Set(), \"\", obj);\n return obj.count;\n};\n\nfunction dfs(tiles, used, visited, path, obj) {\n if (path !== \"\" && !visited.has(path)) obj.count++;\n visited.add(path)\n\n for (let i = 0; i < tiles.length; i++) {\n if (used[i]) continue;\n used[i] = true;\n dfs(tiles, used, visited, path + tiles.charAt(i), obj);\n used[i] = false;\n }\n}\n\n// another\n\n/**\n * @param {string} tiles\n * @return {number}\n */\nconst numTilePossibilities = function(tiles) {\n let used = new Array(tiles.length).fill(false);\n let visited = new Set();\n let cnt = 0;\n const dfs = (path) => {\n if (path.length && !visited.has(path)) {\n visited.add(path);\n cnt++;\n }\n for (let i = 0; i < tiles.length; i++) {\n if (used[i]) continue;\n used[i] = true;\n dfs(path + tiles[i]);\n used[i] = false;\n }\n }\n dfs('');\n return cnt;\n};\n\n// another\n\n/**\n * @param {string} tiles\n * @return {number}\n */\nconst numTilePossibilities = function(tiles) {\n const count = new Array(26).fill(0)\n const ACode = 'A'.charCodeAt(0)\n for (let i = 0, len = tiles.length; i < len; i++) {\n count[tiles.charCodeAt(i) - ACode]++\n }\n return dfs(count)\n}\n\nfunction dfs(arr) {\n let sum = 0\n for (let i = 0; i < 26; i++) {\n if (arr[i] === 0) continue\n sum++\n arr[i]--\n sum += dfs(arr)\n arr[i]++\n }\n return sum\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720d1b", + "questionid": 592, + "title": "Relative Sort Array", + "slug": "relative-sort-array", + "description": "Given two arrays arr1 and arr2, the elements of arr2 are distinct, and all elements in arr2 are also in arr1. Sort the elements of arr1 such that the relative ordering of items in arr1 are the same as in arr2. Elements that do not appear in arr2 should be placed at the end of arr1 in ascending order. ", + "category": [ + "Array", + "Hash Table", + "Sorting", + "Counting Sort" + ], + "complexity": "Easy", + "successrate": 68.2, + "totalsubmissions": 180859, + "totalaccepted": 123303, + "likes": 1635, + "dislikes": 98, + "hints": "Using a hashmap, we can map the values of arr2 to their position in arr2. After, we can use a custom sorting function.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "arr1 = [2,3,1,3,2,4,6,7,9,2,19], arr2 = [2,1,4,3,9,6]", + "expected_output": "[2,2,2,1,4,3,3,9,6,7,19]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "arr1 = [28,6,22,8,44,17], arr2 = [22,28,8,6]", + "expected_output": "[22,28,8,6,17,44]", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} arr1\n * @param {number[]} arr2\n * @return {number[]}\n */\nconst relativeSortArray = function(arr1, arr2) {\n const hash = {}\n const res = []\n arr1.forEach(el => {\n if(hash.hasOwnProperty(el)) hash[el] += 1\n else hash[el] = 1\n })\n for(let i = 0, len = arr2.length; i < len; i++) {\n res.push(...makeArr(arr2[i], hash[arr2[i]]))\n delete hash[arr2[i]]\n }\n const keys = Object.keys(hash).sort((a, b) => a - b)\n for(let i = 0, len = keys.length; i < len; i++) {\n res.push(...makeArr(keys[i], hash[keys[i]]))\n }\n return res\n};\n\nfunction makeArr(el, num) {\n return new Array(num).fill(el)\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720d1e", + "questionid": 595, + "title": "Remove Covered Intervals", + "slug": "remove-covered-intervals", + "description": "Given an array intervals where intervals[i] = [li, ri] represent the interval [li, ri), remove all intervals that are covered by another interval in the list. The interval [a, b) is covered by the interval [c, d) if and only if c <= a and b <= d. Return the number of remaining intervals. ", + "category": [ + "Array", + "Sorting" + ], + "complexity": "Medium", + "successrate": 57.4, + "totalsubmissions": 166495, + "totalaccepted": 95595, + "likes": 1851, + "dislikes": 44, + "hints": "How to check if an interval is covered by another? Compare each interval to all others and check if it is covered by any interval.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "intervals = [[1,4],[3,6],[2,8]]", + "expected_output": "2", + "explanation": "Interval [3,6] is covered by [2,8], therefore it is removed." + }, + { + "example_num": 2, + "expected_input": "intervals = [[1,4],[2,3]]", + "expected_output": "1", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[][]} intervals\n * @return {number}\n */\nconst removeCoveredIntervals = function(intervals) {\n intervals.sort((a, b) => a[0] === b[0] ? b[1] - a[1] : a[0] - b[0])\n const n = intervals.length\n let res = n, max = intervals[0][1]\n for(let i = 1; i < n; i++) {\n if(intervals[i][1] <= max) res--\n else max = intervals[i][1]\n }\n return res\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720d20", + "questionid": 597, + "title": "Number of Equivalent Domino Pairs", + "slug": "number-of-equivalent-domino-pairs", + "description": "Given a list of dominoes, dominoes[i] = [a, b] is equivalent to dominoes[j] = [c, d] if and only if either (a == c and b == d), or (a == d and b == c) - that is, one domino can be rotated to be equal to another domino. Return the number of pairs (i, j) for which 0 <= i < j < dominoes.length, and dominoes[i] is equivalent to dominoes[j]. ", + "category": [ + "Array", + "Hash Table", + "Counting" + ], + "complexity": "Easy", + "successrate": 46.3, + "totalsubmissions": 100715, + "totalaccepted": 46607, + "likes": 476, + "dislikes": 230, + "hints": "For each domino j, find the number of dominoes you've already seen (dominoes i with i < j) that are equivalent. You can keep track of what you've seen using a hashmap.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "dominoes = [[1,2],[2,1],[3,4],[5,6]]", + "expected_output": "1", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "dominoes = [[1,2],[1,2],[1,1],[1,2],[2,2]]", + "expected_output": "3", + "explanation": "" + } + ], + "solution": null + }, + { + "_id": "66f925ddfdfb8e1665720d21", + "questionid": 598, + "title": "Replace Elements with Greatest Element on Right Side", + "slug": "replace-elements-with-greatest-element-on-right-side", + "description": "Given an array arr,\u00a0replace every element in that array with the greatest element among the elements to its\u00a0right, and replace the last element with -1. After doing so, return the array. ", + "category": [ + "Array" + ], + "complexity": "Easy", + "successrate": 74.5, + "totalsubmissions": 270455, + "totalaccepted": 201365, + "likes": 1208, + "dislikes": 164, + "hints": "Loop through the array starting from the end. Keep the maximum value seen so far.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "arr = [17,18,5,4,6,1]", + "expected_output": "[18,6,6,6,1,-1]", + "explanation": "- index 0 --> the greatest element to the right of index 0 is index 1 (18).\n- index 1 --> the greatest element to the right of index 1 is index 4 (6).\n- index 2 --> the greatest element to the right of index 2 is index 4 (6).\n- index 3 --> the greatest element to the right of index 3 is index 4 (6).\n- index 4 --> the greatest element to the right of index 4 is index 5 (1).\n- index 5 --> there are no elements to the right of index 5, so we put -1." + }, + { + "example_num": 2, + "expected_input": "arr = [400]", + "expected_output": "[-1]", + "explanation": "There are no elements to the right of index 0." + } + ], + "solution": "/**\n * @param {number[]} arr\n * @return {number[]}\n */\nconst replaceElements = function(arr) {\n const suffix = [-1], n = arr.length\n for(let i = n - 2; i >= 0; i--) {\n suffix.unshift(Math.max(suffix[0], arr[i + 1]))\n }\n \n return suffix\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720d24", + "questionid": 601, + "title": "Stone Game II", + "slug": "stone-game-ii", + "description": "Alice and Bob continue their\u00a0games with piles of stones.\u00a0 There are a number of\u00a0piles\u00a0arranged in a row, and each pile has a positive integer number of stones\u00a0piles[i].\u00a0 The objective of the game is to end with the most\u00a0stones. Alice\u00a0and Bob take turns, with Alice starting first.\u00a0 Initially, M = 1. On each player's turn, that player\u00a0can take all the stones in the first X remaining piles, where 1 <= X <= 2M.\u00a0 Then, we set\u00a0M = max(M, X). The game continues until all the stones have been taken. Assuming Alice and Bob play optimally, return the maximum number of stones Alice\u00a0can get. ", + "category": [ + "Array", + "Math", + "Dynamic Programming", + "Game Theory" + ], + "complexity": "Medium", + "successrate": 64.9, + "totalsubmissions": 59817, + "totalaccepted": 38833, + "likes": 1293, + "dislikes": 251, + "hints": "Use dynamic programming: the states are (i, m) for the answer of piles[i:] and that given m.", + "deleted": false, + "examples": [], + "solution": "/**\n * @param {number[]} piles\n * @return {number}\n */\nconst stoneGameII = function(piles) {\n let sums = [] //the sum from piles[i] to the end\n let hash = []\n if (piles == null || piles.length == 0) return 0\n let n = piles.length\n sums = new Array(n)\n sums[n - 1] = piles[n - 1]\n for (let i = n - 2; i >= 0; i--) {\n sums[i] = sums[i + 1] + piles[i] //the sum from piles[i] to the end\n }\n\n hash = Array.from({ length: n }, () => new Array(n).fill(0))\n return helper(piles, 0, 1)\n\n function helper(a, i, M) {\n if (i == a.length) return 0\n if (2 * M >= a.length - i) {\n return sums[i]\n }\n if (hash[i][M] != 0) return hash[i][M]\n let min = Number.MAX_SAFE_INTEGER //the min value the next player can get\n for (let x = 1; x <= 2 * M; x++) {\n min = Math.min(min, helper(a, i + x, Math.max(M, x)))\n }\n hash[i][M] = sums[i] - min //max stones = all the left stones - the min stones next player can get\n return hash[i][M]\n }\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720d25", + "questionid": 602, + "title": "Decompress Run-Length Encoded List", + "slug": "decompress-run-length-encoded-list", + "description": "We are given a list nums of integers representing a list compressed with run-length encoding. Consider each adjacent pair\u00a0of elements [freq, val] = [nums[2*i], nums[2*i+1]]\u00a0(with i >= 0).\u00a0 For each such pair, there are freq elements with value val concatenated in a sublist. Concatenate all the sublists from left to right to generate the decompressed list. Return the decompressed list. ", + "category": [ + "Array" + ], + "complexity": "Easy", + "successrate": 85.9, + "totalsubmissions": 206085, + "totalaccepted": 176994, + "likes": 730, + "dislikes": 1063, + "hints": "Decompress the given array by repeating nums[2*i+1] a number of times equal to nums[2*i].", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,2,3,4]", + "expected_output": "[2,4,4,4]", + "explanation": "The first pair [1,2] means we have freq = 1 and val = 2 so we generate the array [2].\nThe second pair [3,4] means we have freq = 3 and val = 4 so we generate [4,4,4].\nAt the end the concatenation [2] + [4,4,4] is [2,4,4,4]." + }, + { + "example_num": 2, + "expected_input": "nums = [1,1,2,3]", + "expected_output": "[1,3,3]", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} nums\n * @return {number[]}\n */\nconst decompressRLElist = function(nums) {\n const res = []\n for(let i = 0, n = nums.length; i < n - 1; i += 2) {\n const [freq, val] = [nums[i], nums[i + 1]]\n for(let j = 0; j < freq; j++) res.push(val)\n } \n \n return res\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720d29", + "questionid": 606, + "title": "Longest Common Subsequence", + "slug": "longest-common-subsequence", + "description": "Given two strings text1 and text2, return the length of their longest common subsequence. If there is no common subsequence, return 0. A subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters. A common subsequence of two strings is a subsequence that is common to both strings. ", + "category": [ + "String", + "Dynamic Programming" + ], + "complexity": "Medium", + "successrate": 58.9, + "totalsubmissions": 666769, + "totalaccepted": 392632, + "likes": 6213, + "dislikes": 70, + "hints": "Try dynamic programming. \r\nDP[i][j] represents the longest common subsequence of text1[0 ... i] & text2[0 ... j]. DP[i][j] = DP[i - 1][j - 1] + 1 , if text1[i] == text2[j]\r\nDP[i][j] = max(DP[i - 1][j], DP[i][j - 1]) , otherwise", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "text1 = "abcde", text2 = "ace"", + "expected_output": "3", + "explanation": "The longest common subsequence is "ace" and its length is 3." + }, + { + "example_num": 2, + "expected_input": "text1 = "abc", text2 = "abc"", + "expected_output": "3", + "explanation": "The longest common subsequence is "abc" and its length is 3." + }, + { + "example_num": 3, + "expected_input": "text1 = "abc", text2 = "def"", + "expected_output": "0", + "explanation": "There is no such common subsequence, so the result is 0." + } + ], + "solution": "/**\n * @param {string} text1\n * @param {string} text2\n * @return {number}\n */\nconst longestCommonSubsequence = function(text1, text2) {\n let dp = new Array(text1.length + 1)\n for (let i = 0; i < dp.length; i++)\n dp[i] = new Array(text2.length + 1).fill(0)\n for (let i = 1; i < dp.length; i++) {\n for (let j = 1; j < dp[i].length; j++) {\n if (text1[i - 1] == text2[j - 1]) dp[i][j] = 1 + dp[i - 1][j - 1]\n else dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1])\n }\n }\n return dp[dp.length - 1].pop()\n}\n\n// another\n\n/**\n * @param {string} text1\n * @param {string} text2\n * @return {number}\n */\nconst longestCommonSubsequence = function(text1, text2) {\n const len1 = text1.length\n const len2 = text2.length\n if(len1 === 0 || len2 === 0) return 0\n const dp = Array(len2 + 1).fill(0)\n for(let i = 1; i <= len1; i++) {\n let prev = 0\n for(let j = 1; j <= len2; j++) {\n const tmp = dp[j]\n if(text1[i - 1] === text2[j - 1]) dp[j] = Math.max(dp[j], prev + 1)\n else {\n dp[j] = Math.max(dp[j - 1], dp[j])\n }\n prev = tmp\n }\n }\n return dp[len2]\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720d38", + "questionid": 621, + "title": "Four Divisors", + "slug": "four-divisors", + "description": "Given an integer array nums, return the sum of divisors of the integers in that array that have exactly four divisors. If there is no such integer in the array, return 0. ", + "category": [ + "Array", + "Math" + ], + "complexity": "Medium", + "successrate": 40.8, + "totalsubmissions": 49183, + "totalaccepted": 20060, + "likes": 201, + "dislikes": 146, + "hints": "Find the divisors of each element in the array. You only need to loop to the square root of a number to find its divisors.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [21,4,7]", + "expected_output": "32", + "explanation": "21 has 4 divisors: 1, 3, 7, 21\n4 has 3 divisors: 1, 2, 4\n7 has 2 divisors: 1, 7\nThe answer is the sum of divisors of 21 only." + }, + { + "example_num": 2, + "expected_input": "nums = [21,21]", + "expected_output": "64", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "nums = [1,2,3,4,5]", + "expected_output": "0", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} nums\n * @return {number}\n */\nvar sumFourDivisors = function(nums) {\n let res = 0\n \n for(const e of nums) {\n const set = helper(e)\n if(set.size === 4) {\n for(const i of set) res += i\n }\n }\n \n return res\n \n function helper(num) {\n const set = new Set()\n const r = ~~(Math.sqrt(num) + 1)\n for(let i = 1; i < r; i++) {\n if(num % i === 0) {\n set.add(i)\n set.add(num / i)\n }\n }\n return set\n }\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720d3e", + "questionid": 627, + "title": "Make Array Strictly Increasing", + "slug": "make-array-strictly-increasing", + "description": "Given two integer arrays\u00a0arr1 and arr2, return the minimum number of operations (possibly zero) needed\u00a0to make arr1 strictly increasing. In one operation, you can choose two indices\u00a00 <=\u00a0i < arr1.length\u00a0and\u00a00 <= j < arr2.length\u00a0and do the assignment\u00a0arr1[i] = arr2[j]. If there is no way to make\u00a0arr1\u00a0strictly increasing,\u00a0return\u00a0-1. ", + "category": [ + "Array", + "Binary Search", + "Dynamic Programming" + ], + "complexity": "Hard", + "successrate": 44.4, + "totalsubmissions": 25430, + "totalaccepted": 11302, + "likes": 595, + "dislikes": 16, + "hints": "Use dynamic programming. The state would be the index in arr1 and the index of the previous element in arr2 after sorting it and removing duplicates.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "arr1 = [1,5,3,6,7], arr2 = [1,3,2,4]", + "expected_output": "1", + "explanation": "Replace 5 with 2, then arr1 = [1, 2, 3, 6, 7]." + }, + { + "example_num": 2, + "expected_input": "arr1 = [1,5,3,6,7], arr2 = [4,3,1]", + "expected_output": "2", + "explanation": "Replace 5 with 3 and then replace 3 with 4. arr1 = [1, 3, 4, 6, 7]." + }, + { + "example_num": 3, + "expected_input": "arr1 = [1,5,3,6,7], arr2 = [1,6,3,3]", + "expected_output": "-1", + "explanation": "You can't make arr1 strictly increasing." + } + ], + "solution": "/**\n * @param {number[]} arr1\n * @param {number[]} arr2\n * @return {number}\n */\nconst makeArrayIncreasing = function(arr1, arr2) {\n arr2.sort((a, b) => a - b)\n let arr3 = [arr2[0]]\n for (let i = 1; i < arr2.length; i++) {\n if (arr2[i] > arr2[i - 1]) {\n arr3.push(arr2[i])\n }\n }\n arr2 = arr3\n let n = arr1.length\n let indexMap = new Array(n * 2 + 2)\n for (let i = 0; i < n; i++) {\n let ai = arr1[i]\n let li = findLarger(arr2, ai)\n indexMap[i * 2] = li\n indexMap[i * 2 + 1] = arr2[li - 1] === ai ? li - 2 : li - 1\n }\n indexMap[n * 2] = arr2.length\n indexMap[n * 2 + 1] = arr2.length - 1\n let dp = new Array(n + 1)\n let MaxNum = 1000000000 + 1\n dp[0] = 0\n for (let i = 1; i < n + 1; i++) {\n let min = i\n let ai = i === n ? MaxNum : arr1[i]\n for (let j = 0; j < i; j++) {\n if (dp[j] == -1 || ai <= arr1[j]) {\n continue\n }\n if (indexMap[i * 2 + 1] - indexMap[j * 2] + 1 < i - j - 1) continue\n min = Math.min(min, dp[j] + i - j - 1)\n }\n if (min === i) {\n if (indexMap[i * 2 + 1] + 1 < i) {\n min = -1\n }\n }\n dp[i] = min\n }\n return dp[n]\n}\nconst findLarger = function(arr, a) {\n if (a > arr[arr.length - 1]) return arr.length\n let l = 0\n let r = arr.length - 1\n while (l < r) {\n let mid = (l + r) >> 1\n if (arr[mid] <= a) {\n l = mid + 1\n } else {\n r = mid\n }\n }\n return l\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720d45", + "questionid": 634, + "title": "Minimum Absolute Difference", + "slug": "minimum-absolute-difference", + "description": "Given an array of distinct integers arr, find all pairs of elements with the minimum absolute difference of any two elements. Return a list of pairs in ascending order(with respect to pairs), each pair [a, b] follows ", + "category": [ + "Array", + "Sorting" + ], + "complexity": "Easy", + "successrate": 69.8, + "totalsubmissions": 170198, + "totalaccepted": 118863, + "likes": 1465, + "dislikes": 58, + "hints": "Find the minimum absolute difference between two elements in the array. The minimum absolute difference must be a difference between two consecutive elements in the sorted array.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "arr = [4,2,1,3]", + "expected_output": "[[1,2],[2,3],[3,4]]\nExplanation: The minimum absolute difference is 1. List all pairs with difference equal to 1 in ascending order.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "arr = [1,3,6,10,15]", + "expected_output": "[[1,3]]", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "arr = [3,8,-10,23,19,-4,-14,27]", + "expected_output": "[[-14,-10],[19,23],[23,27]]", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} arr\n * @return {number[][]}\n */\nconst minimumAbsDifference = function(arr) {\n arr.sort((a, b) => a - b)\n let min = Number.MAX_VALUE\n for(let i = 1, len = arr.length; i < len; i++) {\n if(arr[i] - arr[i - 1] < min) min = arr[i] - arr[i - 1]\n }\n const res = []\n for(let i = 1, len = arr.length; i < len; i++) {\n if(arr[i] - arr[i - 1] === min) res.push([arr[i - 1], arr[i]])\n }\n return res\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720d13", + "questionid": 584, + "title": "Car Pooling", + "slug": "car-pooling", + "description": "There is a car with capacity empty seats. The vehicle only drives east (i.e., it cannot turn around and drive west). You are given the integer capacity and an array trips where trips[i] = [numPassengersi, fromi, toi] indicates that the ith trip has numPassengersi passengers and the locations to pick them up and drop them off are fromi and toi respectively. The locations are given as the number of kilometers due east from the car's initial location. Return true if it is possible to pick up and drop off all passengers for all the given trips, or false otherwise. ", + "category": [ + "Array", + "Sorting", + "Heap (Priority Queue)", + "Simulation", + "Prefix Sum" + ], + "complexity": "Medium", + "successrate": 58.3, + "totalsubmissions": 257410, + "totalaccepted": 149966, + "likes": 3080, + "dislikes": 66, + "hints": "Sort the pickup and dropoff events by location, then process them in order.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "trips = [[2,1,5],[3,3,7]], capacity = 4", + "expected_output": "false", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "trips = [[2,1,5],[3,3,7]], capacity = 5", + "expected_output": "true", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[][]} trips\n * @param {number} capacity\n * @return {boolean}\n */\nconst carPooling = function(trips, capacity) {\n const arr = Array(1001).fill(0)\n for(const [num, s, e] of trips) {\n arr[s] += num\n arr[e] -= num\n }\n for(let i = 1; i < 1001; i++) {\n arr[i] += arr[i - 1]\n }\n \n for(let e of arr) {\n if(e > capacity) return false\n }\n return true\n};\n\n// another\n\n/**\n * @param {number[][]} trips\n * @param {number} capacity\n * @return {boolean}\n */\nconst carPooling = function(trips, capacity) {\n let stops = new Array(1001).fill(0)\n for (let t of trips) {\n stops[t[1]] += t[0]\n stops[t[2]] -= t[0]\n }\n for (let i = 0; capacity >= 0 && i < 1001; ++i) capacity -= stops[i]\n return capacity >= 0\n}\n\n// another\n\n/**\n * @param {number[][]} trips\n * @param {number} capacity\n * @return {boolean}\n */\nconst carPooling = function(trips, capacity) {\n const arr = Array(1001).fill(0)\n for(let el of trips) {\n const [num, s, e] = el\n arr[s] += num\n arr[e] -= num\n }\n for(let i = 1; i < 1001; i++) {\n if(arr[i] !== 0) arr[i] += arr[i - 1]\n else arr[i] = arr[i - 1]\n }\n for(let e of arr) {\n if(e > capacity) return false\n }\n return true\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720d15", + "questionid": 586, + "title": "Filling Bookcase Shelves", + "slug": "filling-bookcase-shelves", + "description": "You are given an array books where books[i] = [thicknessi, heighti] indicates the thickness and height of the ith book. You are also given an integer shelfWidth. We want to place these books in order onto bookcase shelves that have a total width shelfWidth. We choose some of the books to place on this shelf such that the sum of their thickness is less than or equal to shelfWidth, then build another level of the shelf of the bookcase so that the total height of the bookcase has increased by the maximum height of the books we just put down. We repeat this process until there are no more books to place. Note that at each step of the above process, the order of the books we place is the same order as the given sequence of books. Return the minimum possible height that the total bookshelf can be after placing shelves in this manner. ", + "category": [ + "Array", + "Dynamic Programming" + ], + "complexity": "Medium", + "successrate": 58.2, + "totalsubmissions": 55901, + "totalaccepted": 32512, + "likes": 1234, + "dislikes": 75, + "hints": "Use dynamic programming: dp(i) will be the answer to the problem for books[i:].", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "books = [[1,1],[2,3],[2,3],[1,1],[1,1],[1,1],[1,2]], shelfWidth = 4", + "expected_output": "6", + "explanation": "The sum of the heights of the 3 shelves is 1 + 3 + 2 = 6.\nNotice that book number 2 does not have to be on the first shelf." + }, + { + "example_num": 2, + "expected_input": "books = [[1,3],[2,4],[3,2]], shelfWidth = 6", + "expected_output": "4", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[][]} books\n * @param {number} shelf_width\n * @return {number}\n */\nconst minHeightShelves = function(books, shelf_width) {\n const dp = new Array(books.length + 1)\n dp[0] = 0\n for(let i = 1; i <= books.length; i++) {\n let width = books[i - 1][0]\n let height = books[i - 1][1]\n dp[i] = dp[i - 1] + height\n for(let j = i - 1; j > 0 && width + books[j - 1][0] <= shelf_width; j--) {\n height = Math.max(height, books[j - 1][1])\n width += books[j - 1][0]\n dp[i] = Math.min(dp[i], dp[j - 1] + height)\n }\n }\n return dp[books.length]\n};\n\n// another\n\n/**\n * @param {number[][]} books\n * @param {number} shelf_width\n * @return {number}\n */\nconst minHeightShelves = function(books, shelf_width) {\n const n = books.length, dp = Array(1001).fill(Infinity)\n dp[0] = 0\n for(let i = 0; i < n; i++) {\n let sum = 0, mx = 0\n for(let j = i; j >= 0 && sum + books[j][0] <= shelf_width; j--) {\n sum += books[j][0]\n mx = Math.max(mx, books[j][1])\n dp[i + 1] = Math.min(dp[i + 1], dp[j] + mx)\n }\n }\n return dp[n]\n};\n\n// another\n\n/**\n * @param {number[][]} books\n * @param {number} shelf_width\n * @return {number}\n */\n const minHeightShelves = function(books, shelf_width) {\n const n = books.length, dp = Array(1001)\n dp[0] = 0\n\n for(let i = 0; i < n; i++) {\n let [w, h] = books[i]\n dp[i + 1] = dp[i] + h\n for(let j = i - 1; j >= 0 && w + books[j][0] <= shelf_width; j--) {\n h = Math.max(h, books[j][1])\n w += books[j][0]\n dp[i + 1] = Math.min(dp[i + 1], dp[j] + h) \n }\n }\n\n return dp[n]\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720d18", + "questionid": 589, + "title": "Delete Nodes And Return Forest", + "slug": "delete-nodes-and-return-forest", + "description": "Given the root of a binary tree, each node in the tree has a distinct value. After deleting all nodes with a value in to_delete, we are left with a forest (a disjoint union of trees). Return the roots of the trees in the remaining forest. You may return the result in any order. ", + "category": [ + "Tree", + "Depth-First Search", + "Binary Tree" + ], + "complexity": "Medium", + "successrate": 69.3, + "totalsubmissions": 224073, + "totalaccepted": 155220, + "likes": 2775, + "dislikes": 80, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [1,2,3,4,5,6,7], to_delete = [3,5]", + "expected_output": "[[1,2,null,4],[6],[7]]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "root = [1,2,4,null,3], to_delete = [3]", + "expected_output": "[[1,2,4]]", + "explanation": "" + } + ], + "solution": "/**\n * Definition for a binary tree node.\n * function TreeNode(val) {\n * this.val = val;\n * this.left = this.right = null;\n * }\n */\n/**\n * @param {TreeNode} root\n * @param {number[]} to_delete\n * @return {TreeNode[]}\n */\nconst delNodes = function(root, to_delete) {\n let rst = []\n let dfs = function(node, isRoot) {\n if (!node) return\n let isDel = to_delete.indexOf(node.val) !== -1\n if (node.left) node.left = dfs(node.left, isDel)\n if (node.right) node.right = dfs(node.right, isDel)\n if (isRoot && !isDel) rst.push(node)\n return isDel ? null : node\n }\n if (!root) return []\n dfs(root, true)\n return rst\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720d27", + "questionid": 604, + "title": "Distinct Echo Substrings", + "slug": "distinct-echo-substrings", + "description": "Return the number of distinct non-empty substrings of text\u00a0that can be written as the concatenation of some string with itself (i.e. it can be written as a + a\u00a0where a is some string). ", + "category": [ + "String", + "Dynamic Programming", + "Trie", + "Sliding Window", + "Rolling Hash", + "Hash Function" + ], + "complexity": "Hard", + "successrate": 49.9, + "totalsubmissions": 22844, + "totalaccepted": 11399, + "likes": 181, + "dislikes": 169, + "hints": "Given a substring of the text, how to check if it can be written as the concatenation of a string with itself ? We can do that in linear time, a faster way is to use hashing. Try all substrings and use hashing to check them.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "text = "abcabcabc"", + "expected_output": "3\nExplanation: The 3 substrings are "abcabc", "bcabca" and "cabcab".", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "text = "leetcodeleetcode"", + "expected_output": "2\nExplanation: The 2 substrings are "ee" and "leetcodeleetcode".", + "explanation": "" + } + ], + "solution": "/**\n * @param {string} text\n * @return {number}\n */\nconst distinctEchoSubstrings = function (text) {\n const set = new Set()\n for(let len = 1; len <= text.length / 2; len++) {\n for(let l = 0, r = len, count = 0; l < text.length - len; l++, r++) {\n if(text.charAt(l) === text.charAt(r)) count++\n else count = 0\n\n if(count === len) {\n set.add(text.slice(l - len + 1, l + 1))\n count--\n }\n }\n }\n return set.size\n}\n\n" + }, + { + "_id": "66f925ddfdfb8e1665720d2b", + "questionid": 608, + "title": "Sort the Matrix Diagonally", + "slug": "sort-the-matrix-diagonally", + "description": "A matrix diagonal is a diagonal line of cells starting from some cell in either the topmost row or leftmost column and going in the bottom-right direction until reaching the matrix's end. For example, the matrix diagonal starting from mat[2][0], where mat is a 6 x 3 matrix, includes cells mat[2][0], mat[3][1], and mat[4][2]. Given an m x n matrix mat of integers, sort each matrix diagonal in ascending order and return the resulting matrix. ", + "category": [ + "Array", + "Sorting", + "Matrix" + ], + "complexity": "Medium", + "successrate": 81.3, + "totalsubmissions": 101810, + "totalaccepted": 82802, + "likes": 1599, + "dislikes": 176, + "hints": "Use a data structure to store all values of each diagonal. How to index the data structure with the id of the diagonal? All cells in the same diagonal (i,j) have the same difference so we can get the diagonal of a cell using the difference i-j.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "mat = [[3,3,1,1],[2,2,1,2],[1,1,1,2]]", + "expected_output": "[[1,1,1,1],[1,2,2,2],[1,2,3,3]]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "mat = [[11,25,66,1,69,7],[23,55,17,45,15,52],[75,31,36,44,58,8],[22,27,33,25,68,4],[84,28,14,11,5,50]]", + "expected_output": "[[5,17,4,1,52,7],[11,11,25,45,8,69],[14,23,25,44,58,15],[22,27,31,36,50,66],[84,28,75,33,55,68]]", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[][]} mat\n * @return {number[][]}\n */\nconst diagonalSort = function(mat) {\n const m = mat.length, n = mat[0].length\n \n for(let j = 0; j < n; j++) {\n let i = 0, jj = j\n const tmp = []\n while(jj < n && i < m) {\n tmp.push(mat[i++][jj++])\n }\n tmp.sort((a, b) => a - b)\n let idx = 0\n jj = j\n let ii = 0\n while(ii < m && jj < n) {\n mat[ii++][jj++] = tmp[idx++]\n }\n }\n \n for(let i = 1; i < m; i++) {\n let j = 0\n let ii = i\n const tmp = []\n while(j < n && ii < m) {\n tmp.push(mat[ii++][j++])\n }\n tmp.sort((a, b) => a - b)\n let idx = 0\n ii = i\n j = 0\n while(ii < m && j < n) {\n mat[ii++][j++] = tmp[idx++]\n }\n }\n return mat\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720d2d", + "questionid": 610, + "title": "Day of the Year", + "slug": "day-of-the-year", + "description": "Given a string date representing a Gregorian calendar date formatted as YYYY-MM-DD, return the day number of the year. ", + "category": [ + "Math", + "String" + ], + "complexity": "Easy", + "successrate": 50.9, + "totalsubmissions": 64176, + "totalaccepted": 32690, + "likes": 240, + "dislikes": 303, + "hints": "Have a integer array of how many days there are per month. February gets one extra day if its a leap year. Then, we can manually count the ordinal as day + (number of days in months before this one).", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "date = "2019-01-09"", + "expected_output": "9", + "explanation": "Given date is the 9th day of the year in 2019." + }, + { + "example_num": 2, + "expected_input": "date = "2019-02-10"", + "expected_output": "41", + "explanation": "" + } + ], + "solution": "/**\n * @param {string} date\n * @return {number}\n */\n\nconst dayOfYear = function(date) {\n const [year, month, day] = date.split('-').map(s => +s),\n months = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],\n isLeapYear = !(year % 4) && month > 2 && (!!(year % 100) || !(year % 400))\n return months.splice(0, month - 1).reduce((a, b) => a + b, day + +isLeapYear)\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720d31", + "questionid": 614, + "title": "Remove Zero Sum Consecutive Nodes from Linked List", + "slug": "remove-zero-sum-consecutive-nodes-from-linked-list", + "description": "Given the head of a linked list, we repeatedly delete consecutive sequences of nodes that sum to 0 until there are no such sequences. After doing so, return the head of the final linked list.\u00a0 You may return any such answer. (Note that in the examples below, all sequences are serializations of ListNode objects.)", + "category": [ + "Hash Table", + "Linked List" + ], + "complexity": "Medium", + "successrate": 42.6, + "totalsubmissions": 82720, + "totalaccepted": 35212, + "likes": 1389, + "dislikes": 71, + "hints": "Convert the linked list into an array. While you can find a non-empty subarray with sum = 0, erase it. Convert the array into a linked list.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "head = [1,2,-3,3,1]", + "expected_output": "[3,1]\nNote: The answer [1,2,1] would also be accepted.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "head = [1,2,3,-3,4]", + "expected_output": "[1,2,4]", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "head = [1,2,3,-3,-2]", + "expected_output": "[1]", + "explanation": "" + } + ], + "solution": "/**\n * Definition for singly-linked list.\n * function ListNode(val) {\n * this.val = val;\n * this.next = null;\n * }\n */\n/**\n * @param {ListNode} head\n * @return {ListNode}\n */\nconst removeZeroSumSublists = function(head) {\n let dummy = new ListNode(0), cur = dummy;\n dummy.next = head;\n let prefix = 0;\n let m = new Map();\n while (cur != null) {\n prefix += cur.val;\n if (m.has(prefix)) {\n cur = m.get(prefix).next;\n let p = prefix + cur.val;\n while (p != prefix) {\n m.delete(p);\n cur = cur.next;\n p += cur.val;\n }\n m.get(prefix).next = cur.next;\n } else {\n m.set(prefix, cur);\n }\n cur = cur.next;\n }\n return dummy.next;\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720d32", + "questionid": 615, + "title": "Compare Strings by Frequency of the Smallest Character", + "slug": "compare-strings-by-frequency-of-the-smallest-character", + "description": "Let the function f(s) be the frequency of the lexicographically smallest character in a non-empty string s. For example, if s = \"dcce\" then f(s) = 2 because the lexicographically smallest character is 'c', which has a frequency of 2. You are given an array of strings words and another array of query strings queries. For each query queries[i], count the number of words in words such that f(queries[i]) < f(W) for each W in words. Return an integer array answer, where each answer[i] is the answer to the ith query. ", + "category": [ + "Array", + "Hash Table", + "String", + "Binary Search", + "Sorting" + ], + "complexity": "Medium", + "successrate": 61.1, + "totalsubmissions": 106244, + "totalaccepted": 64885, + "likes": 492, + "dislikes": 888, + "hints": "For each string from words calculate the leading count and store it in an array, then sort the integer array. For each string from queries calculate the leading count \"p\" and in base of the sorted array calculated on the step 1 do a binary search to count the number of items greater than \"p\".", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "queries = ["cbd"], words = ["zaaaz"]", + "expected_output": "[1]", + "explanation": "On the first query we have f("cbd") = 1, f("zaaaz") = 3 so f("cbd") < f("zaaaz")." + }, + { + "example_num": 2, + "expected_input": "queries = ["bbb","cc"], words = ["a","aa","aaa","aaaa"]", + "expected_output": "[1,2]", + "explanation": "On the first query only f("bbb") < f("aaaa"). On the second query both f("aaa") and f("aaaa") are both > f("cc")." + } + ], + "solution": "/**\n * @param {string[]} queries\n * @param {string[]} words\n * @return {number[]}\n */\nconst numSmallerByFrequency = function(queries, words) {\n const qArr = []\n for(let i = 0, len = queries.length; i < len; i++) {\n let sm = 'z'\n let hash = {}\n let cur = queries[i]\n for(let char of cur) {\n if(hash[char] == null) hash[char] = 0\n hash[char]++\n if(char < sm) sm = char\n }\n qArr.push(hash[sm])\n }\n const wArr = []\n for(let i = 0, len = words.length; i < len; i++) {\n let sm = 'z'\n let hash = {}\n let cur = words[i]\n for(let char of cur) {\n if(hash[char] == null) hash[char] = 0\n hash[char]++\n if(char < sm) sm = char\n }\n wArr.push(hash[sm])\n }\n const res = []\n for(let i = 0, len = queries.length; i < len; i++) {\n let cur = 0\n for(let j = 0, wlen = words.length; j < wlen; j++) {\n if(qArr[i] < wArr[j]) cur++\n }\n res.push(cur)\n }\n return res\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720d37", + "questionid": 620, + "title": "Prime Arrangements", + "slug": "prime-arrangements", + "description": "Return the number of permutations of 1 to n so that prime numbers are at prime indices (1-indexed.) (Recall that an integer\u00a0is prime if and only if it is greater than 1, and cannot be written as a product of two positive integers\u00a0both smaller than it.) Since the answer may be large, return the answer modulo 10^9 + 7. ", + "category": [ + "Math" + ], + "complexity": "Easy", + "successrate": 52.8, + "totalsubmissions": 37583, + "totalaccepted": 19850, + "likes": 243, + "dislikes": 352, + "hints": "Solve the problem for prime numbers and composite numbers separately. Multiply the number of permutations of prime numbers over prime indices with the number of permutations of composite numbers over composite indices. The number of permutations equals the factorial.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 5", + "expected_output": "12", + "explanation": "For example [1,2,5,4,3] is a valid permutation, but [5,2,3,4,1] is not because the prime number 5 is at index 1." + }, + { + "example_num": 2, + "expected_input": "n = 100", + "expected_output": "682289015", + "explanation": "" + } + ], + "solution": "/**\n * @param {number} n\n * @return {number}\n */\nfunction isPrime(n) {\n // Corner case\n if (n <= 1) return false\n // Check from 2 to n-1\n for (let i = 2; i < n; i++) if (n % i == 0) return false\n return true\n}\n\nconst numPrimeArrangements = function(n) {\n let primes = 0 // # of primes.\n let result = 1\n const mod = 10 ** 9 + 7\n for (let i = 2; i <= n; i++) if (isPrime(i)) primes++\n // Calculate factorials and multiply.\n for (let i = primes; i >= 1; i--) result = (i * result) % mod\n for (let i = n - primes; i >= 1; i--) result = (i * result) % mod\n return result // result of multiplying factorial(primes) with factorial(non-primes)\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720d39", + "questionid": 622, + "title": "Balance a Binary Search Tree", + "slug": "balance-a-binary-search-tree", + "description": "Given the root of a binary search tree, return a balanced binary search tree with the same node values. If there is more than one answer, return any of them. A binary search tree is balanced if the depth of the two subtrees of every node never differs by more than 1. ", + "category": [ + "Divide and Conquer", + "Greedy", + "Tree", + "Depth-First Search", + "Binary Search Tree", + "Binary Tree" + ], + "complexity": "Medium", + "successrate": 80.3, + "totalsubmissions": 111866, + "totalaccepted": 89848, + "likes": 1762, + "dislikes": 56, + "hints": "Convert the tree to a sorted array using an in-order traversal. Construct a new balanced tree from the sorted array recursively.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [1,null,2,null,3,null,4,null,null]", + "expected_output": "[2,1,3,null,null,null,4]\nExplanation: This is not the only correct answer, [3,1,4,null,2] is also correct.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "root = [2,1,3]", + "expected_output": "[2,1,3]", + "explanation": "" + } + ], + "solution": "/**\n * Definition for a binary tree node.\n * function TreeNode(val, left, right) {\n * this.val = (val===undefined ? 0 : val)\n * this.left = (left===undefined ? null : left)\n * this.right = (right===undefined ? null : right)\n * }\n */\n/**\n * @param {TreeNode} root\n * @return {TreeNode}\n */\nconst balanceBST = function(root) {\n const arr = []\n inOrder(root, arr)\n return constructBST(arr, 0, arr.length - 1)\n};\n\nfunction inOrder(node, arr) {\n if(node == null) return\n inOrder(node.left, arr)\n arr.push(node.val)\n inOrder(node.right, arr)\n}\n\nfunction constructBST(arr, start, end) {\n if(start > end) return null\n const mid = start + ((end - start) >> 1)\n const node = new TreeNode(arr[mid])\n node.left = constructBST(arr, start, mid - 1)\n node.right = constructBST(arr, mid + 1, end)\n return node\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720d3b", + "questionid": 624, + "title": "Distance Between Bus Stops", + "slug": "distance-between-bus-stops", + "description": "A bus\u00a0has n stops numbered from 0 to n - 1 that form\u00a0a circle. We know the distance between all pairs of neighboring stops where distance[i] is the distance between the stops number\u00a0i and (i + 1) % n. The bus goes along both directions\u00a0i.e. clockwise and counterclockwise. Return the shortest distance between the given\u00a0start\u00a0and destination\u00a0stops. ", + "category": [ + "Array" + ], + "complexity": "Easy", + "successrate": 54, + "totalsubmissions": 76073, + "totalaccepted": 41117, + "likes": 512, + "dislikes": 58, + "hints": "Find the distance between the two stops if the bus moved in clockwise or counterclockwise directions.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "distance = [1,2,3,4], start = 0, destination = 1", + "expected_output": "1", + "explanation": "Distance between 0 and 1 is 1 or 9, minimum is 1." + }, + { + "example_num": 2, + "expected_input": "distance = [1,2,3,4], start = 0, destination = 2", + "expected_output": "3", + "explanation": "Distance between 0 and 2 is 3 or 7, minimum is 3." + }, + { + "example_num": 3, + "expected_input": "distance = [1,2,3,4], start = 0, destination = 3", + "expected_output": "4", + "explanation": "Distance between 0 and 3 is 6 or 4, minimum is 4." + } + ], + "solution": "/**\n * @param {number[]} distance\n * @param {number} start\n * @param {number} destination\n * @return {number}\n */\nconst distanceBetweenBusStops = function(distance, start, destination) {\n if (start > destination) {\n let temp = start\n start = destination\n destination = temp\n }\n let res = 0,\n total = 0\n for (let i = 0; i < distance.length; i++) {\n if (i >= start && i < destination) {\n res += distance[i]\n }\n total += distance[i]\n }\n return Math.min(res, total - res)\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720d3f", + "questionid": 628, + "title": "Maximum Number of Balloons", + "slug": "maximum-number-of-balloons", + "description": "Given a string text, you want to use the characters of text to form as many instances of the word \"balloon\" as possible. You can use each character in text at most once. Return the maximum number of instances that can be formed. ", + "category": [ + "Hash Table", + "String", + "Counting" + ], + "complexity": "Easy", + "successrate": 62.5, + "totalsubmissions": 175531, + "totalaccepted": 109751, + "likes": 1002, + "dislikes": 68, + "hints": "Count the frequency of letters in the given string. Find the letter than can make the minimum number of instances of the word \"balloon\".", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "text = "nlaebolko"", + "expected_output": "1", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "text = "loonbalxballpoon"", + "expected_output": "2", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "text = "leetcode"", + "expected_output": "0", + "explanation": "" + } + ], + "solution": "/**\n * @param {string} text\n * @return {number}\n */\nconst maxNumberOfBalloons = function(text) {\n const cnt = [...text].reduce((A, ch) => {\n A[ch] = (A[ch] || 0) + 1;\n return A;\n }, {});\n const ans = Math.min(cnt['b'], cnt['a'], cnt['l'] / 2, cnt['o'] / 2, cnt['n']);\n return ans ? Math.floor(ans) : 0;\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720d41", + "questionid": 630, + "title": "K-Concatenation Maximum Sum", + "slug": "k-concatenation-maximum-sum", + "description": "Given an integer array arr and an integer k, modify the array by repeating it k times. For example, if arr = [1, 2] and k = 3 then the modified array will be [1, 2, 1, 2, 1, 2]. Return the maximum sub-array sum in the modified array. Note that the length of the sub-array can be 0 and its sum in that case is 0. As the answer can be very large, return the answer modulo 109 + 7. ", + "category": [ + "Array", + "Dynamic Programming" + ], + "complexity": "Medium", + "successrate": 24.1, + "totalsubmissions": 99886, + "totalaccepted": 24098, + "likes": 891, + "dislikes": 86, + "hints": "How to solve the problem for k=1 ? Use Kadane's algorithm for k=1. What are the possible cases for the answer ? The answer is the maximum between, the answer for k=1, the sum of the whole array multiplied by k, or the maximum suffix sum plus the maximum prefix sum plus (k-2) multiplied by the whole array sum for k > 1.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "arr = [1,2], k = 3", + "expected_output": "9", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "arr = [1,-2,1], k = 5", + "expected_output": "2", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "arr = [-1,-2], k = 7", + "expected_output": "0", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} arr\n * @param {number} k\n * @return {number}\n */\nconst kConcatenationMaxSum = function(arr, k) {\n const MOD = 1e9 + 7,\n INF = 1e4 + 1;\n const kadane = (A, sum = 0, ans = -INF) => {\n for (let x of A) {\n sum = Math.max(0, sum + x);\n ans = Math.max(ans, sum);\n }\n return [sum, ans];\n };\n const [sum1, ans1] = kadane(arr);\n const [sum2, ans2] = kadane(arr, sum1);\n const [sum3, ans3] = kadane(arr, sum2);\n const delta1 = ans2 - ans1,\n delta2 = ans3 - ans2;\n return k == 1 || delta1 == 0\n ? ans1\n : delta2 == 0\n ? ans2\n : ans1 + ((delta1 * (k - 1)) % MOD);\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720d43", + "questionid": 632, + "title": "Delete Characters to Make Fancy String", + "slug": "delete-characters-to-make-fancy-string", + "description": "A fancy string is a string where no three consecutive characters are equal. Given a string s, delete the minimum possible number of characters from s to make it fancy. Return the final string after the deletion. It can be shown that the answer will always be unique. ", + "category": [ + "String" + ], + "complexity": "Easy", + "successrate": 56.8, + "totalsubmissions": 32711, + "totalaccepted": 18591, + "likes": 215, + "dislikes": 10, + "hints": "What's the optimal way to delete characters if three or more consecutive characters are equal? If three or more consecutive characters are equal, keep two of them and delete the rest.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "leeetcode"", + "expected_output": ""leetcode"", + "explanation": "Remove an 'e' from the first group of 'e's to create "leetcode".\nNo three consecutive characters are equal, so return "leetcode"." + }, + { + "example_num": 2, + "expected_input": "s = "aaabaaaa"", + "expected_output": ""aabaa"", + "explanation": "Remove an 'a' from the first group of 'a's to create "aabaaaa".\nRemove two 'a's from the second group of 'a's to create "aabaa".\nNo three consecutive characters are equal, so return "aabaa"." + }, + { + "example_num": 3, + "expected_input": "s = "aab"", + "expected_output": ""aab"", + "explanation": "No three consecutive characters are equal, so return "aab"." + } + ], + "solution": null + }, + { + "_id": "66f925ddfdfb8e1665720d46", + "questionid": 635, + "title": "Ugly Number III", + "slug": "ugly-number-iii", + "description": "An ugly number is a positive integer that is divisible by a, b, or c. Given four integers n, a, b, and c, return the nth ugly number. ", + "category": [ + "Math", + "Binary Search", + "Number Theory" + ], + "complexity": "Medium", + "successrate": 27.7, + "totalsubmissions": 69539, + "totalaccepted": 19251, + "likes": 750, + "dislikes": 394, + "hints": "Write a function f(k) to determine how many ugly numbers smaller than k. As f(k) is non-decreasing, try binary search. Find all ugly numbers in [1, LCM(a, b, c)] (LCM is Least Common Multiple). Use inclusion-exclusion principle to expand the result.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 3, a = 2, b = 3, c = 5", + "expected_output": "4", + "explanation": "The ugly numbers are 2, 3, 4, 5, 6, 8, 9, 10... The 3rd is 4." + }, + { + "example_num": 2, + "expected_input": "n = 4, a = 2, b = 3, c = 4", + "expected_output": "6", + "explanation": "The ugly numbers are 2, 3, 4, 6, 8, 9, 10, 12... The 4th is 6." + }, + { + "example_num": 3, + "expected_input": "n = 5, a = 2, b = 11, c = 13", + "expected_output": "10", + "explanation": "The ugly numbers are 2, 4, 6, 8, 10, 11, 12, 13... The 5th is 10." + } + ], + "solution": "/**\n * @param {number} n\n * @param {number} a\n * @param {number} b\n * @param {number} c\n * @return {number}\n */\nconst nthUglyNumber = function(n, a, b, c) {\n let lo = 1, hi = 2 * 1e9;\n const { floor: f } = Math\n let ab = a * b / gcd(a, b);\n let bc = b * c / gcd(b, c);\n let ac = a * c / gcd(a, c);\n let abc = a * bc / gcd(a, bc);\n while(lo < hi) {\n let mid = lo + Math.floor((hi - lo) / 2);\n if(valid(mid)) hi = mid;\n else lo = mid + 1;\n }\n return lo;\n\n function valid(mid) {\n let res = f(mid / a) + f(mid / b) + f(mid / c) - f(mid / ab) - f(mid / bc) - f(mid / ac) + f(mid / abc)\n return res >= n\n }\n\n function gcd(a, b) {\n return b === 0 ? a : gcd(b, a % b)\n }\n};\n\n// another\n\n/**\n * @param {number} n\n * @param {number} a\n * @param {number} b\n * @param {number} c\n * @return {number}\n */\nvar nthUglyNumber = function (n, a, b, c) {\n const {floor} = Math\n let lo = 1,\n hi = 2 * (1e9 | 0)\n ;(a = BigInt(a)), (b = BigInt(b)), (c = BigInt(c))\n let ab = (a * b) / gcd(a, b)\n let bc = (b * c) / gcd(b, c)\n let ac = (a * c) / gcd(a, c)\n let abc = (a * bc) / gcd(a, bc)\n\n while (lo < hi) {\n let mid = lo + ((hi - lo) >> 1)\n let cnt =\n floor(mid / Number(a)) +\n floor(mid / Number(b)) +\n floor(mid / Number(c)) -\n floor(mid / Number(ab)) -\n floor(mid / Number(bc)) -\n floor(mid / Number(ac)) +\n floor(mid / Number(abc))\n if (cnt < n) {\n lo = mid + 1\n } else {\n hi = mid\n }\n }\n\n return lo\n\n function gcd(a, b) {\n return b ? gcd(b, a % b) : a\n }\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720d4a", + "questionid": 639, + "title": "Unique Number of Occurrences", + "slug": "unique-number-of-occurrences", + "description": "Given an array of integers arr, return true if the number of occurrences of each value in the array is unique, or false otherwise. ", + "category": [ + "Array", + "Hash Table" + ], + "complexity": "Easy", + "successrate": 72, + "totalsubmissions": 170248, + "totalaccepted": 122558, + "likes": 1402, + "dislikes": 33, + "hints": "Find the number of occurrences of each element in the array using a hash map. Iterate through the hash map and check if there is a repeated value.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "arr = [1,2,2,1,1,3]", + "expected_output": "true", + "explanation": " The value 1 has 3 occurrences, 2 has 2 and 3 has 1. No two values have the same number of occurrences." + }, + { + "example_num": 2, + "expected_input": "arr = [1,2]", + "expected_output": "false", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "arr = [-3,0,1,-3,1,1,1,-3,10,0]", + "expected_output": "true", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} arr\n * @return {boolean}\n */\nconst uniqueOccurrences = function(arr) {\n const hash = {}\n for(let e of arr) {\n if(hash[e] == null) hash[e] = 0\n hash[e]++\n }\n const ks = new Set(Object.keys(hash)), vs = new Set(Object.values(hash))\n return ks.size === vs.size\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720d4f", + "questionid": 644, + "title": "Sum of Floored Pairs", + "slug": "sum-of-floored-pairs", + "description": "Given an integer array nums, return the sum of floor(nums[i] / nums[j]) for all pairs of indices 0 <= i, j < nums.length in the array. Since the answer may be too large, return it modulo 109 + 7. The floor() function returns the integer part of the division. ", + "category": [ + "Array", + "Math", + "Binary Search", + "Prefix Sum" + ], + "complexity": "Hard", + "successrate": 27.9, + "totalsubmissions": 20976, + "totalaccepted": 5862, + "likes": 287, + "dislikes": 24, + "hints": "Find the frequency (number of occurrences) of all elements in the array. For each element, iterate through its multiples and multiply frequencies to find the answer.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [2,5,9]", + "expected_output": "10", + "explanation": "floor(2 / 5) = floor(2 / 9) = floor(5 / 9) = 0\nfloor(2 / 2) = floor(5 / 5) = floor(9 / 9) = 1\nfloor(5 / 2) = 2\nfloor(9 / 2) = 4\nfloor(9 / 5) = 1\nWe calculate the floor of the division for every pair of indices in the array then sum them up." + }, + { + "example_num": 2, + "expected_input": "nums = [7,7,7,7,7,7,7]", + "expected_output": "49", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} nums\n * @return {number}\n */\nconst sumOfFlooredPairs = function (nums) {\n const MAX = Math.max(...nums)\n const countsGreaterOrEqualTo = new Array(MAX + 1).fill(0)\n const numCounts = new Map()\n const MOD = 1e9 + 7\n nums.forEach((num) => {\n countsGreaterOrEqualTo[num]++\n numCounts.set(num, (numCounts.get(num) || 0) + 1)\n })\n\n for (let num = MAX - 1; num >= 0; num--) {\n countsGreaterOrEqualTo[num] += countsGreaterOrEqualTo[num + 1]\n }\n \n let totalCount = 0\n numCounts.forEach((count, num) => {\n let current = num\n while (current <= MAX) {\n totalCount = (totalCount + countsGreaterOrEqualTo[current] * count) % MOD\n current += num\n }\n })\n\n return totalCount\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720d5a", + "questionid": 655, + "title": "Maximum Length of a Concatenated String with Unique Characters", + "slug": "maximum-length-of-a-concatenated-string-with-unique-characters", + "description": "You are given an array of strings arr. A string s is formed by the concatenation of a subsequence of arr that has unique characters. Return the maximum possible length of s. A subsequence is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements. ", + "category": [ + "Array", + "String", + "Backtracking", + "Bit Manipulation" + ], + "complexity": "Medium", + "successrate": 50.5, + "totalsubmissions": 208173, + "totalaccepted": 105219, + "likes": 1721, + "dislikes": 155, + "hints": "You can try all combinations and keep mask of characters you have. You can use DP.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "arr = ["un","iq","ue"]", + "expected_output": "4", + "explanation": "All the valid concatenations are:\n- ""\n- "un"\n- "iq"\n- "ue"\n- "uniq" ("un" + "iq")\n- "ique" ("iq" + "ue")\nMaximum length is 4." + }, + { + "example_num": 2, + "expected_input": "arr = ["cha","r","act","ers"]", + "expected_output": "6", + "explanation": "Possible longest valid concatenations are "chaers" ("cha" + "ers") and "acters" ("act" + "ers")." + }, + { + "example_num": 3, + "expected_input": "arr = ["abcdefghijklmnopqrstuvwxyz"]", + "expected_output": "26", + "explanation": "The only string in arr has all 26 characters." + } + ], + "solution": "/**\n * @param {string[]} arr\n * @return {number}\n */\nconst maxLength = function(arr) {\n let maxLen = 0;\n arr = arr.filter(isUnique);\n const mem = {};\n maxLen = dfs(arr, \"\", 0, maxLen, mem);\n \n return maxLen;\n};\n\nfunction dfs(arr, path, i, maxLen, mem) {\n if (mem[path]) return mem[path];\n let pathIsUnique = isUnique(path);\n if (pathIsUnique) {\n maxLen = Math.max(path.length, maxLen);\n } \n if (i === arr.length || !pathIsUnique) {\n mem[path] = maxLen;\n return maxLen;\n }\n for (let j = i; j < arr.length; j++) {\n maxLen = dfs(arr, path + arr[j], j + 1, maxLen, mem);\n }\n\n\n mem[path] = maxLen;\n return maxLen;\n}\n\nfunction isUnique(str) {\n const map = {}\n for (let i = 0; i < str.length; i++) {\n if (map[str[i]]) return false;\n map[str[i]] = 1;\n }\n \n return true;\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720d5c", + "questionid": 657, + "title": "Tuple with Same Product", + "slug": "tuple-with-same-product", + "description": "Given an array nums of distinct positive integers, return the number of tuples (a, b, c, d) such that a * b = c * d where a, b, c, and d are elements of nums, and a != b != c != d. ", + "category": [ + "Array", + "Hash Table" + ], + "complexity": "Medium", + "successrate": 60.5, + "totalsubmissions": 30445, + "totalaccepted": 18406, + "likes": 406, + "dislikes": 19, + "hints": "Note that all of the integers are distinct. This means that each time a product is formed it must be formed by two unique integers. Count the frequency of each product of 2 distinct numbers. Then calculate the permutations formed.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [2,3,4,6]", + "expected_output": "8", + "explanation": "There are 8 valid tuples:\n(2,6,3,4) , (2,6,4,3) , (6,2,3,4) , (6,2,4,3)\n(3,4,2,6) , (4,3,2,6) , (3,4,6,2) , (4,3,6,2)" + }, + { + "example_num": 2, + "expected_input": "nums = [1,2,4,5,10]", + "expected_output": "16", + "explanation": "There are 16 valid tuples:\n(1,10,2,5) , (1,10,5,2) , (10,1,2,5) , (10,1,5,2)\n(2,5,1,10) , (2,5,10,1) , (5,2,1,10) , (5,2,10,1)\n(2,10,4,5) , (2,10,5,4) , (10,2,4,5) , (10,2,5,4)\n(4,5,2,10) , (4,5,10,2) , (5,4,2,10) , (5,4,10,2)" + } + ], + "solution": "/**\n * @param {number[]} nums\n * @return {number}\n */\nconst tupleSameProduct = function(nums) {\n const m = {}\n const len = nums.length\n for(let i = 0; i < len - 1; i++) {\n for(let j = i + 1; j < len; j++) {\n const tmp = nums[i] * nums[j]\n if(m[tmp] == null) m[tmp] = 0\n m[tmp]++\n } \n }\n let res = 0\n Object.keys(m).forEach(e => {\n if(m[e] > 1) res += m[e] * (m[e] - 1) * 4\n })\n \n return res\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720d5e", + "questionid": 659, + "title": "Count Number of Nice Subarrays", + "slug": "count-number-of-nice-subarrays", + "description": "Given an array of integers nums and an integer k. A continuous subarray is called nice if there are k odd numbers on it. Return the number of nice sub-arrays. ", + "category": [ + "Array", + "Hash Table", + "Math", + "Sliding Window" + ], + "complexity": "Medium", + "successrate": 58.5, + "totalsubmissions": 89894, + "totalaccepted": 52568, + "likes": 1659, + "dislikes": 42, + "hints": "After replacing each even by zero and every odd by one can we use prefix sum to find answer ? Can we use two pointers to count number of sub-arrays ? Can we store indices of odd numbers and for each k indices count number of sub-arrays contains them ?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,1,2,1,1], k = 3", + "expected_output": "2", + "explanation": "The only sub-arrays with 3 odd numbers are [1,1,2,1] and [1,2,1,1]." + }, + { + "example_num": 2, + "expected_input": "nums = [2,4,6], k = 1", + "expected_output": "0", + "explanation": "There are no odd numbers in the array." + }, + { + "example_num": 3, + "expected_input": "nums = [2,2,2,1,2,2,1,2,2,2], k = 2", + "expected_output": "16", + "explanation": "" + } + ], + "solution": null + }, + { + "_id": "66f925ddfdfb8e1665720d5f", + "questionid": 660, + "title": "Check If It Is a Good Array", + "slug": "check-if-it-is-a-good-array", + "description": "Given an array nums of\u00a0positive integers. Your task is to select some subset of nums, multiply each element by an integer and add all these numbers.\u00a0The array is said to be\u00a0good\u00a0if you can obtain a sum of\u00a01\u00a0from the array by any possible subset and multiplicand. Return\u00a0True\u00a0if the array is good\u00a0otherwise\u00a0return\u00a0False. ", + "category": [ + "Array", + "Math", + "Number Theory" + ], + "complexity": "Hard", + "successrate": 57.9, + "totalsubmissions": 22606, + "totalaccepted": 13097, + "likes": 251, + "dislikes": 274, + "hints": "Eq. ax+by=1 has solution x, y if gcd(a,b) = 1. Can you generalize the formula?. Check B\u00c3\u00a9zout's lemma.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [12,5,7,23]", + "expected_output": "true", + "explanation": "Pick numbers 5 and 7.\n5*3 + 7*(-2) = 1" + }, + { + "example_num": 2, + "expected_input": "nums = [29,6,10]", + "expected_output": "true", + "explanation": "Pick numbers 29, 6 and 10.\n29*1 + 6*(-3) + 10*(-1) = 1" + }, + { + "example_num": 3, + "expected_input": "nums = [3,6]", + "expected_output": "false", + "explanation": "" + } + ], + "solution": null + }, + { + "_id": "66f925ddfdfb8e1665720d61", + "questionid": 662, + "title": "Number of Closed Islands", + "slug": "number-of-closed-islands", + "description": "Given a 2D\u00a0grid consists of 0s (land)\u00a0and 1s (water).\u00a0 An island is a maximal 4-directionally connected group of 0s and a closed island\u00a0is an island totally\u00a0(all left, top, right, bottom) surrounded by 1s. Return the number of closed islands. ", + "category": [ + "Array", + "Depth-First Search", + "Breadth-First Search", + "Union Find", + "Matrix" + ], + "complexity": "Medium", + "successrate": 63.3, + "totalsubmissions": 133520, + "totalaccepted": 84486, + "likes": 1755, + "dislikes": 39, + "hints": "Exclude connected group of 0s on the corners because they are not closed island. Return number of connected component of 0s on the grid.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "grid = [[1,1,1,1,1,1,1,0],[1,0,0,0,0,1,1,0],[1,0,1,0,1,1,1,0],[1,0,0,0,0,1,0,1],[1,1,1,1,1,1,1,0]]", + "expected_output": "2", + "explanation": "Islands in gray are closed because they are completely surrounded by water (group of 1s)." + }, + { + "example_num": 2, + "expected_input": "grid = [[0,0,1,0,0],[0,1,0,1,0],[0,1,1,1,0]]", + "expected_output": "1", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "grid = [[1,1,1,1,1,1,1],\n  [1,0,0,0,0,0,1],\n  [1,0,1,1,1,0,1],\n  [1,0,1,0,1,0,1],\n  [1,0,1,1,1,0,1],\n  [1,0,0,0,0,0,1],\n [1,1,1,1,1,1,1]]", + "expected_output": "2", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[][]} grid\n * @return {number}\n */\nconst closedIsland = function(grid) {\n const m = grid.length, n = grid[0].length\n const dirs = [[0,1], [0,-1], [1,0], [-1,0]]\n for(let i = 0; i < m; i++) {\n for(let j = 0; j < n; j++) {\n if((i=== 0 || i === m - 1 || j === 0 || j === n - 1) && grid[i][j] === 0){\n fill(i, j)\n }\n }\n }\n\n \n let res = 0\n for(let i = 0; i < m; i++) {\n for(let j = 0; j < n; j++) {\n if(grid[i][j] === 0) {\n res++\n fill(i, j)\n } \n }\n }\n \n return res\n\n \n function fill(i, j) {\n if(i < 0 || i >= m || j < 0 || j >= n || grid[i][j] !== 0) return\n grid[i][j] = 1\n for(const [dx, dy] of dirs) {\n const nx = i + dx, ny = j + dy\n fill(nx, ny)\n }\n }\n};\n\n// another\n\n\n/**\n * @param {number[][]} grid\n * @return {number}\n */\nconst closedIsland = function(grid) {\n const m = grid.length, n = grid[0].length\n const arr = []\n for(let i = 0; i < m; i++) {\n for(let j = 0; j < n; j++) {\n if(grid[i][j] === 0) arr.push([i, j])\n }\n }\n const dirs = [[0,1], [0,-1], [1,0], [-1,0]]\n let num = 2\n for(const [i, j] of arr) {\n if(grid[i][j] !== 0) continue\n else {\n bfs(i, j, num)\n num++\n }\n }\n \n let res = 0\n const set = new Set()\n for(let i = 2; i < num; i++) {\n set.add(i)\n }\n \n for(let i = 0; i < m; i++) {\n for(let j = 0; j < n; j++) {\n if(grid[i][j] > 1 && invalid(i, j)) {\n set.delete(grid[i][j])\n } \n }\n }\n return set.size\n \n function invalid(i,j) {\n if(i === 0 || i === m - 1 || j === 0 || j === n - 1) return true\n return false\n }\n function bfs(i, j, v) {\n let q = [[i,j]]\n grid[i][j] = v\n while(q.length) {\n const tmp = []\n const size = q.length\n \n for(const [x, y] of q) {\n for(const [dx, dy] of dirs) {\n const nx = x + dx, ny = y + dy\n if(nx >= 0 && nx < m && ny >= 0 && ny < n && grid[nx][ny] === 0) {\n grid[nx][ny] = v\n tmp.push([nx, ny])\n }\n }\n }\n \n q = tmp\n }\n }\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720d68", + "questionid": 669, + "title": "Count Square Submatrices with All Ones", + "slug": "count-square-submatrices-with-all-ones", + "description": "Given a m * n matrix of ones and zeros, return how many square submatrices have all ones. ", + "category": [ + "Array", + "Dynamic Programming", + "Matrix" + ], + "complexity": "Medium", + "successrate": 74.2, + "totalsubmissions": 215047, + "totalaccepted": 159523, + "likes": 3221, + "dislikes": 53, + "hints": "Create an additive table that counts the sum of elements of submatrix with the superior corner at (0,0). Loop over all subsquares in O(n^3) and check if the sum make the whole array to be ones, if it checks then add 1 to the answer.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "matrix =\n[\n  [0,1,1,1],\n  [1,1,1,1],\n  [0,1,1,1]\n]", + "expected_output": "15", + "explanation": "There are 10 squares of side 1.\nThere are 4 squares of side 2.\nThere is 1 square of side 3.\nTotal number of squares = 10 + 4 + 1 = 15." + }, + { + "example_num": 2, + "expected_input": "matrix = \n[\n [1,0,1],\n [1,1,0],\n [1,1,0]\n]", + "expected_output": "7", + "explanation": "There are 6 squares of side 1. \nThere is 1 square of side 2. \nTotal number of squares = 6 + 1 = 7." + } + ], + "solution": "/**\n * @param {number[][]} matrix\n * @return {number}\n */\nconst countSquares = function (matrix) {\n const [m, n] = [matrix.length, matrix[0].length]\n let res = 0\n for(let i = 0; i < m; i++) {\n for(let j = 0; j < n; j++) {\n if(matrix[i][j] && i > 0 && j > 0) {\n matrix[i][j] = 1 + Math.min(\n matrix[i - 1][j],\n matrix[i][j - 1],\n matrix[i - 1][j - 1],\n )\n }\n res += matrix[i][j]\n }\n }\n return res\n}\n\n// another\n\n/**\n * @param {number[][]} matrix\n * @return {number}\n */\nconst countSquares = function (A) {\n const [M, N] = [A.length, A[0].length]\n let ans = 0\n for (let i = 0; i < M; ++i) {\n for (let j = 0; j < N; ++j) {\n if (A[i][j] && i > 0 && j > 0) {\n A[i][j] = 1 + Math.min(A[i - 1][j], A[i][j - 1], A[i - 1][j - 1])\n }\n ans += A[i][j]\n }\n }\n return ans\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720d69", + "questionid": 670, + "title": "Group the People Given the Group Size They Belong To", + "slug": "group-the-people-given-the-group-size-they-belong-to", + "description": "There are n people\u00a0that are split into some unknown number of groups. Each person is labeled with a\u00a0unique ID\u00a0from\u00a00\u00a0to\u00a0n - 1. You are given an integer array\u00a0groupSizes, where groupSizes[i]\u00a0is the size of the group that person\u00a0i\u00a0is in. For example, if\u00a0groupSizes[1] = 3, then\u00a0person\u00a01\u00a0must be in a\u00a0group of size\u00a03. Return\u00a0a list of groups\u00a0such that\u00a0each person\u00a0i\u00a0is in a group of size\u00a0groupSizes[i]. Each person should\u00a0appear in\u00a0exactly one group,\u00a0and every person must be in a group. If there are\u00a0multiple answers, return any of them. It is guaranteed that there will be at least one valid solution for the given input. ", + "category": [ + "Array", + "Hash Table" + ], + "complexity": "Medium", + "successrate": 85.3, + "totalsubmissions": 91779, + "totalaccepted": 78252, + "likes": 995, + "dislikes": 461, + "hints": "Put people's IDs with same groupSize into buckets, then split each bucket into groups. Greedy fill until you need a new group.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "groupSizes = [3,3,3,3,3,1,3]", + "expected_output": "[[5],[0,1,2],[3,4,6]]\nExplanation: \nThe first group is [5]. The size is 1, and groupSizes[5] = 1.\nThe second group is [0,1,2]. The size is 3, and groupSizes[0] = groupSizes[1] = groupSizes[2] = 3.\nThe third group is [3,4,6]. The size is 3, and groupSizes[3] = groupSizes[4] = groupSizes[6] = 3.\nOther possible solutions are [[2,1,6],[5],[0,4,3]] and [[5],[0,6,2],[4,3,1]].", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "groupSizes = [2,1,3,3,3,2]", + "expected_output": "[[1],[0,5],[2,3,4]]", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} groupSizes\n * @return {number[][]}\n */\nconst groupThePeople = function(groupSizes) {\n const hash = {}\n const n = groupSizes.length\n \n for(let i = 0; i < n; i++) {\n const size = groupSizes[i]\n if(hash[size] == null) hash[size] = []\n hash[size].push(i)\n }\n \n const keys = Object.keys(hash)\n // console.log(hash)\n const res = []\n for(let size of keys) {\n size = +size\n const arr = hash[size]\n for(let i = 0; i < arr.length; i += size) {\n res.push(arr.slice(i, i + size))\n }\n }\n \n return res\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720d6b", + "questionid": 672, + "title": "Convert Binary Number in a Linked List to Integer", + "slug": "convert-binary-number-in-a-linked-list-to-integer", + "description": "Given head which is a reference node to a singly-linked list. The value of each node in the linked list is either 0 or 1. The linked list holds the binary representation of a number. Return the decimal value of the number in the linked list. ", + "category": [ + "Linked List", + "Math" + ], + "complexity": "Easy", + "successrate": 82.7, + "totalsubmissions": 340360, + "totalaccepted": 281429, + "likes": 2462, + "dislikes": 123, + "hints": "Traverse the linked list and store all values in a string or array. convert the values obtained to decimal value. You can solve the problem in O(1) memory using bits operation. use shift left operation ( << ) and or operation ( | ) to get the decimal value in one operation.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "head = [1,0,1]", + "expected_output": "5", + "explanation": "(101) in base 2 = (5) in base 10" + }, + { + "example_num": 2, + "expected_input": "head = [0]", + "expected_output": "0", + "explanation": "" + } + ], + "solution": "/**\n * Definition for singly-linked list.\n * function ListNode(val, next) {\n * this.val = (val===undefined ? 0 : val)\n * this.next = (next===undefined ? null : next)\n * }\n */\n/**\n * @param {ListNode} head\n * @return {number}\n */\nconst getDecimalValue = function(head) {\n let res = 0\n\n while(head) {\n res = res * 2 + head.val\n head = head.next\n }\n return res\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720d6c", + "questionid": 673, + "title": "Maximum Side Length of a Square with Sum Less than or Equal to Threshold", + "slug": "maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold", + "description": "Given a m x n matrix mat and an integer threshold, return the maximum side-length of a square with a sum less than or equal to threshold or return 0 if there is no such square. ", + "category": [ + "Array", + "Binary Search", + "Matrix", + "Prefix Sum" + ], + "complexity": "Medium", + "successrate": 52.2, + "totalsubmissions": 45286, + "totalaccepted": 23625, + "likes": 766, + "dislikes": 59, + "hints": "Store prefix sum of all grids in another 2D array. Try all possible solutions and if you cannot find one return -1. If x is a valid answer then any y < x is also valid answer. Use binary search to find answer.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "mat = [[1,1,3,2,4,3,2],[1,1,3,2,4,3,2],[1,1,3,2,4,3,2]], threshold = 4", + "expected_output": "2", + "explanation": "The maximum side length of square with sum less than 4 is 2 as shown." + }, + { + "example_num": 2, + "expected_input": "mat = [[2,2,2,2,2],[2,2,2,2,2],[2,2,2,2,2],[2,2,2,2,2],[2,2,2,2,2]], threshold = 1", + "expected_output": "0", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[][]} mat\n * @param {number} threshold\n * @return {number}\n */\nconst maxSideLength = function (mat, threshold) {\n let m = mat.length\n let n = mat[0].length\n const sum = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0))\n\n let res = 0\n let len = 1 // square side length\n\n for (let i = 1; i <= m; i++) {\n for (let j = 1; j <= n; j++) {\n sum[i][j] =\n sum[i - 1][j] + sum[i][j - 1] - sum[i - 1][j - 1] + mat[i - 1][j - 1]\n\n if (\n i >= len &&\n j >= len &&\n sum[i][j] - sum[i - len][j] - sum[i][j - len] + sum[i - len][j - len] <=\n threshold\n )\n res = len++\n }\n }\n\n return res\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720d70", + "questionid": 677, + "title": "Find N Unique Integers Sum up to Zero", + "slug": "find-n-unique-integers-sum-up-to-zero", + "description": "Given an integer n, return any array containing n unique integers such that they add up to 0. ", + "category": [ + "Array", + "Math" + ], + "complexity": "Easy", + "successrate": 76.9, + "totalsubmissions": 175888, + "totalaccepted": 135316, + "likes": 1047, + "dislikes": 456, + "hints": "Return an array where the values are symmetric. (+x , -x). If n is odd, append value 0 in your returned array.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 5", + "expected_output": "[-7,-1,1,3,4]", + "explanation": "These arrays also are accepted [-5,-1,1,2,3] , [-3,-1,2,-2,4]." + }, + { + "example_num": 2, + "expected_input": "n = 3", + "expected_output": "[-1,0,1]", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "n = 1", + "expected_output": "[0]", + "explanation": "" + } + ], + "solution": "/**\n * @param {number} n\n * @return {number[]}\n */\nconst sumZero = function(n) {\n const num = ~~(n / 2)\n const odd = n % 2 === 1\n const res = pair(num)\n if(odd) res.push(0)\n return res\n};\n\nfunction pair(num) {\n const set = new Set()\n const res = []\n for(let i = 1; i <= num; i++) res.push(i, -i)\n return res\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720d72", + "questionid": 679, + "title": "Jump Game III", + "slug": "jump-game-iii", + "description": "Given an array of non-negative integers arr, you are initially positioned at start\u00a0index of the array. When you are at index i, you can jump\u00a0to i + arr[i] or i - arr[i], check if you can reach to any index with value 0. Notice that you can not jump outside of the array at any time. ", + "category": [ + "Array", + "Depth-First Search", + "Breadth-First Search" + ], + "complexity": "Medium", + "successrate": 62.8, + "totalsubmissions": 225811, + "totalaccepted": 141718, + "likes": 2638, + "dislikes": 63, + "hints": "Think of BFS to solve the problem. When you reach a position with a value = 0 then return true.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "arr = [4,2,3,0,3,1,2], start = 5", + "expected_output": "true", + "explanation": "All possible ways to reach at index 3 with value 0 are: \nindex 5 -> index 4 -> index 1 -> index 3 \nindex 5 -> index 6 -> index 4 -> index 1 -> index 3" + }, + { + "example_num": 2, + "expected_input": "arr = [4,2,3,0,3,1,2], start = 0", + "expected_output": "true \nExplanation: \nOne possible way to reach at index 3 with value 0 is: \nindex 0 -> index 4 -> index 1 -> index 3", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "arr = [3,0,2,1,2], start = 2", + "expected_output": "false\nExplanation: There is no way to reach at index 1 with value 0.", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} arr\n * @param {number} start\n * @return {boolean}\n */\nconst canReach = function(arr, start) {\n const s = new Set()\n return helper(arr, start, s)\n};\n\nfunction helper(arr, start, s) {\n if(start < 0 || start >= arr.length || s.has(start)) return false\n s.add(start)\n if(arr[start] === 0) return true\n \n return helper(arr, start + arr[start], s) || helper(arr, start - arr[start], s)\n}\n\n// another\n\n/**\n * @param {number[]} arr\n * @param {number} start\n * @return {boolean}\n */\nconst canReach = function (A, i) {\n return (\n 0 <= i &&\n i < A.length &&\n A[i] >= 0 &&\n (!(A[i] = -A[i]) || canReach(A, i + A[i]) || canReach(A, i - A[i]))\n )\n}\n\n// another\n\n/**\n * @param {number[]} arr\n * @param {number} start\n * @return {boolean}\n */\nconst canReach = function(arr, start) {\n const q = [start]\n const s = new Set()\n while(q.length) {\n const len = q.length\n for(let i = 0; i < len; i++) {\n const cur = q.shift()\n s.add(cur)\n if(arr[cur] === 0) return true\n if(!s.has(cur + arr[cur])) q.push(cur + arr[cur])\n if(!s.has(cur - arr[cur])) q.push(cur - arr[cur])\n }\n }\n return false\n};\n\n" + }, + { + "_id": "66f925ddfdfb8e1665720d74", + "questionid": 681, + "title": "XOR Queries of a Subarray", + "slug": "xor-queries-of-a-subarray", + "description": "You are given an array arr of positive integers. You are also given the array queries where queries[i] = [lefti, righti]. For each query i compute the XOR of elements from lefti to righti (that is, arr[lefti] XOR arr[lefti + 1] XOR ... XOR arr[righti] ). Return an array answer where answer[i] is the answer to the ith query. ", + "category": [ + "Array", + "Bit Manipulation", + "Prefix Sum" + ], + "complexity": "Medium", + "successrate": 71.2, + "totalsubmissions": 50087, + "totalaccepted": 35676, + "likes": 895, + "dislikes": 30, + "hints": "What is the result of x ^ y ^ x ? Compute the prefix sum for XOR. Process the queries with the prefix sum values.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "arr = [1,3,4,8], queries = [[0,1],[1,2],[0,3],[3,3]]", + "expected_output": "[2,7,14,8]", + "explanation": "The binary representation of the elements in the array are:\n1 = 0001 \n3 = 0011 \n4 = 0100 \n8 = 1000 \nThe XOR values for queries are:\n[0,1] = 1 xor 3 = 2 \n[1,2] = 3 xor 4 = 7 \n[0,3] = 1 xor 3 xor 4 xor 8 = 14 \n[3,3] = 8" + }, + { + "example_num": 2, + "expected_input": "arr = [4,8,2,10], queries = [[2,3],[1,3],[0,0],[0,3]]", + "expected_output": "[8,0,4,4]", + "explanation": "" + } + ], + "solution": " /**\n * @param {number[]} arr\n * @param {number[][]} queries\n * @return {number[]}\n */\nconst xorQueries = function(arr, queries) {\n const pre = [], n = arr.length\n let xor = arr[0]\n pre.push(xor)\n for(let i = 1; i < n; i++) {\n pre[i] = pre[i - 1] ^ arr[i]\n }\n\n const res = queries.map((e, i) => {\n const [l, r] = e\n return pre[r] ^ (l > 0 ? pre[l - 1] : 0)\n })\n return res\n};\n\n// another\n\n/**\n * @param {number[]} arr\n * @param {number[][]} queries\n * @return {number[]}\n */\nconst xorQueries = function(arr, queries) {\n const xorArr = []\n xorArr[0] = 0\n const n = arr.length\n for(let i = 0; i < n; i++) {\n const cur = arr[i]\n xorArr.push(cur ^ xorArr[xorArr.length - 1])\n }\n const res = []\n for(const [l, r] of queries) {\n res.push(xorArr[r + 1] ^ xorArr[l])\n }\n \n return res\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720d77", + "questionid": 684, + "title": "Minimum Flips to Make a OR b Equal to c", + "slug": "minimum-flips-to-make-a-or-b-equal-to-c", + "description": "Given 3 positives numbers a, b and c. Return the minimum flips required in some bits of a and b to make (\u00a0a OR b == c\u00a0). (bitwise OR operation).\r\nFlip operation\u00a0consists of change\u00a0any\u00a0single bit 1 to 0 or change the bit 0 to 1\u00a0in their binary representation. ", + "category": [ + "Bit Manipulation" + ], + "complexity": "Medium", + "successrate": 65.3, + "totalsubmissions": 36445, + "totalaccepted": 23792, + "likes": 428, + "dislikes": 37, + "hints": "Check the bits one by one whether they need to be flipped.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "a = 2, b = 6, c = 5", + "expected_output": "3\r\nExplanation: After flips a = 1 , b = 4 , c = 5 such that (a OR b == c)", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "a = 4, b = 2, c = 7", + "expected_output": "1", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "a = 1, b = 2, c = 3", + "expected_output": "0", + "explanation": "" + } + ], + "solution": null + }, + { + "_id": "66f925ddfdfb8e1665720d79", + "questionid": 686, + "title": "Minimum Distance to Type a Word Using Two Fingers", + "slug": "minimum-distance-to-type-a-word-using-two-fingers", + "description": "You have a keyboard layout as shown above in the X-Y plane, where each English uppercase letter is located at some coordinate. Given the string word, return the minimum total distance to type such string using only two fingers. The distance between coordinates (x1, y1) and (x2, y2) is |x1 - x2| + |y1 - y2|. Note that the initial positions of your two fingers are considered free so do not count towards your total distance, also your two fingers do not have to start at the first letter or the first two letters. ", + "category": [ + "String", + "Dynamic Programming" + ], + "complexity": "Hard", + "successrate": 60.3, + "totalsubmissions": 39380, + "totalaccepted": 23752, + "likes": 755, + "dislikes": 30, + "hints": "Use dynamic programming. dp[i][j][k]: smallest movements when you have one finger on i-th char and the other one on j-th char already having written k first characters from word.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "word = "CAKE"", + "expected_output": "3", + "explanation": "Using two fingers, one optimal way to type "CAKE" is: \nFinger 1 on letter 'C' -> cost = 0 \nFinger 1 on letter 'A' -> cost = Distance from letter 'C' to letter 'A' = 2 \nFinger 2 on letter 'K' -> cost = 0 \nFinger 2 on letter 'E' -> cost = Distance from letter 'K' to letter 'E' = 1 \nTotal distance = 3" + }, + { + "example_num": 2, + "expected_input": "word = "HAPPY"", + "expected_output": "6", + "explanation": "Using two fingers, one optimal way to type "HAPPY" is:\nFinger 1 on letter 'H' -> cost = 0\nFinger 1 on letter 'A' -> cost = Distance from letter 'H' to letter 'A' = 2\nFinger 2 on letter 'P' -> cost = 0\nFinger 2 on letter 'P' -> cost = Distance from letter 'P' to letter 'P' = 0\nFinger 1 on letter 'Y' -> cost = Distance from letter 'A' to letter 'Y' = 4\nTotal distance = 6" + } + ], + "solution": "/**\n * @param {string} word\n * @return {number}\n */\nconst minimumDistance = function (word) {\n const dp = Array.from({ length: 2 }, () =>\n new Array(27).fill(0).map(() => Array(27).fill(0))\n )\n const A = 'A'.charCodeAt(0)\n for (let pos = word.length - 1; pos >= 0; --pos) {\n let to = word[pos].charCodeAt(0) - A\n for (let i = 0; i < 27; ++i) {\n for (let j = 0; j < 27; ++j) {\n dp[pos % 2][i][j] = Math.min(\n dp[(pos + 1) % 2][to][i] + cost(j, to),\n dp[(pos + 1) % 2][to][j] + cost(i, to)\n )\n }\n }\n }\n return dp[0][26][26]\n}\nfunction cost(from, to) {\n if (from === 26) return 0\n return (\n Math.abs(((from / 6) >> 0) - ((to / 6) >> 0)) +\n Math.abs((from % 6) - (to % 6))\n )\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720d7b", + "questionid": 688, + "title": "Number of Sub-arrays of Size K and Average Greater than or Equal to Threshold", + "slug": "number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold", + "description": "Given an array of integers arr and two integers k and threshold, return the number of sub-arrays of size k and average greater than or equal to threshold. ", + "category": [ + "Array", + "Sliding Window" + ], + "complexity": "Medium", + "successrate": 67.8, + "totalsubmissions": 47808, + "totalaccepted": 32427, + "likes": 581, + "dislikes": 57, + "hints": "Start with a window of size K and test its average against the threshold. Keep moving the window by one element maintaining its size k until you cover the whole array. count number of windows that satisfy that its average is greater than the threshold.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "arr = [2,2,2,2,5,5,5,8], k = 3, threshold = 4", + "expected_output": "3", + "explanation": "Sub-arrays [2,5,5],[5,5,5] and [5,5,8] have averages 4, 5 and 6 respectively. All other sub-arrays of size 3 have averages less than 4 (the threshold)." + }, + { + "example_num": 2, + "expected_input": "arr = [11,13,17,23,29,31,7,5,2,3], k = 3, threshold = 5", + "expected_output": "6", + "explanation": "The first 6 sub-arrays of size 3 have averages greater than 5. Note that averages are not integers." + } + ], + "solution": "/**\n * @param {number[]} arr\n * @param {number} k\n * @param {number} threshold\n * @return {number}\n */\nconst numOfSubarrays = function(arr, k, threshold) {\n const n = arr.length\n const pre = Array(n).fill(0)\n pre[0] = arr[0]\n for(let i = 1; i < n; i++) {\n pre[i] = pre[i - 1] + arr[i]\n }\n \n let res = 0\n if(pre[k - 1] / k >= threshold) res++\n for(let i = k; i < n; i++) {\n if(pre[i] - pre[i - k] >= k * threshold) res++\n }\n return res\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720d7c", + "questionid": 689, + "title": "Angle Between Hands of a Clock", + "slug": "angle-between-hands-of-a-clock", + "description": "Given two numbers, hour and minutes, return the smaller angle (in degrees) formed between the hour and the minute hand. Answers within 10-5 of the actual value will be accepted as correct. ", + "category": [ + "Math" + ], + "complexity": "Medium", + "successrate": 63.2, + "totalsubmissions": 140671, + "totalaccepted": 88882, + "likes": 914, + "dislikes": 191, + "hints": "The tricky part is determining how the minute hand affects the position of the hour hand. Calculate the angles separately then find the difference.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "hour = 12, minutes = 30", + "expected_output": "165", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "hour = 3, minutes = 30", + "expected_output": "75", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "hour = 3, minutes = 15", + "expected_output": "7.5", + "explanation": "" + } + ], + "solution": "/**\n * @param {number} hour\n * @param {number} minutes\n * @return {number}\n */\nconst angleClock = function(hour, minutes) {\n const minutesAngle = minutes * 6;\n const hoursAngle = (hour + minutes / 60) * 30;\n const diff = Math.abs(minutesAngle - hoursAngle);\n return Math.min(diff, 360 - diff);\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720d7e", + "questionid": 691, + "title": "Print Words Vertically", + "slug": "print-words-vertically", + "description": "Given a string s.\u00a0Return\u00a0all the words vertically in the same order in which they appear in s.\r\nWords are returned as a list of strings, complete with\u00a0spaces when is necessary. (Trailing spaces are not allowed).\r\nEach word would be put on only one column and that in one column there will be only one word. ", + "category": [ + "Array", + "String", + "Simulation" + ], + "complexity": "Medium", + "successrate": 59.6, + "totalsubmissions": 43408, + "totalaccepted": 25873, + "likes": 431, + "dislikes": 87, + "hints": "Use the maximum length of words to determine the length of the returned answer. However, don't forget to remove trailing spaces.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "HOW ARE YOU"", + "expected_output": "["HAY","ORO","WEU"]\r\nExplanation: Each word is printed vertically. \r\n "HAY"\r\n "ORO"\r\n "WEU"", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "s = "TO BE OR NOT TO BE"", + "expected_output": "["TBONTB","OEROOE"," T"]\r\nExplanation: Trailing spaces is not allowed. \r\n"TBONTB"\r\n"OEROOE"\r\n" T"", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "s = "CONTEST IS COMING"", + "expected_output": "["CIC","OSO","N M","T I","E N","S G","T"]", + "explanation": "" + } + ], + "solution": "/**\n * @param {string} s\n * @return {string[]}\n */\nconst printVertically = function(s) {\n const arr = s.split(' ').filter(e => e !== '')\n const m = arr.length\n let n = 0\n for(const e of arr) {\n n = Math.max(n, e.length)\n }\n \n const mat = Array.from({ length: m }, () => Array(n).fill(' '))\n for(let i = 0; i < arr.length; i++) {\n const cur = mat[i]\n for(let j = 0; j < arr[i].length; j++) {\n mat[i][j] = arr[i][j]\n }\n }\n const res = []\n for(let j = 0; j < n; j++) {\n const col = []\n for(let i = 0; i < m; i++) {\n col.push(mat[i][j])\n }\n res.push(col.join('').trimEnd())\n }\n \n return res\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720d86", + "questionid": 699, + "title": "Number of Substrings Containing All Three Characters", + "slug": "number-of-substrings-containing-all-three-characters", + "description": "Given a string s\u00a0consisting only of characters a, b and c. Return the number of substrings containing at least\u00a0one occurrence of all these characters a, b and c. ", + "category": [ + "Hash Table", + "String", + "Sliding Window" + ], + "complexity": "Medium", + "successrate": 62.1, + "totalsubmissions": 57647, + "totalaccepted": 35808, + "likes": 1378, + "dislikes": 25, + "hints": "For each position we simply need to find the first occurrence of a/b/c on or after this position. So we can pre-compute three link-list of indices of each a, b, and c.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "abcabc"", + "expected_output": "10", + "explanation": "The substrings containing at least one occurrence of the characters ab and c are "abc", "abca", "abcab", "abcabc", "bca", "bcab", "bcabc", "cab", "cabc" and "abc" (again). " + }, + { + "example_num": 2, + "expected_input": "s = "aaacb"", + "expected_output": "3", + "explanation": "The substrings containing at least one occurrence of the characters ab and c are "aaacb", "aacb" and "acb". " + }, + { + "example_num": 3, + "expected_input": "s = "abc"", + "expected_output": "1", + "explanation": "" + } + ], + "solution": null + }, + { + "_id": "66f925ddfdfb8e1665720d53", + "questionid": 648, + "title": "Split a String in Balanced Strings", + "slug": "split-a-string-in-balanced-strings", + "description": "Balanced strings are those that have an equal quantity of 'L' and 'R' characters. Given a balanced string s, split it in the maximum amount of balanced strings. Return the maximum amount of split balanced strings. ", + "category": [ + "String", + "Greedy", + "Counting" + ], + "complexity": "Easy", + "successrate": 84.7, + "totalsubmissions": 231115, + "totalaccepted": 195643, + "likes": 1680, + "dislikes": 747, + "hints": "Loop from left to right maintaining a balance variable when it gets an L increase it by one otherwise decrease it by one. Whenever the balance variable reaches zero then we increase the answer by one.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "RLRRLLRLRL"", + "expected_output": "4", + "explanation": "s can be split into "RL", "RRLL", "RL", "RL", each substring contains same number of 'L' and 'R'." + }, + { + "example_num": 2, + "expected_input": "s = "RLRRRLLRLL"", + "expected_output": "2", + "explanation": "s can be split into "RL", "RRRLLRLL", each substring contains same number of 'L' and 'R'.\nNote that s cannot be split into "RL", "RR", "RL", "LR", "LL", because the 2nd and 5th substrings are not balanced." + }, + { + "example_num": 3, + "expected_input": "s = "LLLLRRRR"", + "expected_output": "1", + "explanation": "s can be split into "LLLLRRRR"." + } + ], + "solution": "/**\n * @param {string} s\n * @return {number}\n */\nconst balancedStringSplit = function(s) {\n let res = 0, num = 0\n for(let ch of s) {\n num += ch === 'L' ? 1 : -1\n if(num === 0) res++\n }\n return res\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720d55", + "questionid": 650, + "title": "Dice Roll Simulation", + "slug": "dice-roll-simulation", + "description": "A die simulator generates a random number from 1 to 6 for each roll. You introduced a constraint to the generator such that it cannot roll the number i more than rollMax[i] (1-indexed) consecutive times. Given an array of integers rollMax and an integer n, return the number of distinct sequences that can be obtained with exact n rolls. Since the answer may be too large, return it modulo 109 + 7. Two sequences are considered different if at least one element differs from each other. ", + "category": [ + "Array", + "Dynamic Programming" + ], + "complexity": "Hard", + "successrate": 47.8, + "totalsubmissions": 45213, + "totalaccepted": 21615, + "likes": 680, + "dislikes": 175, + "hints": "Think on Dynamic Programming. DP(pos, last) which means we are at the position pos having as last the last character seen.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 2, rollMax = [1,1,2,2,2,3]", + "expected_output": "34", + "explanation": "There will be 2 rolls of die, if there are no constraints on the die, there are 6 * 6 = 36 possible combinations. In this case, looking at rollMax array, the numbers 1 and 2 appear at most once consecutively, therefore sequences (1,1) and (2,2) cannot occur, so the final answer is 36-2 = 34." + }, + { + "example_num": 2, + "expected_input": "n = 2, rollMax = [1,1,1,1,1,1]", + "expected_output": "30", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "n = 3, rollMax = [1,1,1,2,2,3]", + "expected_output": "181", + "explanation": "" + } + ], + "solution": "/**\n * @param {number} n\n * @param {number[]} rollMax\n * @return {number}\n */\nconst dieSimulator = function(n, rollMax) {\n const mod = 10 ** 9 + 7\n const faces = rollMax.length\n const dp = Array.from({ length: n + 1 }, () => new Array(faces + 1).fill(0))\n dp[0][faces] = 1\n for(let j = 0; j < faces; j++) {\n dp[1][j] = 1\n }\n dp[1][faces] = faces\n for(let i = 2; i < n + 1; i++) {\n for(let j = 0; j < faces; j++) {\n for(let k = 1; k < rollMax[j] + 1; k++) {\n if(i - k < 0) break\n dp[i][j] += dp[i - k][faces] - dp[i - k][j]\n dp[i][j] %= mod\n }\n }\n dp[i][faces] = dp[i].reduce((ac, e) => ac + e, 0)\n }\n return dp[n][faces] % mod\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720d56", + "questionid": 651, + "title": "Maximum Equal Frequency", + "slug": "maximum-equal-frequency", + "description": "Given an array nums of positive integers, return the longest possible length of an array prefix of nums, such that it is possible to remove exactly one element from this prefix so that every number that has appeared in it will have the same number of occurrences. If after removing one element there are no remaining elements, it's still considered that every appeared number has the same number of ocurrences (0). ", + "category": [ + "Array", + "Hash Table" + ], + "complexity": "Hard", + "successrate": 36.6, + "totalsubmissions": 28983, + "totalaccepted": 10611, + "likes": 359, + "dislikes": 41, + "hints": "Keep track of the min and max frequencies. The number to be eliminated must have a frequency of 1, same as the others or the same +1.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [2,2,1,1,5,3,3,5]", + "expected_output": "7", + "explanation": "For the subarray [2,2,1,1,5,3,3] of length 7, if we remove nums[4] = 5, we will get [2,2,1,1,3,3], so that each number will appear exactly twice." + }, + { + "example_num": 2, + "expected_input": "nums = [1,1,1,2,2,2,3,3,3,4,4,4,5]", + "expected_output": "13", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} nums\n * @return {number}\n */\nconst maxEqualFreq = function (nums) {\n const freqCnt = {}, cnt = {}, { max } = Math\n\n let res = 0, maxF = 0, i = 0\n for(const e of nums) {\n if(cnt[e] == null) cnt[e] = 0\n cnt[e]++\n\n const f = cnt[e]\n\n if(freqCnt[f - 1] == null) freqCnt[f - 1] = 0\n if(freqCnt[f] == null) freqCnt[f] = 0\n \n if(freqCnt[f - 1] > 0) freqCnt[f - 1]--\n freqCnt[f]++\n\n maxF = max(maxF, f)\n\n /*\n cnt records the occurence of each num, freq records the frequence of number of occurences. max_F is the largest frequence.\n There are three cases which satify the condition:\n\n all elements appear exact once.\n all elements appear max_F times, except one appears once.\n all elements appear max_F-1 times, except one appears max_F.\n */\n if(\n maxF === 1 ||\n maxF * freqCnt[maxF] === i ||\n (maxF - 1) * (freqCnt[maxF - 1] + 1) === i\n ) {\n res = i + 1\n }\n\n i++\n }\n\n return res\n}\n\n// another\n\n/**\n * @param {number[]} nums\n * @return {number}\n */\nconst maxEqualFreq = function (nums) {\n const cnt = {},\n freq = {}\n let maxF = 0,\n res = 0\n nums.forEach((num, i) => {\n if (cnt[num] == null) cnt[num] = 0\n cnt[num] += 1\n if (freq[cnt[num] - 1] == null) freq[cnt[num] - 1] = 0\n if (freq[cnt[num]] == null) freq[cnt[num]] = 0\n freq[cnt[num] - 1] -= 1\n freq[cnt[num]] += 1\n maxF = Math.max(maxF, cnt[num])\n if (\n maxF * freq[maxF] === i ||\n (maxF - 1) * (freq[maxF - 1] + 1) === i ||\n maxF === 1\n )\n res = i + 1\n })\n return res\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720d58", + "questionid": 653, + "title": "Maximum Profit in Job Scheduling", + "slug": "maximum-profit-in-job-scheduling", + "description": "We have n jobs, where every job is scheduled to be done from startTime[i] to endTime[i], obtaining a profit of profit[i]. You're given the startTime, endTime and profit arrays, return the maximum profit you can take such that there are no two jobs in the subset with overlapping time range. If you choose a job that ends at time X you will be able to start another job that starts at time X. ", + "category": [ + "Array", + "Binary Search", + "Dynamic Programming", + "Sorting" + ], + "complexity": "Hard", + "successrate": 50.9, + "totalsubmissions": 216641, + "totalaccepted": 110214, + "likes": 3106, + "dislikes": 34, + "hints": "Think on DP. Sort the elements by starting time, then define the dp[i] as the maximum profit taking elements from the suffix starting at i. Use binarySearch (lower_bound/upper_bound on C++) to get the next index for the DP transition.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "startTime = [1,2,3,3], endTime = [3,4,5,6], profit = [50,10,40,70]", + "expected_output": "120", + "explanation": "The subset chosen is the first and fourth job. \nTime range [1-3]+[3-6] , we get profit of 120 = 50 + 70." + }, + { + "example_num": 2, + "expected_input": "startTime = [1,2,3,4,6], endTime = [3,5,10,6,9], profit = [20,20,100,70,60]", + "expected_output": "150", + "explanation": "The subset chosen is the first, fourth and fifth job. \nProfit obtained 150 = 20 + 70 + 60." + }, + { + "example_num": 3, + "expected_input": "startTime = [1,1,1], endTime = [2,3,4], profit = [5,6,4]", + "expected_output": "6", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} startTime\n * @param {number[]} endTime\n * @param {number[]} profit\n * @return {number}\n */\nconst jobScheduling = function (startTime, endTime, profit) {\n const n = startTime.length\n const items = Array(n)\n for(let i = 0;i < n; i++) items[i] = [startTime[i], endTime[i], profit[i]]\n items.sort((a, b) => a[1] - b[1])\n const dpEndTime = [0]\n const dpProfit = [0]\n for(const [s, e, p] of items) {\n const prevIdx = binarySearch(dpEndTime, 0, dpEndTime.length - 1, s)\n const curProfit = dpProfit[prevIdx] + p, maxProfit = dpProfit[dpProfit.length - 1]\n if(curProfit > maxProfit) {\n dpProfit.push(curProfit)\n dpEndTime.push(e)\n }\n }\n \n return dpProfit[dpProfit.length - 1]\n}\n\nfunction binarySearch(arr, l, r, x) {\n while (l < r) {\n const mid = r - ((r - l) >> 1)\n if (arr[mid] > x) r = mid - 1\n else l = mid\n }\n return l\n}\n\n\n// another\n\n/**\n * @param {number[]} startTime\n * @param {number[]} endTime\n * @param {number[]} profit\n * @return {number}\n */\nconst jobScheduling = function (startTime, endTime, profit) {\n const n = startTime.length\n const items = Array.from({ length: startTime.length }, () => Array(3).fill(0))\n for (let i = 0; i < startTime.length; i++) {\n items[i] = [startTime[i], endTime[i], profit[i]]\n }\n items.sort((a1, a2) => a1[1] - a2[1])\n const dpProfit = [0]\n for (let i = 0; i < n; i++) {\n const [s, e, p] = items[i]\n let prevIdx = -1\n for(let j = i - 1; j >= 0; j--) {\n if(items[j][1] <= items[i][0]) {\n prevIdx = j\n break\n }\n }\n const curProfit = (prevIdx === -1 ? 0 : dpProfit[prevIdx]) + p\n dpProfit[i] = Math.max(dpProfit[dpProfit.length - 1], curProfit)\n }\n return dpProfit[dpProfit.length - 1]\n}\n\n\n// another\n\n\n/**\n * @param {number[]} startTime\n * @param {number[]} endTime\n * @param {number[]} profit\n * @return {number}\n */\nconst jobScheduling = function (startTime, endTime, profit) {\n const items = Array.from({ length: startTime.length }, () => Array(3).fill(0))\n for (let i = 0; i < startTime.length; i++) {\n items[i] = [startTime[i], endTime[i], profit[i]]\n }\n items.sort((a1, a2) => a1[1] - a2[1])\n const dpEndTime = []\n const dpProfit = []\n dpEndTime.push(0)\n dpProfit.push(0)\n for (let item of items) {\n const s = item[0],\n e = item[1],\n p = item[2]\n // find previous endTime index\n const prevIdx = binarySearch(dpEndTime, 0, dpEndTime.length - 1, s)\n const currProfit = dpProfit[prevIdx] + p,\n maxProfit = dpProfit[dpProfit.length - 1]\n if (currProfit > maxProfit) {\n dpProfit.push(currProfit)\n dpEndTime.push(e)\n }\n }\n return dpProfit[dpProfit.length - 1]\n}\n\nfunction binarySearch(arr, l, r, x) {\n while (l <= r) {\n const mid = l + ((r - l) >> 1)\n if (arr[mid] > x) r = mid - 1\n else {\n if (mid == arr.length - 1 || arr[mid + 1] > x) return mid\n l = mid + 1\n }\n }\n return -1\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720d60", + "questionid": 661, + "title": "Find Palindrome With Fixed Length", + "slug": "find-palindrome-with-fixed-length", + "description": "Given an integer array queries and a positive integer intLength, return an array answer where answer[i] is either the queries[i]th smallest positive palindrome of length intLength or -1 if no such palindrome exists. A palindrome is a number that reads the same backwards and forwards. Palindromes cannot have leading zeros. ", + "category": [ + "Array", + "Math" + ], + "complexity": "Medium", + "successrate": 34.3, + "totalsubmissions": 28626, + "totalaccepted": 9810, + "likes": 298, + "dislikes": 165, + "hints": "For any value of queries[i] and intLength, how can you check if there exists at least queries[i] palindromes of length intLength? Since a palindrome reads the same forwards and backwards, consider how you can efficiently find the first half (ceil(intLength/2) digits) of the palindrome.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "queries = [1,2,3,4,5,90], intLength = 3", + "expected_output": "[101,111,121,131,141,999]", + "explanation": "The first few palindromes of length 3 are:\n101, 111, 121, 131, 141, 151, 161, 171, 181, 191, 202, ...\nThe 90th palindrome of length 3 is 999." + }, + { + "example_num": 2, + "expected_input": "queries = [2,4,6], intLength = 4", + "expected_output": "[1111,1331,1551]", + "explanation": "The first six palindromes of length 4 are:\n1001, 1111, 1221, 1331, 1441, and 1551." + } + ], + "solution": "/**\n * @param {number[]} queries\n * @param {number} intLength\n * @return {number[]}\n */\nvar kthPalindrome = function(queries, intLength) {\n if (intLength == 1) {\n let res = []\n for (let item of queries) {\n if (item <= 9) res.push(item)\n else res.push(-1) \n }\n return res \n }\n\n let n = Math.floor(intLength / 2)\n let ref = +(\"1\"+\"0\".repeat(n-1))\n\n if (intLength % 2 == 0) {\n let res = []\n for (let item of queries) res.push(gen_even(item))\n return res \n } else {\n let res = []\n for (let item of queries) res.push(gen_odd(item))\n return res\n }\n\n function gen_even(val) {\n let part = ref + val - 1\n part = '' + part\n if (part.length != n) return -1\n return +(part + part.split('').reverse().join('')) \n }\n\n\n function gen_odd(val) {\n let mod = (val - 1) % 10\n let div = Math.floor((val - 1) / 10)\n let part = ref + div\n mod = '' + mod, part = '' + part\n if (part.length != n) return -1\n return +(part + mod + part.split('').reverse().join('')) \n }\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720d63", + "questionid": 664, + "title": "Greatest Sum Divisible by Three", + "slug": "greatest-sum-divisible-by-three", + "description": "Given an array\u00a0nums\u00a0of integers, we need to find the maximum possible sum of elements of the array such that it is divisible by three. ", + "category": [ + "Array", + "Dynamic Programming", + "Greedy" + ], + "complexity": "Medium", + "successrate": 50.8, + "totalsubmissions": 73929, + "totalaccepted": 37564, + "likes": 1184, + "dislikes": 34, + "hints": "Represent the state as DP[pos][mod]: maximum possible sum starting in the position \"pos\" in the array where the current sum modulo 3 is equal to mod.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [3,6,5,1,8]", + "expected_output": "18", + "explanation": "Pick numbers 3, 6, 1 and 8 their sum is 18 (maximum sum divisible by 3)." + }, + { + "example_num": 2, + "expected_input": "nums = [4]", + "expected_output": "0", + "explanation": "Since 4 is not divisible by 3, do not pick any number." + }, + { + "example_num": 3, + "expected_input": "nums = [1,2,3,4,4]", + "expected_output": "12", + "explanation": "Pick numbers 1, 3, 4 and 4 their sum is 12 (maximum sum divisible by 3)." + } + ], + "solution": "/**\n * @param {number[]} nums\n * @return {number}\n */\nconst maxSumDivThree = function (nums) {\n const n = nums.length\n let dp = [0, -Infinity, -Infinity]\n for (let i = n - 1; i >= 0; i--) {\n const nextDp = []\n for (let j = 0; j < 3; j++) {\n const nextRemain = nums[i] % 3\n nextDp[j] = Math.max(nums[i] + dp[(nextRemain + j) % 3], dp[j])\n }\n dp = nextDp\n }\n return dp[0]\n}\n\n// another\n\n/**\n * @param {number[]} nums\n * @return {number}\n */\nconst maxSumDivThree = function(nums) {\n const sum = nums.reduce((ac, el) => ac + el, 0)\n if(sum % 3 === 0) return sum\n const remainder = sum % 3\n const comp = 3 - remainder\n nums.sort((a, b) => a - b)\n const re = [], rc = []\n for(let i = 0, len = nums.length; i < len; i++) {\n if(nums[i] % 3 === remainder) {\n if(re.length < 1) re.push(i)\n }\n if(nums[i] % 3 === comp) {\n if(rc.length < 2) rc.push(i)\n }\n if(re.length === 1 && rc.length === 2) break\n }\n if(re.length === 1 && rc.length === 2) {\n return Math.max(sum - nums[re[0]], sum - nums[rc[0]] - nums[rc[1]])\n } else if(re.length === 1) {\n return sum - nums[re[0]]\n } else if(rc.length === 2) {\n return sum - nums[rc[0]] - nums[rc[1]]\n } else {\n return 0\n }\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720d67", + "questionid": 668, + "title": "Number of Ways to Stay in the Same Place After Some Steps", + "slug": "number-of-ways-to-stay-in-the-same-place-after-some-steps", + "description": "You have a pointer at index 0 in an array of size arrLen. At each step, you can move 1 position to the left, 1 position to the right in the array, or stay in the same place (The pointer should not be placed outside the array at any time). Given two integers steps and arrLen, return the number of ways such that your pointer still at index 0 after exactly steps steps. Since the answer may be too large, return it modulo 109 + 7. ", + "category": [ + "Dynamic Programming" + ], + "complexity": "Hard", + "successrate": 43.4, + "totalsubmissions": 63005, + "totalaccepted": 27329, + "likes": 531, + "dislikes": 30, + "hints": "Try with Dynamic programming, dp(pos,steps): number of ways to back pos = 0 using exactly \"steps\" moves. Notice that the computational complexity does not depend of \"arrlen\".", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "steps = 3, arrLen = 2", + "expected_output": "4\nExplanation: There are 4 differents ways to stay at index 0 after 3 steps.\nRight, Left, Stay\nStay, Right, Left\nRight, Stay, Left\nStay, Stay, Stay", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "steps = 2, arrLen = 4", + "expected_output": "2", + "explanation": "There are 2 differents ways to stay at index 0 after 2 steps\nRight, Left\nStay, Stay" + }, + { + "example_num": 3, + "expected_input": "steps = 4, arrLen = 2", + "expected_output": "8", + "explanation": "" + } + ], + "solution": "/**\n * @param {number} steps\n * @param {number} arrLen\n * @return {number}\n */\nconst numWays = function (steps, arrLen) {\n const MOD = 10 ** 9 + 7\n const memo = Array.from({ length: (steps >> 1) + 1 }, () =>\n Array(steps + 1).fill(-1)\n )\n return dp(0, steps)\n function dp(i, steps) {\n if (steps === 0 && i === 0) return 1\n if (i < 0 || i >= arrLen || steps === 0 || i > steps) return 0\n if (memo[i][steps] !== -1) return memo[i][steps]\n return (memo[i][steps] =\n ((dp(i + 1, steps - 1) % MOD) +\n (dp(i - 1, steps - 1) % MOD) +\n (dp(i, steps - 1) % MOD)) %\n MOD)\n }\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720d6e", + "questionid": 675, + "title": "Find Numbers with Even Number of Digits", + "slug": "find-numbers-with-even-number-of-digits", + "description": "Given an array nums of integers, return how many of them contain an even number of digits. ", + "category": [ + "Array" + ], + "complexity": "Easy", + "successrate": 77.1, + "totalsubmissions": 545968, + "totalaccepted": 421174, + "likes": 1225, + "dislikes": 98, + "hints": "How to compute the number of digits of a number ? Divide the number by 10 again and again to get the number of digits.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [12,345,2,6,7896]", + "expected_output": "2\nExplanation: \n12 contains 2 digits (even number of digits). \n345 contains 3 digits (odd number of digits). \n2 contains 1 digit (odd number of digits). \n6 contains 1 digit (odd number of digits). \n7896 contains 4 digits (even number of digits). \nTherefore only 12 and 7896 contain an even number of digits.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "nums = [555,901,482,1771]", + "expected_output": "1 \nExplanation: \nOnly 1771 contains an even number of digits.", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} nums\n * @return {number}\n */\nconst findNumbers = function(nums) {\n let res = 0\n for(const e of nums) {\n const str = '' + e\n if(str.length % 2 === 0) res++\n }\n return res\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720d71", + "questionid": 678, + "title": "All Elements in Two Binary Search Trees", + "slug": "all-elements-in-two-binary-search-trees", + "description": "Given two binary search trees root1 and root2, return a list containing all the integers from both trees sorted in ascending order. ", + "category": [ + "Tree", + "Depth-First Search", + "Binary Search Tree", + "Sorting", + "Binary Tree" + ], + "complexity": "Medium", + "successrate": 79.6, + "totalsubmissions": 200538, + "totalaccepted": 159646, + "likes": 2179, + "dislikes": 64, + "hints": "Traverse the first tree in list1 and the second tree in list2. Merge the two trees in one list and sort it.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root1 = [2,1,4], root2 = [1,0,3]", + "expected_output": "[0,1,1,2,3,4]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "root1 = [1,null,8], root2 = [8,1]", + "expected_output": "[1,1,8,8]", + "explanation": "" + } + ], + "solution": "/**\n * Definition for a binary tree node.\n * function TreeNode(val, left, right) {\n * this.val = (val===undefined ? 0 : val)\n * this.left = (left===undefined ? null : left)\n * this.right = (right===undefined ? null : right)\n * }\n */\n/**\n * @param {TreeNode} root1\n * @param {TreeNode} root2\n * @return {number[]}\n */\nvar getAllElements = function(root1, root2) {\n const set1 = new Set(), set2 = new Set()\n traverse(root1, set1)\n traverse(root2, set2)\n const res = []\n const it1 = set1[Symbol.iterator]()\n const it2 = set2[Symbol.iterator]()\n let { value: value1, done: done1 } = it1.next()\n let { value: value2, done: done2 } = it2.next()\n while(done1 === false || done2 === false) {\n if(done2 || value1 < value2) {\n res.push(value1)\n const obj = it1.next()\n value1 = obj.value\n done1 = obj.done\n }else {\n res.push(value2)\n const obj = it2.next()\n value2 = obj.value\n done2 = obj.done\n }\n }\n \n \n return res\n \n \n function traverse(node, set) {\n if(node == null) return\n traverse(node.left, set)\n set.add(node.val)\n traverse(node.right, set)\n }\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720d75", + "questionid": 682, + "title": "Get Watched Videos by Your Friends", + "slug": "get-watched-videos-by-your-friends", + "description": "There are n people, each person has a unique id between 0 and n-1. Given the arrays watchedVideos and friends, where watchedVideos[i] and friends[i] contain the list of watched videos and the list of friends respectively for the person with id = i. Level 1 of videos are all watched videos by your\u00a0friends, level 2 of videos are all watched videos by the friends of your\u00a0friends and so on. In general, the level k of videos are all\u00a0watched videos by people\u00a0with the shortest path exactly equal\u00a0to\u00a0k with you. Given your\u00a0id and the level of videos, return the list of videos ordered by their frequencies (increasing). For videos with the same frequency order them alphabetically from least to greatest. ", + "category": [ + "Array", + "Hash Table", + "Breadth-First Search", + "Sorting" + ], + "complexity": "Medium", + "successrate": 45.2, + "totalsubmissions": 33009, + "totalaccepted": 14910, + "likes": 207, + "dislikes": 289, + "hints": "Do BFS to find the kth level friends. Then collect movies saw by kth level friends and sort them accordingly.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "watchedVideos = [["A","B"],["C"],["B","C"],["D"]], friends = [[1,2],[0,3],[0,3],[1,2]], id = 0, level = 1", + "expected_output": "["B","C"]", + "explanation": "You have id = 0 (green color in the figure) and your friends are (yellow color in the figure):\nPerson with id = 1 -> watchedVideos = ["C"] \nPerson with id = 2 -> watchedVideos = ["B","C"] \nThe frequencies of watchedVideos by your friends are: \nB -> 1 \nC -> 2" + }, + { + "example_num": 2, + "expected_input": "watchedVideos = [["A","B"],["C"],["B","C"],["D"]], friends = [[1,2],[0,3],[0,3],[1,2]], id = 0, level = 2", + "expected_output": "["D"]", + "explanation": "You have id = 0 (green color in the figure) and the only friend of your friends is the person with id = 3 (yellow color in the figure)." + } + ], + "solution": null + }, + { + "_id": "66f925ddfdfb8e1665720d76", + "questionid": 683, + "title": "Minimum Insertion Steps to Make a String Palindrome", + "slug": "minimum-insertion-steps-to-make-a-string-palindrome", + "description": "Given a string s. In one step you can insert any character at any index of the string. Return the minimum number of steps to make s\u00a0palindrome. A\u00a0Palindrome String\u00a0is one that reads the same backward as well as forward. ", + "category": [ + "String", + "Dynamic Programming" + ], + "complexity": "Hard", + "successrate": 63.6, + "totalsubmissions": 72187, + "totalaccepted": 45892, + "likes": 1686, + "dislikes": 25, + "hints": "Is dynamic programming suitable for this problem ? If we know the longest palindromic sub-sequence is x and the length of the string is n then, what is the answer to this problem? It is n - x as we need n - x insertions to make the remaining characters also palindrome.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "zzazz"", + "expected_output": "0", + "explanation": "The string "zzazz" is already palindrome we do not need any insertions." + }, + { + "example_num": 2, + "expected_input": "s = "mbadm"", + "expected_output": "2", + "explanation": "String can be "mbdadbm" or "mdbabdm"." + }, + { + "example_num": 3, + "expected_input": "s = "leetcode"", + "expected_output": "5", + "explanation": "Inserting 5 characters the string becomes "leetcodocteel"." + } + ], + "solution": "/**\n * @param {string} s\n * @return {number}\n */\nconst minInsertions = function (s) {\n const dp = [...Array(501)].map((x) => Array(501).fill(0))\n const N = s.length\n for (let i = N - 1; i >= 0; --i)\n for (let j = i + 1; j <= N; ++j)\n if (s[i] == s[j - 1]) dp[i][j] = dp[i + 1][j - 1]\n else dp[i][j] = 1 + Math.min(dp[i + 1][j], dp[i][j - 1])\n return dp[0][N]\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720d78", + "questionid": 685, + "title": "Number of Operations to Make Network Connected", + "slug": "number-of-operations-to-make-network-connected", + "description": "There are n computers numbered from 0 to n - 1 connected by ethernet cables connections forming a network where connections[i] = [ai, bi] represents a connection between computers ai and bi. Any computer can reach any other computer directly or indirectly through the network. You are given an initial computer network connections. You can extract certain cables between two directly connected computers, and place them between any pair of disconnected computers to make them directly connected. Return the minimum number of times you need to do this in order to make all the computers connected. If it is not possible, return -1. ", + "category": [ + "Depth-First Search", + "Breadth-First Search", + "Union Find", + "Graph" + ], + "complexity": "Medium", + "successrate": 57.7, + "totalsubmissions": 127191, + "totalaccepted": 73342, + "likes": 2025, + "dislikes": 32, + "hints": "As long as there are at least (n - 1) connections, there is definitely a way to connect all computers. Use DFS to determine the number of isolated computer clusters.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 4, connections = [[0,1],[0,2],[1,2]]", + "expected_output": "1", + "explanation": "Remove cable between computer 1 and 2 and place between computers 1 and 3." + }, + { + "example_num": 2, + "expected_input": "n = 6, connections = [[0,1],[0,2],[0,3],[1,2],[1,3]]", + "expected_output": "2", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "n = 6, connections = [[0,1],[0,2],[0,3],[1,2]]", + "expected_output": "-1", + "explanation": "There are not enough cables." + } + ], + "solution": null + }, + { + "_id": "66f925ddfdfb8e1665720d81", + "questionid": 694, + "title": "Remove Palindromic Subsequences", + "slug": "remove-palindromic-subsequences", + "description": "You are given a string s consisting only of letters 'a' and 'b'. In a single step you can remove one palindromic subsequence from s. Return the minimum number of steps to make the given string empty. A string is a subsequence of a given string if it is generated by deleting some characters of a given string without changing its order. Note that a subsequence does not necessarily need to be contiguous. A string is called palindrome if is one that reads the same backward as well as forward. ", + "category": [ + "Two Pointers", + "String" + ], + "complexity": "Easy", + "successrate": 69.5, + "totalsubmissions": 77351, + "totalaccepted": 53790, + "likes": 191, + "dislikes": 304, + "hints": "Use the fact that string contains only 2 characters. Are subsequences composed of only one type of letter always palindrome strings ?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "ababa"", + "expected_output": "1", + "explanation": "s is already a palindrome, so its entirety can be removed in a single step." + }, + { + "example_num": 2, + "expected_input": "s = "abb"", + "expected_output": "2", + "explanation": ""abb" -> "bb" -> "". \nRemove palindromic subsequence "a" then "bb"." + }, + { + "example_num": 3, + "expected_input": "s = "baabb"", + "expected_output": "2", + "explanation": ""baabb" -> "b" -> "". \nRemove palindromic subsequence "baab" then "b"." + } + ], + "solution": "/**\n * @param {string} s\n * @return {number}\n */\nconst removePalindromeSub = function(s) {\n if(s == null || s === '') return 0\n if(chk(s)) return 1\n return 2\n};\n\nfunction chk(s) {\n let l = 0, r = s.length - 1\n while(l < r) {\n if(s[l] !== s[r]) return false\n l++\n r--\n }\n \n return true\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720d82", + "questionid": 695, + "title": "Filter Restaurants by Vegan-Friendly, Price and Distance", + "slug": "filter-restaurants-by-vegan-friendly-price-and-distance", + "description": "Given the array restaurants where \u00a0restaurants[i] = [idi, ratingi, veganFriendlyi, pricei, distancei]. You have to filter the restaurants using three filters. The veganFriendly filter will be either true (meaning you should only include restaurants with veganFriendlyi set to true)\u00a0or false\u00a0(meaning you can include any restaurant). In addition, you have the filters\u00a0maxPrice and maxDistance\u00a0which\u00a0are the maximum value for price and distance of restaurants you should consider respectively. Return the array of restaurant IDs after filtering, ordered by rating from highest to lowest. For restaurants with the same rating, order them by id from highest to lowest. For simplicity veganFriendlyi and veganFriendly take value 1 when it is true, and 0 when it is false. ", + "category": [ + "Array", + "Sorting" + ], + "complexity": "Medium", + "successrate": 58.8, + "totalsubmissions": 36990, + "totalaccepted": 21750, + "likes": 208, + "dislikes": 174, + "hints": "Do the filtering and sort as said. Note that the id may not be the index in the array.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "restaurants = [[1,4,1,40,10],[2,8,0,50,5],[3,8,1,30,4],[4,10,0,10,3],[5,1,1,15,1]], veganFriendly = 1, maxPrice = 50, maxDistance = 10", + "expected_output": "[3,1,5] \nExplanation: \nThe restaurants are:\nRestaurant 1 [id=1, rating=4, veganFriendly=1, price=40, distance=10]\nRestaurant 2 [id=2, rating=8, veganFriendly=0, price=50, distance=5]\nRestaurant 3 [id=3, rating=8, veganFriendly=1, price=30, distance=4]\nRestaurant 4 [id=4, rating=10, veganFriendly=0, price=10, distance=3]\nRestaurant 5 [id=5, rating=1, veganFriendly=1, price=15, distance=1] \nAfter filter restaurants with veganFriendly = 1, maxPrice = 50 and maxDistance = 10 we have restaurant 3, restaurant 1 and restaurant 5 (ordered by rating from highest to lowest).", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "restaurants = [[1,4,1,40,10],[2,8,0,50,5],[3,8,1,30,4],[4,10,0,10,3],[5,1,1,15,1]], veganFriendly = 0, maxPrice = 50, maxDistance = 10", + "expected_output": "[4,3,2,1,5]", + "explanation": "The restaurants are the same as in example 1, but in this case the filter veganFriendly = 0, therefore all restaurants are considered." + }, + { + "example_num": 3, + "expected_input": "restaurants = [[1,4,1,40,10],[2,8,0,50,5],[3,8,1,30,4],[4,10,0,10,3],[5,1,1,15,1]], veganFriendly = 0, maxPrice = 30, maxDistance = 3", + "expected_output": "[4,5]", + "explanation": "" + } + ], + "solution": null + }, + { + "_id": "66f925ddfdfb8e1665720d88", + "questionid": 701, + "title": "Reduce Array Size to The Half", + "slug": "reduce-array-size-to-the-half", + "description": "You are given an integer array arr. You can choose a set of integers and remove all the occurrences of these integers in the array. Return the minimum size of the set so that at least half of the integers of the array are removed. ", + "category": [ + "Array", + "Hash Table", + "Greedy", + "Sorting", + "Heap (Priority Queue)" + ], + "complexity": "Medium", + "successrate": 68.4, + "totalsubmissions": 121669, + "totalaccepted": 83223, + "likes": 1228, + "dislikes": 84, + "hints": "Count the frequency of each integer in the array. Start with an empty set, add to the set the integer with the maximum frequency. Keep Adding the integer with the max frequency until you remove at least half of the integers.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "arr = [3,3,3,3,5,5,5,2,2,7]", + "expected_output": "2", + "explanation": "Choosing {3,7} will make the new array [5,5,5,2,2] which has size 5 (i.e equal to half of the size of the old array).\nPossible sets of size 2 are {3,5},{3,2},{5,2}.\nChoosing set {2,7} is not possible as it will make the new array [3,3,3,3,5,5,5] which has a size greater than half of the size of the old array." + }, + { + "example_num": 2, + "expected_input": "arr = [7,7,7,7,7,7]", + "expected_output": "1", + "explanation": "The only possible set you can choose is {7}. This will make the new array empty." + } + ], + "solution": "/**\n * @param {number[]} arr\n * @return {number}\n */\nvar minSetSize = function(arr) {\n const hash = {}\n for(const e of arr) {\n if(hash[e] == null) hash[e] = 0\n hash[e]++\n }\n const n = arr.length\n const entries = Object.entries(hash)\n entries.sort((a, b) => b[1] - a[1])\n let res= 0\n let cnt = 0\n for(const [k, v] of entries) {\n cnt += v\n res++\n if(cnt >= n / 2) break\n }\n \n return res\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720d8b", + "questionid": 704, + "title": "Maximum Students Taking Exam", + "slug": "maximum-students-taking-exam", + "description": "Given a m\u00a0* n\u00a0matrix seats\u00a0\u00a0that represent seats distributions\u00a0in a classroom.\u00a0If a seat\u00a0is\u00a0broken, it is denoted by '#' character otherwise it is denoted by a '.' character. Students can see the answers of those sitting next to the left, right, upper left and upper right, but he cannot see the answers of the student sitting\u00a0directly in front or behind him. Return the maximum number of students that can take the exam together\u00a0without any cheating being possible.. Students must be placed in seats in good condition. ", + "category": [ + "Array", + "Dynamic Programming", + "Bit Manipulation", + "Matrix", + "Bitmask" + ], + "complexity": "Hard", + "successrate": 46.9, + "totalsubmissions": 21205, + "totalaccepted": 9937, + "likes": 554, + "dislikes": 11, + "hints": "Students in row i only can see exams in row i+1. Use Dynamic programming to compute the result given a (current row, bitmask people seated in previous row).", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "seats = [["#",".","#","#",".","#"],\n  [".","#","#","#","#","."],\n  ["#",".","#","#",".","#"]]", + "expected_output": "4", + "explanation": "Teacher can place 4 students in available seats so they don't cheat on the exam." + }, + { + "example_num": 2, + "expected_input": "seats = [[".","#"],\n  ["#","#"],\n  ["#","."],\n  ["#","#"],\n  [".","#"]]", + "expected_output": "3", + "explanation": "Place all students in available seats." + }, + { + "example_num": 3, + "expected_input": "seats = [["#",".",".",".","#"],\n  [".","#",".","#","."],\n  [".",".","#",".","."],\n  [".","#",".","#","."],\n  ["#",".",".",".","#"]]", + "expected_output": "10", + "explanation": "Place students in available seats in column 1, 3 and 5." + } + ], + "solution": "/**\n * @param {character[][]} seats\n * @return {number}\n */\nconst maxStudents = function(seats) {\n const m = seats.length, n = seats[0].length, limit = 1 << n\n const dp = Array.from({ length: m + 1}, () => Array(limit).fill(0))\n \n let res = 0\n for(let i = 1; i <= m; i++) {\n for(let mask = 0; mask < limit; mask++) {\n let valid = true\n for(let j = 0; j < n; j++) {\n if(seats[i - 1][j] === '#' && ((mask >> j) & 1) ) {\n valid = false\n break\n }\n if(j < n - 1 && ((mask >> j) & 1) && ((mask >> (j + 1)) & 1) ) {\n valid = false\n break\n }\n }\n \n if(!valid) {\n dp[i][mask] = -1\n continue\n }\n \n for(let pre = 0; pre < limit; pre++) {\n if(dp[i - 1][pre] === -1) continue\n if( (pre & (mask >> 1)) !== 0 || (pre & (mask << 1)) !== 0 ) continue\n dp[i][mask] = Math.max(dp[i][mask], dp[i - 1][pre])\n }\n \n dp[i][mask] += bitCnt(mask)\n \n res = Math.max(res, dp[i][mask])\n }\n }\n \n return res\n \n function bitCnt(num) {\n let res = 0\n while(num) {\n if(num & 1) res++\n num = num >> 1\n }\n \n return res\n }\n};\n\n// another\n\n\n/**\n * @param {character[][]} seats\n * @return {number}\n */\nconst maxStudents = function (seats) {\n if (!seats.length) return 0\n const lastPos = 1 << seats[0].length\n const classroom = seats.map((row) =>\n row.reduce((a, c, i) => (c === '#' ? a : a | (1 << i)), 0)\n )\n const dp = new Array(seats.length + 1).fill(null).map(() => new Map())\n dp[0].set(0, 0)\n for (let row = 0; row < seats.length; row++) {\n let queue = [0]\n let numStudents = 0\n while (queue.length > 0) {\n const next = []\n for (let arrangement of queue) {\n let max = 0\n for (let [prevArrang, count] of dp[row]) {\n if (conflicts(prevArrang, arrangement)) continue\n max = Math.max(max, count + numStudents)\n }\n dp[row + 1].set(arrangement, max)\n for (let i = 1; i < lastPos; i <<= 1) {\n if (canSit(classroom[row], arrangement, i)) next.push(arrangement | i)\n }\n }\n queue = next\n numStudents++\n }\n }\n return Math.max(...dp[seats.length].values())\n}\nfunction conflicts(prev, curr) {\n return prev & (curr << 1) || prev & (curr >> 1)\n}\nfunction canSit(row, arrangement, newStudent) {\n return (\n row & newStudent &&\n !(arrangement & newStudent) &&\n !(arrangement & (newStudent << 1)) &&\n !(arrangement & (newStudent >> 1))\n )\n}\n\n// another\n\n/**\n * @param {character[][]} seats\n * @return {number}\n */\nconst maxStudents = function (seats) {\n const m = seats.length\n const n = seats[0].length\n const validity = []\n for (let i = 0; i < m; i++) {\n let cur = 0\n for (let j = 0; j < n; j++) {\n cur = (cur << 1) + (seats[i][j] === '.' ? 1 : 0)\n }\n validity.push(cur)\n }\n const f = Array.from({ length: m + 1 }, () => Array(1 << n).fill(-1))\n f[0][0] = 0\n for (let i = 1; i <= m; i++) {\n const valid = validity[i - 1]\n for (let j = 0; j < 1 << n; j++) {\n if ((j & valid) === j && !(j & (j >> 1))) {\n for (let k = 0; k < 1 << n; k++) {\n if (!(j & (k >> 1)) && !((j >> 1) & k) && f[i - 1][k] !== -1) {\n f[i][j] = Math.max(f[i][j], f[i - 1][k] + bitCount(j))\n }\n }\n }\n }\n }\n return Math.max(...f[m])\n}\nfunction bitCount(n) {\n const res = n.toString(2).match(/1/g)\n return res === null ? 0 : res.length\n}\n\n" + }, + { + "_id": "66f925ddfdfb8e1665720d52", + "questionid": 647, + "title": "Maximum Product of the Length of Two Palindromic Substrings", + "slug": "maximum-product-of-the-length-of-two-palindromic-substrings", + "description": "You are given a 0-indexed string s and are tasked with finding two non-intersecting palindromic substrings of odd length such that the product of their lengths is maximized. More formally, you want to choose four integers i, j, k, l such that 0 <= i <= j < k <= l < s.length and both the substrings s[i...j] and s[k...l] are palindromes and have odd lengths. s[i...j] denotes a substring from index i to index j inclusive. Return the maximum possible product of the lengths of the two non-intersecting palindromic substrings. A palindrome is a string that is the same forward and backward. A substring is a contiguous sequence of characters in a string. ", + "category": [ + "String", + "Rolling Hash", + "Hash Function" + ], + "complexity": "Hard", + "successrate": 29, + "totalsubmissions": 6832, + "totalaccepted": 1979, + "likes": 121, + "dislikes": 25, + "hints": "You can use Manacher's algorithm to get the maximum palindromic substring centered at each index After using Manacher's for each center use a line sweep from the center to the left and from the center to the right to find for each index the farthest center to it with distance \u2030\u00a4 palin[center] After that, find the maximum palindrome size for each prefix in the string and for each suffix and the answer would be max(prefix[i] * suffix[i + 1])", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "ababbb"", + "expected_output": "9", + "explanation": "Substrings "aba" and "bbb" are palindromes with odd length. product = 3 * 3 = 9." + }, + { + "example_num": 2, + "expected_input": "s = "zaaaxbbby"", + "expected_output": "9", + "explanation": "Substrings "aaa" and "bbb" are palindromes with odd length. product = 3 * 3 = 9." + } + ], + "solution": "/**\n * @param {string} s\n * @return {number}\n */\nconst maxProduct = function (s) {\n const t1 = helper(s),\n t2 = helper(reverse(s))\n let res = 0\n for (let n = s.length, i = 0, j = n - 2; i < n - 1; ++i, --j)\n res = Math.max(res, t1[i] * t2[j])\n\n return res\n}\nfunction reverse(s) {\n return [...s].reverse().join('')\n}\nfunction helper(s) {\n const man = manachers(s).filter(\n (e, i, ar) => i >= 2 && i < ar.length - 2 && i % 2 === 0\n )\n const n = s.length,\n { max } = Math\n const ints = man.map((e, i) => [i - ~~(e / 2), i + ~~(e / 2)])\n const arr = Array(n).fill(0)\n for (const [a, b] of ints) {\n arr[b] = max(arr[b], b - a + 1)\n }\n for (let i = n - 2; i >= 0; i--) {\n arr[i] = max(arr[i], arr[i + 1] - 2)\n }\n let tmp = 0\n for (let i = 0; i < n; i++) {\n if (arr[i] > tmp) {\n tmp = arr[i]\n } else arr[i] = tmp\n }\n return arr\n}\nfunction manachers(s) {\n const str = `@#${s.split('').join('#')}#$`\n const arr = Array(str.length).fill(0)\n\n let center = 0,\n right = 0\n for (let i = 1, n = str.length; i < n - 1; i++) {\n if (i < right) {\n arr[i] = Math.min(right - i, arr[2 * center - i])\n }\n while (str[i + arr[i] + 1] === str[i - arr[i] - 1]) {\n arr[i] += 1\n }\n if (i + arr[i] > right) {\n center = i\n right = i + arr[i]\n }\n }\n\n return arr\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720d59", + "questionid": 654, + "title": "Minimum Number of Moves to Make Palindrome", + "slug": "minimum-number-of-moves-to-make-palindrome", + "description": "You are given a string s consisting only of lowercase English letters. In one move, you can select any two adjacent characters of s and swap them. Return the minimum number of moves needed to make s a palindrome. Note that the input will be generated such that s can always be converted to a palindrome. ", + "category": [ + "Two Pointers", + "String", + "Greedy", + "Binary Indexed Tree" + ], + "complexity": "Hard", + "successrate": 41.7, + "totalsubmissions": 11174, + "totalaccepted": 4659, + "likes": 194, + "dislikes": 50, + "hints": "Consider a greedy strategy. Let\u20ac\u2122s start by making the leftmost and rightmost characters match with some number of swaps. If we figure out how to do that using the minimum number of swaps, then we can delete the leftmost and rightmost characters and solve the problem recursively.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "aabb"", + "expected_output": "2", + "explanation": "We can obtain two palindromes from s, "abba" and "baab". \n- We can obtain "abba" from s in 2 moves: "aabb" -> "abab" -> "abba".\n- We can obtain "baab" from s in 2 moves: "aabb" -> "abab" -> "baab".\nThus, the minimum number of moves needed to make s a palindrome is 2." + }, + { + "example_num": 2, + "expected_input": "s = "letelt"", + "expected_output": "2", + "explanation": "One of the palindromes we can obtain from s in 2 moves is "lettel".\nOne of the ways we can obtain it is "letelt" -> "letetl" -> "lettel".\nOther palindromes such as "tleelt" can also be obtained in 2 moves.\nIt can be shown that it is not possible to obtain a palindrome in less than 2 moves." + } + ], + "solution": "/**\n * @param {string} s\n * @return {number}\n */\nconst minMovesToMakePalindrome = function(s) {\n let res = 0\n const arr = s.split('')\n \n while(arr.length) {\n const idx = arr.indexOf(arr[arr.length - 1])\n if(idx === arr.length - 1) {\n res += ~~(idx / 2)\n } else {\n res += idx\n arr.splice(idx, 1)\n }\n arr.pop()\n }\n\n return res\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720d62", + "questionid": 663, + "title": "Maximum Score Words Formed by Letters", + "slug": "maximum-score-words-formed-by-letters", + "description": "Given a list of words, list of\u00a0 single\u00a0letters (might be repeating)\u00a0and score\u00a0of every character. Return the maximum score of any valid set of words formed by using the given letters (words[i] cannot be used two\u00a0or more times). It is not necessary to use all characters in letters and each letter can only be used once. Score of letters\u00a0'a', 'b', 'c', ... ,'z' is given by\u00a0score[0], score[1], ... , score[25] respectively. ", + "category": [ + "Array", + "String", + "Dynamic Programming", + "Backtracking", + "Bit Manipulation", + "Bitmask" + ], + "complexity": "Hard", + "successrate": 72.1, + "totalsubmissions": 29091, + "totalaccepted": 20969, + "likes": 634, + "dislikes": 39, + "hints": "Note that words.length is small. This means you can iterate over every subset of words (2^N).", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "words = ["dog","cat","dad","good"], letters = ["a","a","c","d","d","d","g","o","o"], score = [1,0,9,5,0,0,3,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0]", + "expected_output": "23", + "explanation": "Score a=1, c=9, d=5, g=3, o=2\nGiven letters, we can form the words "dad" (5+1+5) and "good" (3+2+2+5) with a score of 23.\nWords "dad" and "dog" only get a score of 21." + }, + { + "example_num": 2, + "expected_input": "words = ["xxxz","ax","bx","cx"], letters = ["z","a","b","c","x","x","x"], score = [4,4,4,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,5,0,10]", + "expected_output": "27", + "explanation": "Score a=4, b=4, c=4, x=5, z=10\nGiven letters, we can form the words "ax" (4+5), "bx" (4+5) and "cx" (4+5) with a score of 27.\nWord "xxxz" only get a score of 25." + }, + { + "example_num": 3, + "expected_input": "words = ["leetcode"], letters = ["l","e","t","c","o","d"], score = [0,0,1,1,1,0,0,0,0,0,0,1,0,0,1,0,0,0,0,1,0,0,0,0,0,0]", + "expected_output": "0", + "explanation": "Letter "e" can only be used once." + } + ], + "solution": "/**\n * @param {string[]} words\n * @param {character[]} letters\n * @param {number[]} score\n * @return {number}\n */\nconst maxScoreWords = function (words, letters, score) {\n const points = new Map()\n const count = Array(26).fill(0)\n for (let w of letters) {\n count[w.charCodeAt(0) - 97] = ~~count[w.charCodeAt(0) - 97] + 1\n }\n return dfs(count, 0)\n function dfs(count, index) {\n if (index >= words.length) {\n return 0\n }\n const x = dfs(count, index + 1)\n const copy = [...count]\n let point = 0\n let isValid = true\n for (let w of words[index]) {\n let k = w.charCodeAt(0) - 97\n copy[k]--\n point += score[k]\n if (copy[k] < 0) isValid = false\n }\n return Math.max(x, isValid ? point + dfs(copy, index + 1) : 0)\n }\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720d64", + "questionid": 665, + "title": "Maximum Value of K Coins From Piles", + "slug": "maximum-value-of-k-coins-from-piles", + "description": "There are n piles of coins on a table. Each pile consists of a positive number of coins of assorted denominations. In one move, you can choose any coin on top of any pile, remove it, and add it to your wallet. Given a list piles, where piles[i] is a list of integers denoting the composition of the ith pile from top to bottom, and a positive integer k, return the maximum total value of coins you can have in your wallet if you choose exactly k coins optimally. ", + "category": [ + "Array", + "Dynamic Programming", + "Prefix Sum" + ], + "complexity": "Hard", + "successrate": 48.8, + "totalsubmissions": 15910, + "totalaccepted": 7765, + "likes": 393, + "dislikes": 6, + "hints": "For each pile i, what will be the total value of coins we can collect if we choose the first j coins? How can we use dynamic programming to combine the results from different piles to find the most optimal answer?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "piles = [[1,100,3],[7,8,9]], k = 2", + "expected_output": "101", + "explanation": "The above diagram shows the different ways we can choose k coins.\nThe maximum total we can obtain is 101." + }, + { + "example_num": 2, + "expected_input": "piles = [[100],[100],[100],[100],[100],[100],[1,1,1,1,1,1,700]], k = 7", + "expected_output": "706\nExplanation:\nThe maximum total can be obtained if we choose all coins from the last pile.", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[][]} piles\n * @param {number} k\n * @return {number}\n */\nvar maxValueOfCoins = function(piles, k) {\n let dp = Array(k + 1).fill(0);\n for (let i = 0; i < piles.length; i++) {\n const next = Array(k + 1).fill(0);\n for (let l = 1; l <= k; l++) {\n let sum = 0;\n next[l] = dp[l];\n for (let j = 0; j < Math.min(piles[i].length, l); j++) {\n sum += piles[i][j];\n next[l] = Math.max(next[l], dp[l - j - 1] + sum);\n }\n }\n dp = next;\n }\n return dp[k]; \n};\n\n// another\n\n/**\n * @param {number[][]} piles\n * @param {number} k\n * @return {number}\n */\nconst maxValueOfCoins = function(piles, k) {\n const n = piles.length\n const memo = Array.from({ length: n + 1 }, () => Array(k + 1).fill(null))\n return helper(0, k)\n\n // TC: O(k * m)\n // k: k\n // n: length of piles\n // m: sum(piles[i]), total elements of all piles\n function helper(i, k) {\n if(k == 0 || i === n) return 0\n if(memo[i][k] != null) return memo[i][k]\n let res = helper(i + 1, k)\n let cur = 0\n\n for(let j = 0; j < Math.min(piles[i].length, k); j++) {\n cur += piles[i][j]\n res = Math.max(res, cur + helper(i + 1, k - j - 1))\n }\n return memo[i][k] = res\n }\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720d6a", + "questionid": 671, + "title": "Minimum Number of Flips to Convert Binary Matrix to Zero Matrix", + "slug": "minimum-number-of-flips-to-convert-binary-matrix-to-zero-matrix", + "description": "Given a m x n binary matrix mat. In one step, you can choose one cell and flip it and all the four neighbors of it if they exist (Flip is changing 1 to 0 and 0 to 1). A pair of cells are called neighbors if they share one edge. Return the minimum number of steps required to convert mat to a zero matrix or -1 if you cannot. A binary matrix is a matrix with all cells equal to 0 or 1 only. A zero matrix is a matrix with all cells equal to 0. ", + "category": [ + "Array", + "Bit Manipulation", + "Breadth-First Search", + "Matrix" + ], + "complexity": "Hard", + "successrate": 72, + "totalsubmissions": 29496, + "totalaccepted": 21243, + "likes": 573, + "dislikes": 64, + "hints": "Flipping same index two times is like not flipping it at all. Each index can be flipped one time. Try all possible combinations. O(2^(n*m)).", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "mat = [[0,0],[0,1]]", + "expected_output": "3", + "explanation": "One possible solution is to flip (1, 0) then (0, 1) and finally (1, 1) as shown." + }, + { + "example_num": 2, + "expected_input": "mat = [[0]]", + "expected_output": "0", + "explanation": "Given matrix is a zero matrix. We do not need to change it." + }, + { + "example_num": 3, + "expected_input": "mat = [[1,0,0],[1,0,0]]", + "expected_output": "-1", + "explanation": "Given matrix cannot be a zero matrix." + } + ], + "solution": "/**\n * @param {number[][]} mat\n * @return {number}\n */\nconst minFlips = function (mat) {\n let start = 0\n const m = mat.length, n = mat[0].length\n for (let i = 0; i < m; i++) {\n for (let j = 0; j < n; j++) {\n start |= mat[i][j] << (i * n + j)\n }\n }\n let q = [start]\n const seen = new Set(), dirs = [[-1, 0], [1, 0], [0, -1], [0, 1], [0, 0]]\n\n for(let i = 0; q.length; i++) {\n const tmp = []\n for (let size = q.length; size > 0; size--) {\n const cur = q.pop()\n if(cur === 0) return i\n for(let i = 0; i < m; i++) {\n for(let j = 0; j < n; j++) {\n let next = cur\n for(const [dx, dy] of dirs) {\n const r = i + dx, c = j + dy\n if(r >= 0 && r < m && c >= 0 && c < n) {\n next ^= (1 << (r * n + c))\n }\n }\n if (!seen.has(next)) {\n seen.add(next)\n tmp.push(next)\n }\n }\n }\n }\n q = tmp\n }\n\n return -1\n}\n\n// another\n\n/**\n * @param {number[][]} mat\n * @return {number}\n */\nconst minFlips = function (mat) {\n const X = mat.length\n const Y = mat[0].length\n const binary = {\n 0: 1,\n 1: 2,\n 2: 4,\n 3: 8,\n 4: 16,\n 5: 32,\n 6: 64,\n 7: 128,\n 8: 256,\n }\n const mask = []\n let state = 0\n for (let i = 0; i < X; ++i) {\n for (let j = 0; j < Y; ++j) {\n let bit = 0\n state += mat[i][j] * binary[Y * i + j]\n bit += binary[Y * i + j]\n if (i > 0) {\n bit += binary[Y * (i - 1) + j]\n }\n if (i < X - 1) {\n bit += binary[Y * (i + 1) + j]\n }\n if (j > 0) {\n bit += binary[Y * i + (j - 1)]\n }\n if (j < Y - 1) {\n bit += binary[Y * i + (j + 1)]\n }\n mask.push(bit)\n }\n }\n if (state === 0) return 0\n const set = new Set()\n const q = [{ state: state, moves: 0 }]\n while (q.length !== 0) {\n const cur = q.shift()\n if (cur.state === 0) {\n return cur.moves\n }\n for (let i = 0; i < X * Y; ++i) {\n let newState = cur.state\n newState ^= mask[i]\n if (!set.has(newState)) {\n set.add(newState)\n q.push({ state: newState, moves: cur.moves + 1 })\n }\n }\n }\n return -1\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720d7a", + "questionid": 687, + "title": "Number of Steps to Reduce a Number to Zero", + "slug": "number-of-steps-to-reduce-a-number-to-zero", + "description": "Given an integer num, return the number of steps to reduce it to zero. In one step, if the current number is even, you have to divide it by 2, otherwise, you have to subtract 1 from it. ", + "category": [ + "Math", + "Bit Manipulation" + ], + "complexity": "Easy", + "successrate": 85.6, + "totalsubmissions": 294100, + "totalaccepted": 251848, + "likes": 1590, + "dislikes": 106, + "hints": "Simulate the process to get the final answer.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "num = 14", + "expected_output": "6", + "explanation": " \nStep 1) 14 is even; divide by 2 and obtain 7. \nStep 2) 7 is odd; subtract 1 and obtain 6.\nStep 3) 6 is even; divide by 2 and obtain 3. \nStep 4) 3 is odd; subtract 1 and obtain 2. \nStep 5) 2 is even; divide by 2 and obtain 1. \nStep 6) 1 is odd; subtract 1 and obtain 0." + }, + { + "example_num": 2, + "expected_input": "num = 8", + "expected_output": "4", + "explanation": " \nStep 1) 8 is even; divide by 2 and obtain 4. \nStep 2) 4 is even; divide by 2 and obtain 2. \nStep 3) 2 is even; divide by 2 and obtain 1. \nStep 4) 1 is odd; subtract 1 and obtain 0." + }, + { + "example_num": 3, + "expected_input": "num = 123", + "expected_output": "12", + "explanation": "" + } + ], + "solution": "/**\n * @param {number} num\n * @return {number}\n */\nconst numberOfSteps = function(num) {\n let res = 0\n while(num !== 0) {\n if(num % 2 === 0) {\n num /= 2\n } else num--\n res++\n }\n \n return res\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720d7d", + "questionid": 690, + "title": "Maximum 69 Number", + "slug": "maximum-69-number", + "description": "You are given a positive integer num consisting only of digits 6 and 9. Return the maximum number you can get by changing at most one digit (6 becomes 9, and 9 becomes 6). ", + "category": [ + "Math", + "Greedy" + ], + "complexity": "Easy", + "successrate": 78.9, + "totalsubmissions": 137155, + "totalaccepted": 108154, + "likes": 967, + "dislikes": 117, + "hints": "Convert the number in an array of its digits. Brute force on every digit to get the maximum number.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "num = 9669", + "expected_output": "9969", + "explanation": "Changing the first digit results in 6669.\nChanging the second digit results in 9969.\nChanging the third digit results in 9699.\nChanging the fourth digit results in 9666.\nThe maximum number is 9969." + }, + { + "example_num": 2, + "expected_input": "num = 9996", + "expected_output": "9999", + "explanation": "Changing the last digit 6 to 9 results in the maximum number." + }, + { + "example_num": 3, + "expected_input": "num = 9999", + "expected_output": "9999", + "explanation": "It is better not to apply any change." + } + ], + "solution": "/**\n * @param {number} num\n * @return {number}\n */\nvar maximum69Number = function(num) {\n const arr = (num+'').split('')\n for(let i = 0; i < arr.length; i++) {\n if(arr[i] === '6') {\n arr[i] = '9'\n break\n }\n }\n return arr.join('')\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720d7f", + "questionid": 692, + "title": "Delete Leaves With a Given Value", + "slug": "delete-leaves-with-a-given-value", + "description": "Given a binary tree root and an integer target, delete all the leaf nodes with value target. Note that once you delete a leaf node with value target, if its parent node becomes a leaf node and has the value target, it should also be deleted (you need to continue doing that until you cannot). ", + "category": [ + "Tree", + "Depth-First Search", + "Binary Tree" + ], + "complexity": "Medium", + "successrate": 74.8, + "totalsubmissions": 87692, + "totalaccepted": 65562, + "likes": 1387, + "dislikes": 26, + "hints": "Use the DFS to reconstruct the tree such that no leaf node is equal to the target. If the leaf node is equal to the target, return an empty object instead.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [1,2,3,2,null,2,4], target = 2", + "expected_output": "[1,null,3,null,4]", + "explanation": "Leaf nodes in green with value (target = 2) are removed (Picture in left). \nAfter removing, new nodes become leaf nodes with value (target = 2) (Picture in center)." + }, + { + "example_num": 2, + "expected_input": "root = [1,3,3,3,2], target = 3", + "expected_output": "[1,3,null,null,2]", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "root = [1,2,null,2,null,2], target = 2", + "expected_output": "[1]", + "explanation": "Leaf nodes in green with value (target = 2) are removed at each step." + } + ], + "solution": "/**\n * Definition for a binary tree node.\n * function TreeNode(val, left, right) {\n * this.val = (val===undefined ? 0 : val)\n * this.left = (left===undefined ? null : left)\n * this.right = (right===undefined ? null : right)\n * }\n */\n/**\n * @param {TreeNode} root\n * @param {number} target\n * @return {TreeNode}\n */\nconst removeLeafNodes = function(root, target) {\n return dfs(root, target)\n};\n\nfunction dfs(node, target) {\n if(node == null) return node\n if(node.left == null && node.right == null) {\n if(node.val === target) return null\n else return node\n }\n node.right = dfs(node.right, target)\n node.left = dfs(node.left, target)\n if(node.right == null && node.left == null) return dfs(node, target)\n return node\n}\n\n// another\n\n/**\n * Definition for a binary tree node.\n * function TreeNode(val, left, right) {\n * this.val = (val===undefined ? 0 : val)\n * this.left = (left===undefined ? null : left)\n * this.right = (right===undefined ? null : right)\n * }\n */\n/**\n * @param {TreeNode} root\n * @param {number} target\n * @return {TreeNode}\n */\nconst removeLeafNodes = function(root, target) {\n if(root.left) root.left = removeLeafNodes(root.left, target)\n if(root.right) root.right = removeLeafNodes(root.right, target)\n return root.left == root.right && root.val === target ? null : root\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720d80", + "questionid": 693, + "title": "Minimum Number of Taps to Open to Water a Garden", + "slug": "minimum-number-of-taps-to-open-to-water-a-garden", + "description": "There is a one-dimensional garden on the x-axis. The garden starts at the point 0 and ends at the point n. (i.e The length of the garden is n). There are n + 1 taps located at points [0, 1, ..., n] in the garden. Given an integer n and an integer array ranges of length n + 1 where ranges[i] (0-indexed) means the i-th tap can water the area [i - ranges[i], i + ranges[i]] if it was open. Return the minimum number of taps that should be open to water the whole garden, If the garden cannot be watered return -1. ", + "category": [ + "Array", + "Dynamic Programming", + "Greedy" + ], + "complexity": "Hard", + "successrate": 48.1, + "totalsubmissions": 113168, + "totalaccepted": 54380, + "likes": 1441, + "dislikes": 106, + "hints": "Create intervals of the area covered by each tap, sort intervals by the left end. We need to cover the interval [0, n]. we can start with the first interval and out of all intervals that intersect with it we choose the one that covers the farthest point to the right. What if there is a gap between intervals that is not covered ? we should stop and return -1 as there is some interval that cannot be covered.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 5, ranges = [3,4,1,1,0,0]", + "expected_output": "1", + "explanation": "The tap at point 0 can cover the interval [-3,3]\nThe tap at point 1 can cover the interval [-3,5]\nThe tap at point 2 can cover the interval [1,3]\nThe tap at point 3 can cover the interval [2,4]\nThe tap at point 4 can cover the interval [4,4]\nThe tap at point 5 can cover the interval [5,5]\nOpening Only the second tap will water the whole garden [0,5]" + }, + { + "example_num": 2, + "expected_input": "n = 3, ranges = [0,0,0,0]", + "expected_output": "-1", + "explanation": "Even if you activate all the four taps you cannot water the whole garden." + } + ], + "solution": "/**\n * @param {number} n\n * @param {number[]} ranges\n * @return {number}\n */\nconst minTaps = function(n, ranges) {\n const len = ranges.length, {min, max} = Math\n const arr = []\n for(let i = 0; i < len; i++) {\n arr.push([max(0, i - ranges[i]), i + ranges[i]])\n }\n // arr.sort((a, b) => a[1] === b[1] ? a[0] - b[0]: a[1] - b[1])\n arr.sort((a, b) => a[0] === b[0] ? b[1] - a[1] : a[0] - b[0])\n let res = 0, end = 0, nextEnd = 0, idx = 0\n while(idx < len) {\n nextEnd = end\n while(idx < len && arr[idx][0] <= end) {\n nextEnd = max(nextEnd, arr[idx][1])\n idx++\n }\n res++\n if(nextEnd >= n) return res\n else if(nextEnd === end) return -1\n end = nextEnd\n }\n\n\n return -1\n};\n\n// another\n\n/**\n * @param {number} n\n * @param {number[]} ranges\n * @return {number}\n */\nconst minTaps = function (n, ranges) {\n const starts = new Array(n + 1).fill(0)\n for (let i = 0; i <= n; i++) {\n const start = Math.max(0, i - ranges[i])\n starts[start] = Math.max(starts[start], i + ranges[i])\n }\n let count = 0\n let max = 0\n let i = 0\n while (max < n) {\n const end = max\n for (let j = i; j <= end; j++) {\n max = Math.max(max, starts[j])\n }\n if (i === max) return -1\n i = end\n count++\n }\n return count\n}\n\n// another\n\n/**\n * @param {number} n\n * @param {number[]} ranges\n * @return {number}\n */\nconst minTaps = function (n, ranges) {\n const dp = new Array(n + 1).fill(n + 2)\n dp[0] = 0\n for (let i = 0; i <= n; ++i)\n for (let j = Math.max(i - ranges[i] + 1, 0); j <= Math.min(i + ranges[i], n); ++j)\n dp[j] = Math.min(dp[j], dp[Math.max(0, i - ranges[i])] + 1)\n return dp[n] < n + 2 ? dp[n] : -1\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720d87", + "questionid": 700, + "title": "Count All Valid Pickup and Delivery Options", + "slug": "count-all-valid-pickup-and-delivery-options", + "description": "Given n orders, each order consist in pickup and delivery services. Count all valid pickup/delivery possible sequences such that delivery(i) is always after of\u00a0pickup(i). Since the answer\u00a0may be too large,\u00a0return it modulo\u00a010^9 + 7. ", + "category": [ + "Math", + "Dynamic Programming", + "Combinatorics" + ], + "complexity": "Hard", + "successrate": 63.4, + "totalsubmissions": 80796, + "totalaccepted": 51194, + "likes": 1518, + "dislikes": 137, + "hints": "Use the permutation and combination theory to add one (P, D) pair each time until n pairs.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 1", + "expected_output": "1", + "explanation": "Unique order (P1, D1), Delivery 1 always is after of Pickup 1." + }, + { + "example_num": 2, + "expected_input": "n = 2", + "expected_output": "6", + "explanation": "All possible orders: \n(P1,P2,D1,D2), (P1,P2,D2,D1), (P1,D1,P2,D2), (P2,P1,D1,D2), (P2,P1,D2,D1) and (P2,D2,P1,D1).\nThis is an invalid order (P1,D2,P2,D1) because Pickup 2 is after of Delivery 2." + }, + { + "example_num": 3, + "expected_input": "n = 3", + "expected_output": "90", + "explanation": "" + } + ], + "solution": "/**\n * @param {number} n\n * @return {number}\n */\nconst countOrders = function(n) {\n let res = 1\n const MOD = 10 ** 9 + 7\n for(let i = 1; i <= n; i++) {\n res = res * (i * 2 - 1) * i % MOD;\n }\n return res\n};\n\n// another\n\n/**\n * @param {number} n\n * @return {number}\n */\nconst countOrders = function(n) {\n let res = 1\n const MOD = 10 ** 9 + 7\n for(let i = 1; i <= n; i++) res = res * i % MOD\n for(let i = 1; i < 2 * n; i += 2) res = res * i % MOD\n return res\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720d4c", + "questionid": 641, + "title": "Get Equal Substrings Within Budget", + "slug": "get-equal-substrings-within-budget", + "description": "You are given two strings s and t of the same length and an integer maxCost. You want to change s to t. Changing the ith character of s to ith character of t costs |s[i] - t[i]| (i.e., the absolute difference between the ASCII values of the characters). Return the maximum length of a substring of s that can be changed to be the same as the corresponding substring of t with a cost less than or equal to maxCost. If there is no substring from s that can be changed to its corresponding substring from t, return 0. ", + "category": [ + "String", + "Binary Search", + "Sliding Window", + "Prefix Sum" + ], + "complexity": "Medium", + "successrate": 46.5, + "totalsubmissions": 61338, + "totalaccepted": 28510, + "likes": 632, + "dislikes": 43, + "hints": "Calculate the differences between a[i] and b[i]. Use a sliding window to track the longest valid substring.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "abcd", t = "bcdf", maxCost = 3", + "expected_output": "3", + "explanation": ""abc" of s can change to "bcd".\nThat costs 3, so the maximum length is 3." + }, + { + "example_num": 2, + "expected_input": "s = "abcd", t = "cdef", maxCost = 3", + "expected_output": "1", + "explanation": "Each character in s costs 2 to change to character in t, so the maximum length is 1." + }, + { + "example_num": 3, + "expected_input": "s = "abcd", t = "acde", maxCost = 0", + "expected_output": "1", + "explanation": "You cannot make any change, so the maximum length is 1." + } + ], + "solution": null + }, + { + "_id": "66f925ddfdfb8e1665720d4d", + "questionid": 642, + "title": "Where Will the Ball Fall", + "slug": "where-will-the-ball-fall", + "description": "You have a 2-D grid of size m x n representing a box, and you have n balls. The box is open on the top and bottom sides. Each cell in the box has a diagonal board spanning two corners of the cell that can redirect a ball to the right or to the left. We drop one ball at the top of each column of the box. Each ball can get stuck in the box or fall out of the bottom. A ball gets stuck if it hits a \"V\" shaped pattern between two boards or if a board redirects the ball into either wall of the box. Return an array answer of size n where answer[i] is the column that the ball falls out of at the bottom after dropping the ball from the ith column at the top, or -1 if the ball gets stuck in the box. ", + "category": [ + "Array", + "Dynamic Programming", + "Depth-First Search", + "Matrix", + "Simulation" + ], + "complexity": "Medium", + "successrate": 66.5, + "totalsubmissions": 40091, + "totalaccepted": 26652, + "likes": 744, + "dislikes": 54, + "hints": "Use DFS. Traverse the path of the ball downwards until you reach the bottom or get stuck.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "grid = [[1,1,1,-1,-1],[1,1,1,-1,-1],[-1,-1,-1,1,1],[1,1,1,1,-1],[-1,-1,-1,-1,-1]]", + "expected_output": "[1,-1,-1,-1,-1]", + "explanation": "This example is shown in the photo.\nBall b0 is dropped at column 0 and falls out of the box at column 1.\nBall b1 is dropped at column 1 and will get stuck in the box between column 2 and 3 and row 1.\nBall b2 is dropped at column 2 and will get stuck on the box between column 2 and 3 and row 0.\nBall b3 is dropped at column 3 and will get stuck on the box between column 2 and 3 and row 0.\nBall b4 is dropped at column 4 and will get stuck on the box between column 2 and 3 and row 1." + }, + { + "example_num": 2, + "expected_input": "grid = [[-1]]", + "expected_output": "[-1]", + "explanation": "The ball gets stuck against the left wall." + }, + { + "example_num": 3, + "expected_input": "grid = [[1,1,1,1,1,1],[-1,-1,-1,-1,-1,-1],[1,1,1,1,1,1],[-1,-1,-1,-1,-1,-1]]", + "expected_output": "[0,1,2,3,4,-1]", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[][]} grid\n * @return {number[]}\n */\nconst findBall = function (grid) {\n const res = new Array(grid[0].length).fill(0)\n for (let i = 0; i < res.length; i++) {\n let start = i\n let state = 1\n for (let j = 0; j < grid.length; j++) {\n if (grid[j][start] === 1) {\n if (start >= grid[0].length - 1 || grid[j][start + 1] === -1) {\n state = -1\n break\n }\n start++\n } else {\n if (start <= 0 || grid[j][start - 1] == 1) {\n state = -1\n break\n }\n start--\n }\n }\n res[i] = state === -1 ? state : start\n }\n return res\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720d4e", + "questionid": 643, + "title": "Path with Maximum Probability", + "slug": "path-with-maximum-probability", + "description": "You are given an undirected weighted graph of\u00a0n\u00a0nodes (0-indexed), represented by an edge list where\u00a0edges[i] = [a, b]\u00a0is an undirected edge connecting the nodes\u00a0a\u00a0and\u00a0b\u00a0with a probability of success of traversing that edge\u00a0succProb[i]. Given two nodes\u00a0start\u00a0and\u00a0end, find the path with the maximum probability of success to go from\u00a0start\u00a0to\u00a0end\u00a0and return its success probability. If there is no path from\u00a0start\u00a0to\u00a0end, return\u00a00. Your answer will be accepted if it differs from the correct answer by at most 1e-5. ", + "category": [ + "Graph", + "Heap (Priority Queue)", + "Shortest Path" + ], + "complexity": "Medium", + "successrate": 46.4, + "totalsubmissions": 89945, + "totalaccepted": 41690, + "likes": 1141, + "dislikes": 25, + "hints": "Multiplying probabilities will result in precision errors. Take log probabilities to sum up numbers instead of multiplying them. Use Dijkstra's algorithm to find the minimum path between the two nodes after negating all costs.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.2], start = 0, end = 2", + "expected_output": "0.25000", + "explanation": " There are two paths from start to end, one having a probability of success = 0.2 and the other has 0.5 * 0.5 = 0.25." + }, + { + "example_num": 2, + "expected_input": "n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.3], start = 0, end = 2", + "expected_output": "0.30000", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "n = 3, edges = [[0,1]], succProb = [0.5], start = 0, end = 2", + "expected_output": "0.00000", + "explanation": " There is no path between 0 and 2." + } + ], + "solution": "/**\n * @param {number} n\n * @param {number[][]} edges\n * @param {number[]} succProb\n * @param {number} start\n * @param {number} end\n * @return {number}\n */\nvar maxProbability = function (n, edges, succProb, start, end) {\n const g = {}\n for (let i = 0; i < edges.length; ++i) {\n const a = edges[i][0],\n b = edges[i][1]\n if (g[a] == null) g[a] = []\n if (g[b] == null) g[b] = []\n g[a].push([b, i])\n g[b].push([a, i])\n }\n const p = new Array(n).fill(-1)\n p[start] = 1\n const pq = new PQ((a, b) => p[a] > p[b])\n pq.push(start)\n while (!pq.isEmpty()) {\n const cur = pq.pop()\n\n for (let a of g[cur] || []) {\n const neighbor = a[0],\n index = a[1]\n if (p[cur] * succProb[index] > p[neighbor]) {\n p[neighbor] = p[cur] * succProb[index]\n pq.push(neighbor)\n }\n }\n }\n return p[end] === -1 ? 0 : p[end]\n}\nclass PQ {\n constructor(comparator = (a, b) => a > b) {\n this.heap = []\n this.top = 0\n this.comparator = comparator\n }\n size() {\n return this.heap.length\n }\n isEmpty() {\n return this.size() === 0\n }\n peek() {\n return this.heap[this.top]\n }\n push(...values) {\n values.forEach((value) => {\n this.heap.push(value)\n this.siftUp()\n })\n return this.size()\n }\n pop() {\n const poppedValue = this.peek()\n const bottom = this.size() - 1\n if (bottom > this.top) {\n this.swap(this.top, bottom)\n }\n this.heap.pop()\n this.siftDown()\n return poppedValue\n }\n replace(value) {\n const replacedValue = this.peek()\n this.heap[this.top] = value\n this.siftDown()\n return replacedValue\n }\n\n parent = (i) => ((i + 1) >>> 1) - 1\n left = (i) => (i << 1) + 1\n right = (i) => (i + 1) << 1\n greater = (i, j) => this.comparator(this.heap[i], this.heap[j])\n swap = (i, j) => ([this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]])\n siftUp = () => {\n let node = this.size() - 1\n while (node > this.top && this.greater(node, this.parent(node))) {\n this.swap(node, this.parent(node))\n node = this.parent(node)\n }\n }\n siftDown = () => {\n let node = this.top\n while (\n (this.left(node) < this.size() && this.greater(this.left(node), node)) ||\n (this.right(node) < this.size() && this.greater(this.right(node), node))\n ) {\n let maxChild =\n this.right(node) < this.size() &&\n this.greater(this.right(node), this.left(node))\n ? this.right(node)\n : this.left(node)\n this.swap(node, maxChild)\n node = maxChild\n }\n }\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720d50", + "questionid": 645, + "title": "Longest Arithmetic Subsequence of Given Difference", + "slug": "longest-arithmetic-subsequence-of-given-difference", + "description": "Given an integer array arr and an integer difference, return the length of the longest subsequence in arr which is an arithmetic sequence such that the difference between adjacent elements in the subsequence equals difference. A subsequence is a sequence that can be derived from arr by deleting some or no elements without changing the order of the remaining elements. ", + "category": [ + "Array", + "Hash Table", + "Dynamic Programming" + ], + "complexity": "Medium", + "successrate": 51.3, + "totalsubmissions": 90972, + "totalaccepted": 46671, + "likes": 983, + "dislikes": 42, + "hints": "Use dynamic programming. Let dp[i] be the maximum length of a subsequence of the given difference whose last element is i. dp[i] = 1 + dp[i-k]", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "arr = [1,2,3,4], difference = 1", + "expected_output": "4\nExplanation: The longest arithmetic subsequence is [1,2,3,4].", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "arr = [1,3,5,7], difference = 1", + "expected_output": "1\nExplanation: The longest arithmetic subsequence is any single element.", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "arr = [1,5,7,8,5,3,4,2,1], difference = -2", + "expected_output": "4\nExplanation: The longest arithmetic subsequence is [7,5,3,1].", + "explanation": "" + } + ], + "solution": null + }, + { + "_id": "66f925ddfdfb8e1665720d51", + "questionid": 646, + "title": "Maximum Candies Allocated to K Children", + "slug": "maximum-candies-allocated-to-k-children", + "description": "You are given a 0-indexed integer array candies. Each element in the array denotes a pile of candies of size candies[i]. You can divide each pile into any number of sub piles, but you cannot merge two piles together. You are also given an integer k. You should allocate piles of candies to k children such that each child gets the same number of candies. Each child can take at most one pile of candies and some piles of candies may go unused. Return the maximum number of candies each child can get. ", + "category": [ + "Array", + "Binary Search" + ], + "complexity": "Medium", + "successrate": 34.6, + "totalsubmissions": 39951, + "totalaccepted": 13813, + "likes": 320, + "dislikes": 20, + "hints": "For a fixed number of candies c, how can you check if each child can get c candies? Use binary search to find the maximum c as the answer.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "candies = [5,8,6], k = 3", + "expected_output": "5", + "explanation": "We can divide candies[1] into 2 piles of size 5 and 3, and candies[2] into 2 piles of size 5 and 1. We now have five piles of candies of sizes 5, 5, 3, 5, and 1. We can allocate the 3 piles of size 5 to 3 children. It can be proven that each child cannot receive more than 5 candies." + }, + { + "example_num": 2, + "expected_input": "candies = [2,5], k = 11", + "expected_output": "0", + "explanation": "There are 11 children but only 7 candies in total, so it is impossible to ensure each child receives at least one candy. Thus, each child gets no candy and the answer is 0." + } + ], + "solution": "/**\n * @param {number[]} candies\n * @param {number} k\n * @return {number}\n */\nconst maximumCandies = function(candies, k) {\n let max = candies.reduce((ac, e) => ac + e, 0);\n let min = 0;\n while (min < max) {\n let mid = max - Math.floor((max - min) / 2);\n let cnt = 0;\n for (let cand of candies) {\n cnt += ~~(cand / mid);\n }\n if (cnt < k) {\n max = mid - 1;\n } else {\n min = mid;\n }\n }\n return min;\n};\n\n// another\n\n/**\n * @param {number[]} candies\n * @param {number} k\n * @return {number}\n */\nconst maximumCandies = function(candies, k) {\n let max = candies.reduce((ac, e) => ac + e, 0)\n let min = 0\n while(min < max) {\n const mid = max - Math.floor((max - min) /2)\n let num = 0\n for(let e of candies) num += ~~(e / mid)\n if(num < k) max = mid - 1\n else min = mid\n }\n return min\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720d54", + "questionid": 649, + "title": "Queens That Can Attack the King", + "slug": "queens-that-can-attack-the-king", + "description": "On an 8x8 chessboard, there can be multiple Black Queens and one White King. Given an array of integer coordinates queens that represents the positions of the Black Queens, and a pair of coordinates king that represent the position of the White King, return the coordinates of all the queens (in any order) that can attack the King. ", + "category": [ + "Array", + "Matrix", + "Simulation" + ], + "complexity": "Medium", + "successrate": 71.1, + "totalsubmissions": 44750, + "totalaccepted": 31819, + "likes": 674, + "dislikes": 124, + "hints": "Check 8 directions around the King. Find the nearest queen in each direction.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "queens = [[0,1],[1,0],[4,0],[0,4],[3,3],[2,4]], king = [0,0]", + "expected_output": "[[0,1],[1,0],[3,3]]", + "explanation": "The diagram above shows the three queens that can directly attack the king and the three queens that cannot attack the king (i.e., marked with red dashes)." + }, + { + "example_num": 2, + "expected_input": "queens = [[0,0],[1,1],[2,2],[3,4],[3,5],[4,4],[4,5]], king = [3,3]", + "expected_output": "[[2,2],[3,4],[4,4]]", + "explanation": "The diagram above shows the three queens that can directly attack the king and the three queens that cannot attack the king (i.e., marked with red dashes)." + } + ], + "solution": null + }, + { + "_id": "66f925ddfdfb8e1665720d57", + "questionid": 652, + "title": "Check If It Is a Straight Line", + "slug": "check-if-it-is-a-straight-line", + "description": "You are given an array\u00a0coordinates, coordinates[i] = [x, y], where [x, y] represents the coordinate of a point. Check if these points\u00a0make a straight line in the XY plane. ", + "category": [ + "Array", + "Math", + "Geometry" + ], + "complexity": "Easy", + "successrate": 41.9, + "totalsubmissions": 268240, + "totalaccepted": 112522, + "likes": 871, + "dislikes": 128, + "hints": "If there're only 2 points, return true. Check if all other points lie on the line defined by the first 2 points. Use cross product to check collinearity.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "coordinates = [[1,2],[2,3],[3,4],[4,5],[5,6],[6,7]]", + "expected_output": "true", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "coordinates = [[1,1],[2,2],[3,4],[4,5],[5,6],[7,7]]", + "expected_output": "false", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[][]} coordinates\n * @return {boolean}\n */\nconst checkStraightLine = function(coordinates) {\n const r = ratio(coordinates[0], coordinates[1])\n for(let i = 1, len = coordinates.length; i < len - 1; i++) {\n if(ratio(coordinates[i], coordinates[i + 1]) !== r) return false\n }\n \n return true\n};\n\nfunction ratio(a, b) {\n return (b[1] - a[1]) / (b[0] - a[0])\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720d5b", + "questionid": 656, + "title": "Tiling a Rectangle with the Fewest Squares", + "slug": "tiling-a-rectangle-with-the-fewest-squares", + "description": "Given a rectangle of size n x m, return the minimum number of integer-sided squares that tile the rectangle. ", + "category": [ + "Dynamic Programming", + "Backtracking" + ], + "complexity": "Hard", + "successrate": 53.7, + "totalsubmissions": 30316, + "totalaccepted": 16265, + "likes": 460, + "dislikes": 428, + "hints": "Can you use backtracking to solve this problem ?. Suppose you've placed a bunch of squares. Where is the natural spot to place the next square ?. The maximum number of squares to be placed will be \u2030\u00a4 max(n,m).", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 2, m = 3", + "expected_output": "3", + "explanation": "3 squares are necessary to cover the rectangle.\n2 (squares of 1x1)\n1 (square of 2x2)" + }, + { + "example_num": 2, + "expected_input": "n = 5, m = 8", + "expected_output": "5", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "n = 11, m = 13", + "expected_output": "6", + "explanation": "" + } + ], + "solution": "/**\n * @param {number} n\n * @param {number} m\n * @return {number}\n */\nconst tilingRectangle = function (n, m) {\n if ((n === 11 && m === 13) || (n === 13 && m === 11)) {\n return 6\n }\n\n const dp = Array(n + 1)\n .fill()\n .map((_) => Array(m + 1).fill(0))\n for (let i = 1; i <= n; i++) {\n for (let j = 1; j <= m; j++) {\n if (i === j) {\n dp[i][j] = 1\n continue\n }\n dp[i][j] = m * n\n for (let k = 1; k <= i / 2; k++) {\n dp[i][j] = Math.min(dp[i][j], dp[i - k][j] + dp[k][j])\n }\n for (let k = 1; k <= j / 2; k++) {\n dp[i][j] = Math.min(dp[i][j], dp[i][k] + dp[i][j - k])\n }\n }\n }\n return dp[n][m]\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720d5d", + "questionid": 658, + "title": "Maximum Height by Stacking Cuboids ", + "slug": "maximum-height-by-stacking-cuboids", + "description": "Given n cuboids where the dimensions of the ith cuboid is cuboids[i] = [widthi, lengthi, heighti] (0-indexed). Choose a subset of cuboids and place them on each other. You can place cuboid i on cuboid j if widthi <= widthj and lengthi <= lengthj and heighti <= heightj. You can rearrange any cuboid's dimensions by rotating it to put it on another cuboid. Return the maximum height of the stacked cuboids. ", + "category": [ + "Array", + "Dynamic Programming", + "Sorting" + ], + "complexity": "Hard", + "successrate": 53.6, + "totalsubmissions": 20099, + "totalaccepted": 10767, + "likes": 477, + "dislikes": 16, + "hints": "Does the dynamic programming sound like the right algorithm after sorting? Let's say box1 can be placed on top of box2. No matter what orientation box2 is in, we can rotate box1 so that it can be placed on top. Why don't we orient everything such that height is the biggest?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "cuboids = [[50,45,20],[95,37,53],[45,23,12]]", + "expected_output": "190", + "explanation": "Cuboid 1 is placed on the bottom with the 53x37 side facing down with height 95.\nCuboid 0 is placed next with the 45x20 side facing down with height 50.\nCuboid 2 is placed next with the 23x12 side facing down with height 45.\nThe total height is 95 + 50 + 45 = 190." + }, + { + "example_num": 2, + "expected_input": "cuboids = [[38,25,45],[76,35,3]]", + "expected_output": "76", + "explanation": "You can't place any of the cuboids on the other.\nWe choose cuboid 1 and rotate it so that the 35x3 side is facing down and its height is 76." + }, + { + "example_num": 3, + "expected_input": "cuboids = [[7,11,17],[7,17,11],[11,7,17],[11,17,7],[17,7,11],[17,11,7]]", + "expected_output": "102", + "explanation": "After rearranging the cuboids, you can see that all cuboids have the same dimension.\nYou can place the 11x7 side down on all cuboids so their heights are 17.\nThe maximum height of stacked cuboids is 6 * 17 = 102." + } + ], + "solution": "/**\n * @param {number[][]} cuboids\n * @return {number}\n */\nvar maxHeight = function (cuboids) {\n let n = cuboids.length\n for (let c of cuboids) {\n c.sort((a, b) => a - b)\n }\n const { max } = Math\n cuboids.sort(compare)\n const f = Array(n)\n let ans = 0\n for (let i = 0; i < n; i++) {\n f[i] = cuboids[i][2]\n for (let j = 0; j < i; j++) {\n if (\n cuboids[i][0] <= cuboids[j][0] &&\n cuboids[i][1] <= cuboids[j][1] &&\n cuboids[i][2] <= cuboids[j][2]\n )\n f[i] = max(f[i], f[j] + cuboids[i][2])\n }\n ans = max(ans, f[i])\n }\n return ans\n function compare(a, b) {\n if (a[0] != b[0]) return b[0] - a[0]\n if (a[1] != b[1]) return b[1] - a[1]\n return b[2] - a[2]\n }\n}\n\n// another\n\n/**\n * @param {number[][]} cuboids\n * @return {number}\n */\nvar maxHeight = function(cuboids) {\n cuboids.forEach((cuboid) => cuboid.sort((a, b) => a - b));\n cuboids.sort((a, b) => {\n if (a[0] !== b[0]) return b[0] - a[0];\n if (a[1] !== b[1]) return b[1] - a[1];\n return b[2] - a[2];\n });\n const n = cuboids.length;\n const dp = Array(n).fill(0);\n let res = 0;\n for (let j = 0; j < n; ++j) {\n dp[j] = cuboids[j][2];\n for (let i = 0; i < j; ++i) {\n if (cuboids[i][0] >= cuboids[j][0]\n && cuboids[i][1] >= cuboids[j][1]\n && cuboids[i][2] >= cuboids[j][2]\n ) {\n dp[j] = Math.max(dp[j], dp[i] + cuboids[j][2]);\n }\n }\n res = Math.max(res, dp[j]);\n }\n return res;\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720d65", + "questionid": 666, + "title": "Count Servers that Communicate", + "slug": "count-servers-that-communicate", + "description": "You are given a map of a server center, represented as a m * n integer matrix\u00a0grid, where 1 means that on that cell there is a server and 0 means that it is no server. Two servers are said to communicate if they are on the same row or on the same column.\n\nReturn the number of servers\u00a0that communicate with any other server. ", + "category": [ + "Array", + "Depth-First Search", + "Breadth-First Search", + "Union Find", + "Matrix", + "Counting" + ], + "complexity": "Medium", + "successrate": 58.3, + "totalsubmissions": 68986, + "totalaccepted": 40205, + "likes": 849, + "dislikes": 73, + "hints": "Store number of computer in each row and column. Count all servers that are not isolated.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "grid = [[1,0],[0,1]]", + "expected_output": "0\nExplanation: No servers can communicate with others.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "grid = [[1,0],[1,1]]", + "expected_output": "3\nExplanation: All three servers can communicate with at least one other server.", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "grid = [[1,1,0,0],[0,0,1,0],[0,0,1,0],[0,0,0,1]]", + "expected_output": "4\nExplanation: The two servers in the first row can communicate with each other. The two servers in the third column can communicate with each other. The server at right bottom corner can't communicate with any other server.", + "explanation": "" + } + ], + "solution": null + }, + { + "_id": "66f925ddfdfb8e1665720d66", + "questionid": 667, + "title": "Search Suggestions System", + "slug": "search-suggestions-system", + "description": "You are given an array of strings products and a string searchWord. Design a system that suggests at most three product names from products after each character of searchWord is typed. Suggested products should have common prefix with searchWord. If there are more than three products with a common prefix return the three lexicographically minimums products. Return a list of lists of the suggested products after each character of searchWord is typed. ", + "category": [ + "Array", + "String", + "Trie" + ], + "complexity": "Medium", + "successrate": 65.4, + "totalsubmissions": 229349, + "totalaccepted": 149953, + "likes": 2209, + "dislikes": 132, + "hints": "Brute force is a good choice because length of the string is \u2030\u00a4 1000. Binary search the answer. Use Trie data structure to store the best three matching. Traverse the Trie.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "products = ["mobile","mouse","moneypot","monitor","mousepad"], searchWord = "mouse"", + "expected_output": "[["mobile","moneypot","monitor"],["mobile","moneypot","monitor"],["mouse","mousepad"],["mouse","mousepad"],["mouse","mousepad"]]", + "explanation": "products sorted lexicographically = ["mobile","moneypot","monitor","mouse","mousepad"].\nAfter typing m and mo all products match and we show user ["mobile","moneypot","monitor"].\nAfter typing mou, mous and mouse the system suggests ["mouse","mousepad"]." + }, + { + "example_num": 2, + "expected_input": "products = ["havana"], searchWord = "havana"", + "expected_output": "[["havana"],["havana"],["havana"],["havana"],["havana"],["havana"]]", + "explanation": "The only word "havana" will be always suggested while typing the search word." + } + ], + "solution": "/**\n * @param {string[]} products\n * @param {string} searchWord\n * @return {string[][]}\n */\nconst suggestedProducts = function(products, searchWord) {\n products.sort()\n let res = [], left = 0, right = products.length - 1\n for (let i = 0; i < searchWord.length; i++) {\n let c = searchWord.charAt(i), tmp = []\n while (products[left]?.charAt(i) < c) left++\n while (products[right]?.charAt(i) > c) right--\n for (let j = 0; j < 3 && left + j <= right; j++) tmp.push(products[left+j])\n res.push(tmp)\n }\n return res\n};\n\n// another\n\n/**\n * @param {string[]} products\n * @param {string} searchWord\n * @return {string[][]}\n */\nconst suggestedProducts = function(products, searchWord) {\n const res = []\n for(let i = 0, n = searchWord.length; i < n; i++) {\n const tmp = [], pre = searchWord.slice(0, i + 1)\n for(const e of products) {\n if(e.startsWith(pre)) {\n tmp.push(e)\n tmp.sort((a, b) => a.localeCompare(b))\n if(tmp.length > 3) tmp.pop()\n }\n }\n res.push(tmp)\n }\n return res\n};\n\n// another\n\n/**\n * @param {string[]} products\n * @param {string} searchWord\n * @return {string[][]}\n */\n const suggestedProducts = function (products, searchWord) {\n products.sort()\n const root = new Node()\n for (const str of products) {\n addProduct(str)\n }\n\n const res = []\n\n let cur = root\n for (const ch of searchWord) {\n const tmp = []\n if (cur == null) {\n res.push(tmp)\n continue\n }\n const map = cur.children.get(ch)\n if (map != null) {\n addThree(map.words.values(), tmp)\n }\n\n res.push(tmp)\n cur = map\n }\n\n return res\n\n function addThree(it, arr) {\n\n for(let i = 0; i < 3; i++) {\n const res = it.next()\n if(res.value) arr.push(res.value)\n }\n }\n\n function addProduct(str) {\n let cur = root\n for (const ch of str) {\n let next = cur.children.get(ch)\n if (next == null) {\n next = new Node()\n cur.children.set(ch, next)\n }\n next.words.add(str)\n cur = next\n }\n cur.isWord = true\n }\n}\n\nclass Node {\n constructor() {\n this.children = new Map()\n this.words = new Set()\n this.isWord = false\n }\n}\n\n" + }, + { + "_id": "66f925ddfdfb8e1665720d6d", + "questionid": 674, + "title": "Shortest Path in a Grid with Obstacles Elimination", + "slug": "shortest-path-in-a-grid-with-obstacles-elimination", + "description": "You are given an m x n integer matrix grid where each cell is either 0 (empty) or 1 (obstacle). You can move up, down, left, or right from and to an empty cell in one step. Return the minimum number of steps to walk from the upper left corner (0, 0) to the lower right corner (m - 1, n - 1) given that you can eliminate at most k obstacles. If it is not possible to find such walk return -1. ", + "category": [ + "Array", + "Breadth-First Search", + "Matrix" + ], + "complexity": "Hard", + "successrate": 43.6, + "totalsubmissions": 208324, + "totalaccepted": 90733, + "likes": 2097, + "dislikes": 39, + "hints": "Use BFS. BFS on (x,y,r) x,y is coordinate, r is remain number of obstacles you can remove.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "grid = [[0,0,0],[1,1,0],[0,0,0],[0,1,1],[0,0,0]], k = 1", + "expected_output": "6", + "explanation": "The shortest path without eliminating any obstacle is 10.\nThe shortest path with one obstacle elimination at position (3,2) is 6. Such path is (0,0) -> (0,1) -> (0,2) -> (1,2) -> (2,2) -> (3,2) -> (4,2)." + }, + { + "example_num": 2, + "expected_input": "grid = [[0,1,1],[1,1,1],[1,0,0]], k = 1", + "expected_output": "-1", + "explanation": "We need to eliminate at least two obstacles to find such a walk." + } + ], + "solution": "/**\n * @param {number[][]} grid\n * @param {number} k\n * @return {number}\n */\nconst shortestPath = function (grid, k) {\n const m = grid.length\n const n = m && grid[0].length\n if (m === 1 && n === 1) return 0\n const queue = [[0, 0, k]]\n const dirs = [\n [1, 0],\n [-1, 0],\n [0, 1],\n [0, -1],\n ]\n const visited = new Set()\n let steps = 0\n while (queue.length > 0) {\n let size = queue.length\n while (size--) {\n const [row, col, em] = queue.shift()\n if (visited.has(row + \"#\" + col + \"#\" + em)) continue\n visited.add(row + \"#\" + col + \"#\" + em)\n for (let dir of dirs) {\n const nx = row + dir[0]\n const ny = col + dir[1]\n if (\n nx < 0 ||\n nx >= m ||\n ny < 0 ||\n ny >= n ||\n visited.has(nx + \"#\" + ny + \"#\" + em)\n )\n continue\n if (nx === m - 1 && ny === n - 1) return steps + 1\n if (grid[nx][ny] === 1) {\n if (em > 0) queue.push([nx, ny, em - 1])\n } else {\n queue.push([nx, ny, em])\n }\n }\n }\n steps++\n }\n return -1\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720d6f", + "questionid": 676, + "title": "Divide Array in Sets of K Consecutive Numbers", + "slug": "divide-array-in-sets-of-k-consecutive-numbers", + "description": "Given an array of integers nums and a positive integer k, check whether it is possible to divide this array into sets of k consecutive numbers. Return true if it is possible. Otherwise, return false. ", + "category": [ + "Array", + "Hash Table", + "Greedy", + "Sorting" + ], + "complexity": "Medium", + "successrate": 56.5, + "totalsubmissions": 104160, + "totalaccepted": 58857, + "likes": 1067, + "dislikes": 81, + "hints": "If the smallest number in the possible-to-split array is V, then numbers V+1, V+2, ... V+k-1 must contain there as well. You can iteratively find k sets and remove them from array until it becomes empty. Failure to do so would mean that array is unsplittable.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,2,3,3,4,4,5,6], k = 4", + "expected_output": "true", + "explanation": "Array can be divided into [1,2,3,4] and [3,4,5,6]." + }, + { + "example_num": 2, + "expected_input": "nums = [3,2,1,2,3,4,3,4,5,9,10,11], k = 3", + "expected_output": "true", + "explanation": "Array can be divided into [1,2,3] , [2,3,4] , [3,4,5] and [9,10,11]." + }, + { + "example_num": 3, + "expected_input": "nums = [1,2,3,4], k = 3", + "expected_output": "false", + "explanation": "Each array should be divided in subarrays of size 3." + } + ], + "solution": null + }, + { + "_id": "66f925ddfdfb8e1665720d73", + "questionid": 680, + "title": "All Ancestors of a Node in a Directed Acyclic Graph", + "slug": "all-ancestors-of-a-node-in-a-directed-acyclic-graph", + "description": "You are given a positive integer n representing the number of nodes of a Directed Acyclic Graph (DAG). The nodes are numbered from 0 to n - 1 (inclusive). You are also given a 2D integer array edges, where edges[i] = [fromi, toi] denotes that there is a unidirectional edge from fromi to toi in the graph. Return a list answer, where answer[i] is the list of ancestors of the ith node, sorted in ascending order. A node u is an ancestor of another node v if u can reach v via a set of edges. ", + "category": [ + "Depth-First Search", + "Breadth-First Search", + "Graph", + "Topological Sort" + ], + "complexity": "Medium", + "successrate": 46.1, + "totalsubmissions": 20517, + "totalaccepted": 9460, + "likes": 351, + "dislikes": 4, + "hints": "Consider how reversing each edge of the graph can help us. How can performing BFS/DFS on the reversed graph help us find the ancestors of every node?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 8, edgeList = [[0,3],[0,4],[1,3],[2,4],[2,7],[3,5],[3,6],[3,7],[4,6]]", + "expected_output": "[[],[],[],[0,1],[0,2],[0,1,3],[0,1,2,3,4],[0,1,2,3]]", + "explanation": "The above diagram represents the input graph.\n- Nodes 0, 1, and 2 do not have any ancestors.\n- Node 3 has two ancestors 0 and 1.\n- Node 4 has two ancestors 0 and 2.\n- Node 5 has three ancestors 0, 1, and 3.\n- Node 6 has five ancestors 0, 1, 2, 3, and 4.\n- Node 7 has four ancestors 0, 1, 2, and 3." + }, + { + "example_num": 2, + "expected_input": "n = 5, edgeList = [[0,1],[0,2],[0,3],[0,4],[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]", + "expected_output": "[[],[0],[0,1],[0,1,2],[0,1,2,3]]", + "explanation": "The above diagram represents the input graph.\n- Node 0 does not have any ancestor.\n- Node 1 has one ancestor 0.\n- Node 2 has two ancestors 0 and 1.\n- Node 3 has three ancestors 0, 1, and 2.\n- Node 4 has four ancestors 0, 1, 2, and 3." + } + ], + "solution": "/**\n * @param {number} n\n * @param {number[][]} edges\n * @return {number[][]}\n */\nconst getAncestors = function(n, edges) {\n const res = Array.from({ length: n }, () => [])\n const graph = {}\n \n for(const [u, v] of edges) {\n if(graph[u] == null) graph[u] = []\n graph[u].push(v)\n }\n \n for(let i = 0; i < n; i++) {\n dfs(i, i)\n }\n \n return res\n \n function dfs(p, cur) {\n for(const nxt of (graph[cur] || [])) {\n if(res[nxt].length === 0 || res[nxt][res[nxt].length - 1] !== p) {\n res[nxt].push(p)\n dfs(p, nxt)\n }\n }\n }\n};\n\n// another\n\n/**\n * @param {number} n\n * @param {number[][]} edges\n * @return {number[][]}\n */\nconst getAncestors = function(n, edges) {\n const res = Array.from({ length: n }, () => new Set())\n const inDegree = Array(n).fill(0)\n const graph = {}\n \n for(const [u, v] of edges) {\n if(graph[v] == null) graph[v] = []\n graph[v].push(u)\n inDegree[v]++\n }\n \n const visited = Array(n).fill(false)\n for (let i = 0; i < n; i++) {\n if (!visited[i]) dfs(i);\n }\n\n return res.map(set => Array.from(set).sort((a, b) => a - b))\n \n function dfs(i) {\n visited[i] = true\n for(const p of (graph[i] || [])) {\n if(visited[p] === false) dfs(p)\n res[i].add(p)\n for(const e of res[p]) res[i].add(e)\n }\n }\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720d83", + "questionid": 696, + "title": "Find the City With the Smallest Number of Neighbors at a Threshold Distance", + "slug": "find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance", + "description": "There are n cities numbered from 0 to n-1. Given the array edges where edges[i] = [fromi, toi, weighti] represents a bidirectional and weighted edge between cities fromi and toi, and given the integer distanceThreshold. Return the city with the smallest number of cities that are reachable through some path and whose distance is at most distanceThreshold, If there are multiple such cities, return the city with the greatest number. Notice that the distance of a path connecting cities i and j is equal to the sum of the edges' weights along that path. ", + "category": [ + "Dynamic Programming", + "Graph", + "Shortest Path" + ], + "complexity": "Medium", + "successrate": 51.1, + "totalsubmissions": 74264, + "totalaccepted": 37977, + "likes": 1113, + "dislikes": 56, + "hints": "Use Floyd-Warshall's algorithm to compute any-point to any-point distances. (Or can also do Dijkstra from every node due to the weights are non-negative). For each city calculate the number of reachable cities within the threshold, then search for the optimal city.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 4, edges = [[0,1,3],[1,2,1],[1,3,4],[2,3,1]], distanceThreshold = 4", + "expected_output": "3\nExplanation: The figure above describes the graph. \nThe neighboring cities at a distanceThreshold = 4 for each city are:\nCity 0 -> [City 1, City 2] \nCity 1 -> [City 0, City 2, City 3] \nCity 2 -> [City 0, City 1, City 3] \nCity 3 -> [City 1, City 2] \nCities 0 and 3 have 2 neighboring cities at a distanceThreshold = 4, but we have to return city 3 since it has the greatest number.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "n = 5, edges = [[0,1,2],[0,4,8],[1,2,3],[1,4,2],[2,3,1],[3,4,1]], distanceThreshold = 2", + "expected_output": "0\nExplanation: The figure above describes the graph. \nThe neighboring cities at a distanceThreshold = 2 for each city are:\nCity 0 -> [City 1] \nCity 1 -> [City 0, City 4] \nCity 2 -> [City 3, City 4] \nCity 3 -> [City 2, City 4]\nCity 4 -> [City 1, City 2, City 3] \nThe city 0 has 1 neighboring city at a distanceThreshold = 2.", + "explanation": "" + } + ], + "solution": "function floyd_warshall (n, edges, start) {\n let d = [...Array(n)].map(() => Array(n).fill(Number.MAX_SAFE_INTEGER))\n for (const [u, v, cost] of edges) {\n // UG\n let c = cost == undefined ? 1 : cost\n d[u][v] = d[v][u] = c\n }\n // for (const [u, v, cost] of edges) d[u][v] = cost == undefined ? 1 : cost; // DG\n for (let i = start; i < n; i++) d[i][i] = 0\n for (let k = start; k < n; k++) {\n for (let i = start; i < n; i++) {\n for (let j = start; j < n; j++) {\n if (d[i][j] > d[i][k] + d[k][j]) d[i][j] = d[i][k] + d[k][j]\n }\n }\n }\n return d\n}\n/**\n * @param {number} n\n * @param {number[][]} edges\n * @param {number} distanceThreshold\n * @return {number}\n */\nconst findTheCity = function(n, edges, distanceThreshold) {\n let dis = floyd_warshall(n, edges, 0),\n res = []\n for (let start = 0; start < n; start++) {\n let canReach = new Set()\n for (let dest = 0; dest < n; dest++) {\n if (start == dest) continue\n if (dis[start][dest] <= distanceThreshold) canReach.add(dest)\n }\n res.push([start, canReach.size])\n }\n res.sort((x, y) => {\n if (x[1] != y[1]) return x[1] - y[1]\n return y[0] - x[0]\n })\n return res[0][0]\n}\n\n" + }, + { + "_id": "66f925ddfdfb8e1665720d84", + "questionid": 697, + "title": "Minimum Difficulty of a Job Schedule", + "slug": "minimum-difficulty-of-a-job-schedule", + "description": "You want to schedule a list of jobs in d days. Jobs are dependent (i.e To work on the ith job, you have to finish all the jobs j where 0 <= j < i). You have to finish at least one task every day. The difficulty of a job schedule is the sum of difficulties of each day of the d days. The difficulty of a day is the maximum difficulty of a job done on that day. You are given an integer array jobDifficulty and an integer d. The difficulty of the ith job is jobDifficulty[i]. Return the minimum difficulty of a job schedule. If you cannot find a schedule for the jobs return -1. ", + "category": [ + "Array", + "Dynamic Programming" + ], + "complexity": "Hard", + "successrate": 56.5, + "totalsubmissions": 119707, + "totalaccepted": 67682, + "likes": 1212, + "dislikes": 140, + "hints": "Use DP. Try to cut the array into d non-empty sub-arrays. Try all possible cuts for the array. Use dp[i][j] where DP states are i the index of the last cut and j the number of remaining cuts. Complexity is O(n * n * d).", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "jobDifficulty = [6,5,4,3,2,1], d = 2", + "expected_output": "7", + "explanation": "First day you can finish the first 5 jobs, total difficulty = 6.\nSecond day you can finish the last job, total difficulty = 1.\nThe difficulty of the schedule = 6 + 1 = 7" + }, + { + "example_num": 2, + "expected_input": "jobDifficulty = [9,9,9], d = 4", + "expected_output": "-1", + "explanation": "If you finish a job per day you will still have a free day. you cannot find a schedule for the given jobs." + }, + { + "example_num": 3, + "expected_input": "jobDifficulty = [1,1,1], d = 3", + "expected_output": "3", + "explanation": "The schedule is one job per day. total difficulty will be 3." + } + ], + "solution": "/**\n * @param {number[]} jobDifficulty\n * @param {number} d\n * @return {number}\n */\nconst minDifficulty = function (jobDifficulty, d) {\n if (jobDifficulty.length < d) return -1\n const cache = {}\n const dfs = (start, numDays) => {\n if (numDays === d) {\n return start === jobDifficulty.length ? 0 : Infinity\n }\n const key = `${start}-${numDays}`\n if (cache[key] !== undefined) return cache[key]\n const end = jobDifficulty.length - d + numDays\n let result = Infinity\n let max = -Infinity\n for (let i = start; i <= end; i++) {\n max = Math.max(max, jobDifficulty[i])\n result = Math.min(result, max + dfs(i + 1, numDays + 1))\n }\n return (cache[key] = result)\n }\n return dfs(0, 0)\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720d85", + "questionid": 698, + "title": "Sort Integers by The Number of 1 Bits", + "slug": "sort-integers-by-the-number-of-1-bits", + "description": "You are given an integer array arr. Sort the integers in the array\u00a0in ascending order by the number of 1's\u00a0in their binary representation and in case of two or more integers have the same number of 1's you have to sort them in ascending order. Return the array after sorting it. ", + "category": [ + "Array", + "Bit Manipulation", + "Sorting", + "Counting" + ], + "complexity": "Easy", + "successrate": 71.4, + "totalsubmissions": 91233, + "totalaccepted": 65098, + "likes": 988, + "dislikes": 45, + "hints": "Simulate the problem. Count the number of 1's in the binary representation of each integer. Sort by the number of 1's ascending and by the value in case of tie.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "arr = [0,1,2,3,4,5,6,7,8]", + "expected_output": "[0,1,2,4,8,3,5,6,7]\nExplantion: [0] is the only integer with 0 bits.\n[1,2,4,8] all have 1 bit.\n[3,5,6] have 2 bits.\n[7] has 3 bits.\nThe sorted array by bits is [0,1,2,4,8,3,5,6,7]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "arr = [1024,512,256,128,64,32,16,8,4,2,1]", + "expected_output": "[1,2,4,8,16,32,64,128,256,512,1024]\nExplantion: All integers have 1 bit in the binary representation, you should just sort them in ascending order.", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} arr\n * @return {number[]}\n */\nconst sortByBits = function(arr) {\n arr.sort((a, b) => {\n const an = numOfBits(a), bn = numOfBits(b)\n return an === bn ? a - b : an - bn\n })\n return arr\n};\n\nfunction numOfBits(n) {\n let res = 0\n for(let i = 0; i < 32; i++) {\n if((1 << i) & n) res++\n }\n return res\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720d89", + "questionid": 702, + "title": "Maximum Product of Splitted Binary Tree", + "slug": "maximum-product-of-splitted-binary-tree", + "description": "Given the root of a binary tree, split the binary tree into two subtrees by removing one edge such that the product of the sums of the subtrees is maximized. Return the maximum product of the sums of the two subtrees. Since the answer may be too large, return it modulo 109 + 7. Note that you need to maximize the answer before taking the mod and not after taking it. ", + "category": [ + "Tree", + "Depth-First Search", + "Binary Tree" + ], + "complexity": "Medium", + "successrate": 42.9, + "totalsubmissions": 130468, + "totalaccepted": 55984, + "likes": 1221, + "dislikes": 55, + "hints": "If we know the sum of a subtree, the answer is max( (total_sum - subtree_sum) * subtree_sum) in each node.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [1,2,3,4,5,6]", + "expected_output": "110", + "explanation": "Remove the red edge and get 2 binary trees with sum 11 and 10. Their product is 110 (11*10)" + }, + { + "example_num": 2, + "expected_input": "root = [1,null,2,3,4,null,null,5,6]", + "expected_output": "90", + "explanation": "Remove the red edge and get 2 binary trees with sum 15 and 6.Their product is 90 (15*6)" + } + ], + "solution": null + }, + { + "_id": "66f925ddfdfb8e1665720d8a", + "questionid": 703, + "title": "Minimum Number of Steps to Make Two Strings Anagram", + "slug": "minimum-number-of-steps-to-make-two-strings-anagram", + "description": "You are given two strings of the same length s and t. In one step you can choose any character of t and replace it with another character. Return the minimum number of steps to make t an anagram of s. An Anagram of a string is a string that contains the same characters with a different (or the same) ordering. ", + "category": [ + "Hash Table", + "String", + "Counting" + ], + "complexity": "Medium", + "successrate": 76.3, + "totalsubmissions": 115048, + "totalaccepted": 87802, + "likes": 1203, + "dislikes": 56, + "hints": "Count the frequency of characters of each string. Loop over all characters if the frequency of a character in t is less than the frequency of the same character in s then add the difference between the frequencies to the answer.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "bab", t = "aba"", + "expected_output": "1", + "explanation": "Replace the first 'a' in t with b, t = "bba" which is anagram of s." + }, + { + "example_num": 2, + "expected_input": "s = "leetcode", t = "practice"", + "expected_output": "5", + "explanation": "Replace 'p', 'r', 'a', 'i' and 'c' from t with proper characters to make t anagram of s." + }, + { + "example_num": 3, + "expected_input": "s = "anagram", t = "mangaar"", + "expected_output": "0", + "explanation": ""anagram" and "mangaar" are anagrams." + } + ], + "solution": "/**\n * @param {string} s\n * @param {string} t\n * @return {number}\n */\nconst minSteps = function(s, t) {\n const as = Array(26).fill(0), ts = Array(26).fill(0)\n const a = 'a'.charCodeAt(0)\n for(const e of s){\n as[e.charCodeAt(0) - a]++\n }\n for(const e of t){\n ts[e.charCodeAt(0) - a]++\n }\n \n let com = 0\n for(let i = 0; i < 26; i++) {\n com += Math.min(as[i], ts[i])\n }\n return t.length - com\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720d8f", + "questionid": 708, + "title": "How Many Numbers Are Smaller Than the Current Number", + "slug": "how-many-numbers-are-smaller-than-the-current-number", + "description": "Given the array nums, for each nums[i] find out how many numbers in the array are smaller than it. That is, for each nums[i] you have to count the number of valid j's\u00a0such that\u00a0j != i and nums[j] < nums[i]. Return the answer in an array. ", + "category": [ + "Array", + "Hash Table", + "Sorting", + "Counting" + ], + "complexity": "Easy", + "successrate": 86.3, + "totalsubmissions": 348022, + "totalaccepted": 300430, + "likes": 3039, + "dislikes": 62, + "hints": "Brute force for each array element. In order to improve the time complexity, we can sort the array and get the answer for each array element.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [8,1,2,2,3]", + "expected_output": "[4,0,1,1,3]", + "explanation": "For nums[0]=8 there exist four smaller numbers than it (1, 2, 2 and 3). \nFor nums[1]=1 does not exist any smaller number than it.\nFor nums[2]=2 there exist one smaller number than it (1). \nFor nums[3]=2 there exist one smaller number than it (1). \nFor nums[4]=3 there exist three smaller numbers than it (1, 2 and 2)." + }, + { + "example_num": 2, + "expected_input": "nums = [6,5,4,8]", + "expected_output": "[2,1,0,3]", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "nums = [7,7,7,7]", + "expected_output": "[0,0,0,0]", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} nums\n * @return {number[]}\n */\nconst smallerNumbersThanCurrent = function(nums) {\n const count = new Array(101).fill(0);\n const res = new Array(nums.length).fill(0);\n for (let i = 0; i < nums.length; i++) count[nums[i]]++\n for (let i = 1 ; i <= 100; i++) count[i] += count[i-1]\n for (let i = 0; i < nums.length; i++) {\n if (nums[i] == 0) res[i] = 0\n else res[i] = count[nums[i] - 1]\n }\n return res;\n};\n\n" + }, + { + "_id": "66f925ddfdfb8e1665720d8c", + "questionid": 705, + "title": "Find the Longest Substring Containing Vowels in Even Counts", + "slug": "find-the-longest-substring-containing-vowels-in-even-counts", + "description": "Given the string s, return the size of the longest substring containing each vowel an even number of times. That is, 'a', 'e', 'i', 'o', and 'u' must appear an even number of times. ", + "category": [ + "Hash Table", + "String", + "Bit Manipulation", + "Prefix Sum" + ], + "complexity": "Medium", + "successrate": 62.6, + "totalsubmissions": 29156, + "totalaccepted": 18248, + "likes": 1092, + "dislikes": 41, + "hints": "Represent the counts (odd or even) of vowels with a bitmask. Precompute the prefix xor for the bitmask of vowels and then get the longest valid substring.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "eleetminicoworoep"", + "expected_output": "13\nExplanation: The longest substring is "leetminicowor" which contains two each of the vowels: e, i and o and zero of the vowels: a and u.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "s = "leetcodeisgreat"", + "expected_output": "5", + "explanation": "The longest substring is "leetc" which contains two e's." + }, + { + "example_num": 3, + "expected_input": "s = "bcbcbc"", + "expected_output": "6", + "explanation": "In this case, the given string "bcbcbc" is the longest because all vowels: a, e, i, o and u appear zero times." + } + ], + "solution": "/**\n * @param {string} s\n * @return {number}\n */\nconst findTheLongestSubstring = function(s) {\n const n = s.length\n let res = 0, mask = 0\n const map = new Map([[0, -1]])\n \n for(let i = 0; i < n; i++) {\n const ch = s[i]\n const idx = 'aeiou'.indexOf(ch)\n if(idx !== -1) {\n mask ^= (1 << idx)\n }\n if(map.has(mask)) {\n res = Math.max(res, i - map.get(mask))\n } else {\n map.set(mask, i)\n }\n }\n \n return res\n};\n\n// another\n\n/**\n * @param {string} s\n * @return {number}\n */\nconst findTheLongestSubstring = function(s) {\n const n = s.length\n let res = 0, mask = 0\n const map = new Map([[0, -1]])\n \n for(let i = 0; i < n; i++) {\n const ch = s[i]\n const idx = 'aeiou'.indexOf(ch)\n if(idx !== -1) {\n mask ^= (1 << idx)\n if(map.has(mask)) {\n res = Math.max(res, i - map.get(mask))\n } else {\n map.set(mask, i)\n }\n } else {\n res = Math.max(res, i - map.get(mask))\n }\n }\n \n return res\n};\n\n// another\n\n/**\n * @param {string} s\n * @return {number}\n */\nconst findTheLongestSubstring = function(s) {\n const n = s.length\n const ch2num = ch => {\n const idx = 'aeiou'.indexOf(ch)\n return idx === -1 ? 0 : (1 << idx)\n }\n let res = 0\n let mask = 0\n const hash = new Map([[0, -1]])\n for (let i = 0; i < n; i++) {\n mask ^= ch2num(s[i])\n const first = hash.has(mask) ? hash.get(mask) : i\n if (!hash.has(mask)) hash.set(mask, i)\n res = Math.max(res, i - first)\n }\n\n return res\n};\n\n// another\n\n/**\n * @param {string} s\n * @return {number}\n */\nvar findTheLongestSubstring = function (s, V = 'aeiou', max = 0) {\n let encode = (c) => {\n let i = V.indexOf(c)\n return i == -1 ? 0 : 1 << i\n }\n let N = s.length\n let A = Array(N + 1).fill(0)\n let seen = new Map([[0, 0]])\n for (let i = 1; i <= N; ++i) {\n A[i] = A[i - 1] ^ encode(s[i - 1])\n let first = seen.has(A[i]) ? seen.get(A[i]) : i\n if (first == i) seen.set(A[i], i) // first seen A[i] index\n max = Math.max(max, i - first) // max of i-th index minus first seen A[i] index\n }\n return max\n}\n\n// another\n\n/**\n * @param {string} s\n * @return {number}\n */\nconst findTheLongestSubstring = function(s) {\n const n = s.length\n const ch2num = ch => {\n const idx = 'aeiou'.indexOf(ch)\n return idx === -1 ? 0 : (1 << idx)\n }\n let res = 0\n let mask = 0\n const hash = new Map([[0, 0]])\n for (let i = 1; i <= n; i++) {\n mask ^= ch2num(s[i - 1])\n const first = hash.has(mask) ? hash.get(mask) : i\n if (!hash.has(mask)) hash.set(mask, i)\n res = Math.max(res, i - first)\n }\n\n return res\n};\n\n// another\n\n/**\n * @param {string} s\n * @return {number}\n */\nconst findTheLongestSubstring = function (s) {\n let mask = 0\n const n = s.length,\n { max } = Math,\n map = new Map(),\n a = 'a'.charCodeAt(0),\n set = new Set(['a', 'e', 'i', 'o', 'u'])\n map.set(0, -1)\n let res = 0\n for (let i = 0; i < n; i++) {\n const ch = s[i]\n if (set.has(ch)) {\n const idx = ch.charCodeAt(0) - a\n mask ^= 1 << idx\n if (mask === 0) res = max(res, i + 1)\n else if (map.has(mask)) {\n res = max(res, i - map.get(mask))\n } else {\n map.set(mask, i)\n }\n } else {\n if(map.has(mask)) {\n // console.log(i, map.get(mask))\n res = max(res, i - map.get(mask))\n }\n }\n }\n\n return res\n}\n\n" + }, + { + "_id": "66f925ddfdfb8e1665720d8e", + "questionid": 707, + "title": "Maximum Number of Events That Can Be Attended", + "slug": "maximum-number-of-events-that-can-be-attended", + "description": "You are given an array of events where events[i] = [startDayi, endDayi]. Every event i starts at startDayi and ends at endDayi. You can attend an event i at any day d where startTimei <= d <= endTimei. You can only attend one event at any time d. Return the maximum number of events you can attend. ", + "category": [ + "Array", + "Greedy", + "Heap (Priority Queue)" + ], + "complexity": "Medium", + "successrate": 33.4, + "totalsubmissions": 161284, + "totalaccepted": 53903, + "likes": 1743, + "dislikes": 239, + "hints": "Sort the events by the start time and in case of tie by the end time in ascending order. Loop over the sorted events. Attend as much as you can and keep the last day occupied. When you try to attend new event keep in mind the first day you can attend a new event in.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "events = [[1,2],[2,3],[3,4]]", + "expected_output": "3", + "explanation": "You can attend all the three events.\nOne way to attend them all is as shown.\nAttend the first event on day 1.\nAttend the second event on day 2.\nAttend the third event on day 3." + }, + { + "example_num": 2, + "expected_input": "events= [[1,2],[2,3],[3,4],[1,2]]", + "expected_output": "4", + "explanation": "" + } + ], + "solution": "class PriorityQueue {\n constructor(comparator = (a, b) => a > b) {\n this.heap = []\n this.top = 0\n this.comparator = comparator\n }\n size() {\n return this.heap.length\n }\n isEmpty() {\n return this.size() === 0\n }\n peek() {\n return this.heap[this.top]\n }\n push(...values) {\n values.forEach((value) => {\n this.heap.push(value)\n this.siftUp()\n })\n return this.size()\n }\n pop() {\n const poppedValue = this.peek()\n const bottom = this.size() - 1\n if (bottom > this.top) {\n this.swap(this.top, bottom)\n }\n this.heap.pop()\n this.siftDown()\n return poppedValue\n }\n replace(value) {\n const replacedValue = this.peek()\n this.heap[this.top] = value\n this.siftDown()\n return replacedValue\n }\n\n parent = (i) => ((i + 1) >>> 1) - 1\n left = (i) => (i << 1) + 1\n right = (i) => (i + 1) << 1\n greater = (i, j) => this.comparator(this.heap[i], this.heap[j])\n swap = (i, j) => ([this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]])\n siftUp = () => {\n let node = this.size() - 1\n while (node > this.top && this.greater(node, this.parent(node))) {\n this.swap(node, this.parent(node))\n node = this.parent(node)\n }\n }\n siftDown = () => {\n let node = this.top\n while (\n (this.left(node) < this.size() && this.greater(this.left(node), node)) ||\n (this.right(node) < this.size() && this.greater(this.right(node), node))\n ) {\n let maxChild =\n this.right(node) < this.size() &&\n this.greater(this.right(node), this.left(node))\n ? this.right(node)\n : this.left(node)\n this.swap(node, maxChild)\n node = maxChild\n }\n }\n}\n/**\n * @param {number[][]} events\n * @return {number}\n */\nfunction maxEvents(events) {\n const pq = new PriorityQueue((a, b) => a < b)\n \n events.sort((a, b) => a[0] - b[0])\n let i = 0, res = 0, d = 0, n = events.length\n\n while(!pq.isEmpty() || i < n) {\n if(pq.isEmpty()) {\n d = events[i][0]\n }\n while(i < n && events[i][0] <= d) {\n pq.push(events[i++][1])\n }\n pq.pop()\n res++\n d++\n while(!pq.isEmpty() && pq.peek() < d) {\n pq.pop()\n }\n }\n\n return res\n}\n\n\n// another\n\nclass PriorityQueue {\n constructor(comparator = (a, b) => a > b) {\n this.heap = []\n this.top = 0\n this.comparator = comparator\n }\n size() {\n return this.heap.length\n }\n isEmpty() {\n return this.size() === 0\n }\n peek() {\n return this.heap[this.top]\n }\n push(...values) {\n values.forEach((value) => {\n this.heap.push(value)\n this.siftUp()\n })\n return this.size()\n }\n pop() {\n const poppedValue = this.peek()\n const bottom = this.size() - 1\n if (bottom > this.top) {\n this.swap(this.top, bottom)\n }\n this.heap.pop()\n this.siftDown()\n return poppedValue\n }\n replace(value) {\n const replacedValue = this.peek()\n this.heap[this.top] = value\n this.siftDown()\n return replacedValue\n }\n\n parent = (i) => ((i + 1) >>> 1) - 1\n left = (i) => (i << 1) + 1\n right = (i) => (i + 1) << 1\n greater = (i, j) => this.comparator(this.heap[i], this.heap[j])\n swap = (i, j) => ([this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]])\n siftUp = () => {\n let node = this.size() - 1\n while (node > this.top && this.greater(node, this.parent(node))) {\n this.swap(node, this.parent(node))\n node = this.parent(node)\n }\n }\n siftDown = () => {\n let node = this.top\n while (\n (this.left(node) < this.size() && this.greater(this.left(node), node)) ||\n (this.right(node) < this.size() && this.greater(this.right(node), node))\n ) {\n let maxChild =\n this.right(node) < this.size() &&\n this.greater(this.right(node), this.left(node))\n ? this.right(node)\n : this.left(node)\n this.swap(node, maxChild)\n node = maxChild\n }\n }\n}\n/**\n * @param {number[][]} events\n * @return {number}\n */\nfunction maxEvents(events) {\n const pq = new PriorityQueue((a, b) => a < b)\n events.sort((a, b) => a[0] - b[0])\n let res = 0, i = 0, n = events.length\n for(let d = 1; d <= 100000; d++) {\n while(i < n && events[i][0] === d) {\n pq.push(events[i++][1])\n }\n while(!pq.isEmpty() && pq.peek() < d) {\n pq.pop()\n }\n if(!pq.isEmpty()) {\n res++\n pq.pop()\n }\n }\n return res\n}\n\n\n// another\n\n\n\n/**\n * @param {number[][]} events\n * @return {number}\n */\nfunction maxEvents(events) {\n events.sort(([, aEnd], [, bEnd]) => aEnd - bEnd);\n const lastDay = events[events.length - 1][1];\n const segmentTree = new SegmentTree(Array.from({ length: lastDay }, (_, i) => i), Infinity, (a, b) => Math.min(a, b));\n let daysAttended = 0;\n\n for (const [start, end] of events) {\n // earliest attendable day\n const ead = segmentTree.queryIn(start - 1, end);\n if (ead <= end) {\n daysAttended += 1;\n segmentTree.setAt(ead, Infinity);\n }\n }\n\n return daysAttended;\n}\n\n// https://github.com/axross/complex-data-structures\n// new SegmentTree(values, identity, associate)\n// segmentTree.getAt(i)\n// segmentTree.queryIn(from, to)\n// segmentTree.setAt(i, value)\n// segmentTree.length\nclass SegmentTree{constructor(t,e,s){if(this.valueLength=t.length,this.identity=e,this.associate=s,0===t.length)this.tree=[];else{const h=2**Math.ceil(Math.log2(t.length))*2-1,i=[];for(let s=0;s<=h>>1;++s)i[(h>>1)+s]=s>1)-1;t>=0;--t)i[t]=s(i[2*t+1],i[2*t+2]);this.tree=i}}get length(){return this.valueLength}getAt(t){return this.tree[t+(this.tree.length>>1)]}queryIn(t,e){let s=this.identity;const h=[[0,0,1+(this.tree.length>>1)]];for(;h.length>0;){const[i,r,n]=h.pop();r>=t&&n<=e?s=this.associate(s,this.tree[i]):r>=e||nthis.tree.length>>1||h.push([2*i+1,r,r+n>>1],[2*i+2,r+n>>1,n])}return s}setAt(t,e){const s=t+(this.tree.length>>1);this.tree[s]=e;let h=s-1>>1;for(;h>=0;)this.tree[h]=this.associate(this.tree[2*h+1],this.tree[2*h+2]),h=h-1>>1}}\n\n\n// another\n\n/**\n * @param {number[][]} events\n * @return {number}\n */\nfunction maxEvents(events) {\n const pq = new MinPriorityQueue ()\n events.sort((a, b) => a[0] - b[0])\n let res = 0, i = 0, n = events.length\n for(let d = 1; d <= 1e5; d++) {\n while(i < n && events[i][0] === d) {\n pq.enqueue(events[i++][1])\n }\n while(!pq.isEmpty() && pq.front().element < d) {\n pq.dequeue()\n }\n if(!pq.isEmpty()) {\n res++\n pq.dequeue()\n }\n }\n return res\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720d91", + "questionid": 710, + "title": "Linked List in Binary Tree", + "slug": "linked-list-in-binary-tree", + "description": "Given a binary tree root and a\u00a0linked list with\u00a0head\u00a0as the first node. Return True if all the elements in the linked list starting from the head correspond to some downward path connected in the binary tree\u00a0otherwise return False. In this context downward path means a path that starts at some node and goes downwards. ", + "category": [ + "Linked List", + "Tree", + "Depth-First Search", + "Breadth-First Search", + "Binary Tree" + ], + "complexity": "Medium", + "successrate": 42.7, + "totalsubmissions": 109555, + "totalaccepted": 46815, + "likes": 1380, + "dislikes": 48, + "hints": "Create recursive function, given a pointer in a Linked List and any node in the Binary Tree. Check if all the elements in the linked list starting from the head correspond to some downward path in the binary tree.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "head = [4,2,8], root = [1,4,4,null,2,2,null,1,null,6,8,null,null,null,null,1,3]", + "expected_output": "true", + "explanation": "Nodes in blue form a subpath in the binary Tree." + }, + { + "example_num": 2, + "expected_input": "head = [1,4,2,6], root = [1,4,4,null,2,2,null,1,null,6,8,null,null,null,null,1,3]", + "expected_output": "true", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "head = [1,4,2,6,8], root = [1,4,4,null,2,2,null,1,null,6,8,null,null,null,null,1,3]", + "expected_output": "false", + "explanation": "There is no path in the binary tree that contains all the elements of the linked list from head." + } + ], + "solution": "/**\n * Definition for singly-linked list.\n * function ListNode(val, next) {\n * this.val = (val===undefined ? 0 : val)\n * this.next = (next===undefined ? null : next)\n * }\n */\n/**\n * Definition for a binary tree node.\n * function TreeNode(val, left, right) {\n * this.val = (val===undefined ? 0 : val)\n * this.left = (left===undefined ? null : left)\n * this.right = (right===undefined ? null : right)\n * }\n */\n/**\n * @param {ListNode} head\n * @param {TreeNode} root\n * @return {boolean}\n */\nfunction isSubPath(head, root) {\n let needle = convertLinkedListToArray(head);\n let lps = computeKMPTable(needle);\n return kmpSearch(root, 0);\n\n function kmpSearch(i, j) {\n if (j === needle.length) return true;\n if (i === null) return false;\n while (j > 0 && i.val !== needle[j]) j = lps[j - 1];\n if (i.val === needle[j]) j++;\n return kmpSearch(i.left, j) || kmpSearch(i.right, j);\n }\n\n function computeKMPTable(pattern) {\n let n = pattern.length;\n let lps = new Array(n);\n for (let i = 0; i < n; i++) {\n lps[i] = 0;\n }\n for (let i = 1, j = 0; i < n; i++) {\n while (j > 0 && pattern[i] !== pattern[j]) j = lps[j - 1];\n if (pattern[i] === pattern[j]) lps[i] = ++j;\n }\n return lps;\n }\n\n function convertLinkedListToArray(head) {\n let list = [];\n while (head !== null) {\n list.push(head.val);\n head = head.next;\n }\n return list;\n }\n}\n\n\n// another\n\n\n/**\n * Definition for singly-linked list.\n * function ListNode(val, next) {\n * this.val = (val===undefined ? 0 : val)\n * this.next = (next===undefined ? null : next)\n * }\n */\n/**\n * Definition for a binary tree node.\n * function TreeNode(val, left, right) {\n * this.val = (val===undefined ? 0 : val)\n * this.left = (left===undefined ? null : left)\n * this.right = (right===undefined ? null : right)\n * }\n */\n/**\n * @param {ListNode} head\n * @param {TreeNode} root\n * @return {boolean}\n */\nconst isSubPath = function(head, root) {\n return dfs(root)\n \n function dfs(node) {\n if(node == null) return false\n if(head.val === node.val) {\n let cur = head\n let q = [node]\n while(q.length) {\n const v = cur.val\n const tmp = []\n let mark = false\n for(const e of q) {\n if(e.val === v) {\n mark = true\n if(e.left) tmp.push(e.left)\n if(e.right) tmp.push(e.right)\n }\n }\n if(cur && !mark) break\n cur = cur.next\n if(cur == null) return true\n q = tmp\n }\n }\n return dfs(node.left) || dfs(node.right)\n }\n \n};\n\n\n// another\n\n\n/**\n * Definition for singly-linked list.\n * function ListNode(val, next) {\n * this.val = (val===undefined ? 0 : val)\n * this.next = (next===undefined ? null : next)\n * }\n */\n/**\n * Definition for a binary tree node.\n * function TreeNode(val, left, right) {\n * this.val = (val===undefined ? 0 : val)\n * this.left = (left===undefined ? null : left)\n * this.right = (right===undefined ? null : right)\n * }\n */\n/**\n * @param {ListNode} head\n * @param {TreeNode} root\n * @return {boolean}\n */\nconst isSubPath = function(head, root) {\n const res = { found: false }\n traverse(root, head, res)\n return res.found\n};\n\nfunction traverse(node, list, res) {\n if(res.found) return\n if(node == null) return\n if(node.val === list.val && helper(node, list)) {\n res.found = true\n return\n } \n traverse(node.left, list, res)\n traverse(node.right, list, res)\n}\n\nfunction helper(node, list) {\n if(list == null) return true\n if(node == null) return false\n if(list.val !== node.val) return false\n return helper(node.left, list.next) || helper(node.right, list.next)\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720d9d", + "questionid": 722, + "title": "Construct K Palindrome Strings", + "slug": "construct-k-palindrome-strings", + "description": "Given a string s and an integer k, return true if you can use all the characters in s to construct k palindrome strings or false otherwise. ", + "category": [ + "Hash Table", + "String", + "Greedy", + "Counting" + ], + "complexity": "Medium", + "successrate": 63.7, + "totalsubmissions": 55688, + "totalaccepted": 35479, + "likes": 691, + "dislikes": 69, + "hints": "If the s.length < k we cannot construct k strings from s and answer is false. If the number of characters that have odd counts is > k then the minimum number of palindrome strings we can construct is > k and answer is false. Otherwise you can construct exactly k palindrome strings and answer is true (why ?).", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "annabelle", k = 2", + "expected_output": "true", + "explanation": "You can construct two palindromes using all characters in s.\nSome possible constructions "anna" + "elble", "anbna" + "elle", "anellena" + "b"" + }, + { + "example_num": 2, + "expected_input": "s = "leetcode", k = 3", + "expected_output": "false", + "explanation": "It is impossible to construct 3 palindromes using all the characters of s." + }, + { + "example_num": 3, + "expected_input": "s = "true", k = 4", + "expected_output": "true", + "explanation": "The only possible solution is to put each character in a separate string." + } + ], + "solution": null + }, + { + "_id": "66f925ddfdfb8e1665720d9e", + "questionid": 723, + "title": "Reducing Dishes", + "slug": "reducing-dishes", + "description": "A chef has collected data on the satisfaction level of his n dishes. Chef can cook any dish in 1 unit of time. Like-time coefficient of a dish is defined as the time taken to cook that dish including previous dishes multiplied by its satisfaction level i.e. time[i] * satisfaction[i]. Return the maximum sum of like-time coefficient that the chef can obtain after dishes preparation. Dishes can be prepared in any order and the chef can discard some dishes to get this maximum value. ", + "category": [ + "Array", + "Dynamic Programming", + "Greedy", + "Sorting" + ], + "complexity": "Hard", + "successrate": 72.5, + "totalsubmissions": 49975, + "totalaccepted": 36207, + "likes": 926, + "dislikes": 136, + "hints": "Use dynamic programming to find the optimal solution by saving the previous best like-time coefficient and its corresponding element sum. If adding the current element to the previous best like-time coefficient and its corresponding element sum would increase the best like-time coefficient, then go ahead and add it. Otherwise, keep the previous best like-time coefficient.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "satisfaction = [-1,-8,0,5,-9]", + "expected_output": "14", + "explanation": "After Removing the second and last dish, the maximum total like-time coefficient will be equal to (-1*1 + 0*2 + 5*3 = 14).\nEach dish is prepared in one unit of time." + }, + { + "example_num": 2, + "expected_input": "satisfaction = [4,3,2]", + "expected_output": "20", + "explanation": "Dishes can be prepared in any order, (2*1 + 3*2 + 4*3 = 20)" + }, + { + "example_num": 3, + "expected_input": "satisfaction = [-1,-4,-5]", + "expected_output": "0", + "explanation": "People do not like the dishes. No dish is prepared." + } + ], + "solution": "/**\n * @param {number[]} satisfaction\n * @return {number}\n */\nconst maxSatisfaction = function (satisfaction, max = 0) {\n satisfaction.sort((a, b) => a - b)\n let res = 0\n let total = 0\n let len = satisfaction.length\n // \"We'll keep doing this as long as satisfaction[i] + total > 0\" === satisfaction[i] > -total\n // It is because the current running sum needs to be greater than 0 otherwise, it would decrease res.\n for (let i = len - 1; i >= 0 && satisfaction[i] > -total; i--) {\n total += satisfaction[i]\n res += total\n }\n return res\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720da2", + "questionid": 727, + "title": "Minimum Value to Get Positive Step by Step Sum", + "slug": "minimum-value-to-get-positive-step-by-step-sum", + "description": "Given an array of integers\u00a0nums, you start with an initial positive value startValue. In each iteration, you calculate the step by step sum of startValue\u00a0plus\u00a0elements in nums\u00a0(from left to right). Return the minimum positive value of\u00a0startValue such that the step by step sum is never less than 1. ", + "category": [ + "Array", + "Prefix Sum" + ], + "complexity": "Easy", + "successrate": 68.7, + "totalsubmissions": 100547, + "totalaccepted": 69049, + "likes": 1005, + "dislikes": 231, + "hints": "Find the minimum prefix sum.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [-3,2,-3,4,2]", + "expected_output": "5\nExplanation: If you choose startValue = 4, in the third iteration your step by step sum is less than 1.\nstep by step sum\nstartValue = 4 | startValue = 5 | nums\n (4 -3 ) = 1 | (5 -3 ) = 2 | -3\n (1 +2 ) = 3 | (2 +2 ) = 4 | 2\n (3 -3 ) = 0 | (4 -3 ) = 1 | -3\n (0 +4 ) = 4 | (1 +4 ) = 5 | 4\n (4 +2 ) = 6 | (5 +2 ) = 7 | 2", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "nums = [1,2]", + "expected_output": "1", + "explanation": "Minimum start value should be positive." + }, + { + "example_num": 3, + "expected_input": "nums = [1,-2,-3]", + "expected_output": "5", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} nums\n * @return {number}\n */\nconst minStartValue = function(nums) {\n let sum = 0, min = Infinity\n for(let e of nums) {\n sum += e\n min = Math.min(min, sum)\n }\n \n return min >= 0 ? 1 : -min + 1\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720daa", + "questionid": 735, + "title": "Display Table of Food Orders in a Restaurant", + "slug": "display-table-of-food-orders-in-a-restaurant", + "description": "Given\u00a0the array orders, which represents the orders that customers have done in a restaurant. More specifically\u00a0orders[i]=[customerNamei,tableNumberi,foodItemi] where customerNamei is the name of the customer, tableNumberi\u00a0is the table customer sit at, and foodItemi\u00a0is the item customer orders. Return the restaurant's \"display table\". The \"display table\" is a table whose row entries denote how many of each food item each table ordered. The first column is the table number and the remaining columns correspond to each food item in alphabetical order. The first row should be a header whose first column is \"Table\", followed by the names of the food items. Note that the customer names are not part of the table. Additionally, the rows should be sorted in numerically increasing order. ", + "category": [ + "Array", + "Hash Table", + "String", + "Sorting", + "Ordered Set" + ], + "complexity": "Medium", + "successrate": 72.3, + "totalsubmissions": 25760, + "totalaccepted": 18637, + "likes": 200, + "dislikes": 338, + "hints": "Keep the frequency of all pairs (tableNumber, foodItem) using a hashmap. Sort rows by tableNumber and columns by foodItem, then process the resulted table.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "orders = [["David","3","Ceviche"],["Corina","10","Beef Burrito"],["David","3","Fried Chicken"],["Carla","5","Water"],["Carla","5","Ceviche"],["Rous","3","Ceviche"]]", + "expected_output": "[["Table","Beef Burrito","Ceviche","Fried Chicken","Water"],["3","0","2","1","0"],["5","0","1","0","1"],["10","1","0","0","0"]] \r\nExplanation:\r\nThe displaying table looks like:\r\nTable,Beef Burrito,Ceviche,Fried Chicken,Water\r\n3 ,0 ,2 ,1 ,0\r\n5 ,0 ,1 ,0 ,1\r\n10 ,1 ,0 ,0 ,0\r\nFor the table 3: David orders "Ceviche" and "Fried Chicken", and Rous orders "Ceviche".\r\nFor the table 5: Carla orders "Water" and "Ceviche".\r\nFor the table 10: Corina orders "Beef Burrito".", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "orders = [["James","12","Fried Chicken"],["Ratesh","12","Fried Chicken"],["Amadeus","12","Fried Chicken"],["Adam","1","Canadian Waffles"],["Brianna","1","Canadian Waffles"]]", + "expected_output": "[["Table","Canadian Waffles","Fried Chicken"],["1","2","0"],["12","0","3"]]", + "explanation": "For the table 1: Adam and Brianna order "Canadian Waffles".\r\nFor the table 12: James, Ratesh and Amadeus order "Fried Chicken"." + }, + { + "example_num": 3, + "expected_input": "orders = [["Laura","2","Bean Burrito"],["Jhon","2","Beef Burrito"],["Melissa","2","Soda"]]", + "expected_output": "[["Table","Bean Burrito","Beef Burrito","Soda"],["2","1","1","1"]]", + "explanation": "" + } + ], + "solution": null + }, + { + "_id": "66f925ddfdfb8e1665720dab", + "questionid": 736, + "title": "Minimum Number of Frogs Croaking", + "slug": "minimum-number-of-frogs-croaking", + "description": "You are given the string croakOfFrogs, which represents a combination of the string \"croak\" from different frogs, that is, multiple frogs can croak at the same time, so multiple \"croak\" are mixed. Return the minimum number of different frogs to finish all the croaks in the given string. A valid \"croak\" means a frog is printing five letters 'c', 'r', 'o', 'a', and 'k' sequentially. The frogs have to print all five letters to finish a croak. If the given string is not a combination of a valid \"croak\" return -1. ", + "category": [ + "String", + "Counting" + ], + "complexity": "Medium", + "successrate": 49.6, + "totalsubmissions": 49977, + "totalaccepted": 24801, + "likes": 630, + "dislikes": 39, + "hints": "keep the frequency of all characters from \"croak\" using a hashmap. For each character in the given string, greedily match it to a possible \"croak\".", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "croakOfFrogs = "croakcroak"", + "expected_output": "1", + "explanation": "One frog yelling "croak" twice." + }, + { + "example_num": 2, + "expected_input": "croakOfFrogs = "crcoakroak"", + "expected_output": "2", + "explanation": "The minimum number of frogs is two. \nThe first frog could yell "crcoakroak".\nThe second frog could yell later "crcoakroak"." + }, + { + "example_num": 3, + "expected_input": "croakOfFrogs = "croakcrook"", + "expected_output": "-1", + "explanation": "The given string is an invalid combination of "croak" from different frogs." + } + ], + "solution": null + }, + { + "_id": "66f925ddfdfb8e1665720dac", + "questionid": 737, + "title": "Maximum Score After Splitting a String", + "slug": "maximum-score-after-splitting-a-string", + "description": "Given a\u00a0string s\u00a0of zeros and ones, return the maximum score after splitting the string into two non-empty substrings (i.e. left substring and right substring). The score after splitting a string is the number of zeros in the left substring plus the number of ones in the right substring. ", + "category": [ + "String" + ], + "complexity": "Easy", + "successrate": 57.8, + "totalsubmissions": 66177, + "totalaccepted": 38228, + "likes": 490, + "dislikes": 26, + "hints": "Precompute a prefix sum of ones ('1'). Iterate from left to right counting the number of zeros ('0'), then use the precomputed prefix sum for counting ones ('1'). Update the answer.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "011101"", + "expected_output": "5", + "explanation": "All possible ways of splitting s into two non-empty substrings are:\nleft = "0" and right = "11101", score = 1 + 4 = 5 \nleft = "01" and right = "1101", score = 1 + 3 = 4 \nleft = "011" and right = "101", score = 1 + 2 = 3 \nleft = "0111" and right = "01", score = 1 + 1 = 2 \nleft = "01110" and right = "1", score = 2 + 1 = 3" + }, + { + "example_num": 2, + "expected_input": "s = "00111"", + "expected_output": "5", + "explanation": "When left = "00" and right = "111", we get the maximum score = 2 + 3 = 5" + }, + { + "example_num": 3, + "expected_input": "s = "1111"", + "expected_output": "3", + "explanation": "" + } + ], + "solution": "/**\n * @param {string} s\n * @return {number}\n */\nconst maxScore = function(s) {\n const n = s.length\n let res = 0, numOfOne = 0\n for(let ch of s) {\n if(ch === '1') numOfOne++\n }\n for(let i = 0, one = 0; i < n - 1; i++) {\n if(s[i] === '1') one++\n res = Math.max(res, (i + 1 - one) + (numOfOne - one))\n }\n\n return res\n};\n\n// another\n\n/**\n * @param {string} s\n * @return {number}\n */\nconst maxScore = function(s) {\n const n = s.length\n let res = -Infinity, one = 0, zero = 0\n for(let i = 0; i < n; i++) {\n s[i] === '0' ? zero++ : one++\n if(i !== n - 1) res = Math.max(res, zero - one)\n }\n\n return res + one\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720db1", + "questionid": 742, + "title": "Count Good Nodes in Binary Tree", + "slug": "count-good-nodes-in-binary-tree", + "description": "Given a binary tree root, a node X in the tree is named\u00a0good if in the path from root to X there are no nodes with a value greater than X. Return the number of good nodes in the binary tree. ", + "category": [ + "Tree", + "Depth-First Search", + "Breadth-First Search", + "Binary Tree" + ], + "complexity": "Medium", + "successrate": 73, + "totalsubmissions": 216657, + "totalaccepted": 158078, + "likes": 2256, + "dislikes": 74, + "hints": "Use DFS (Depth First Search) to traverse the tree, and constantly keep track of the current path maximum.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [3,1,4,3,null,1,5]", + "expected_output": "4", + "explanation": "Nodes in blue are good.\r\nRoot Node (3) is always a good node.\r\nNode 4 -> (3,4) is the maximum value in the path starting from the root.\r\nNode 5 -> (3,4,5) is the maximum value in the path\r\nNode 3 -> (3,1,3) is the maximum value in the path." + }, + { + "example_num": 2, + "expected_input": "root = [3,3,null,4,2]", + "expected_output": "3", + "explanation": "Node 2 -> (3, 3, 2) is not good, because "3" is higher than it." + }, + { + "example_num": 3, + "expected_input": "root = [1]", + "expected_output": "1", + "explanation": "Root is considered as good." + } + ], + "solution": "/**\n * Definition for a binary tree node.\n * function TreeNode(val, left, right) {\n * this.val = (val===undefined ? 0 : val)\n * this.left = (left===undefined ? null : left)\n * this.right = (right===undefined ? null : right)\n * }\n */\n\n/**\n * @param {TreeNode} root\n * @return {number}\n */\nconst goodNodes = function(root) {\n if(root == null) return 0\n let res = 0\n\n helper(root, root.val)\n\n return res\n \n function helper(node, max) {\n if(node == null) return\n if(node.val >= max) {\n res++\n max = node.val\n }\n helper(node.left, max)\n helper(node.right, max)\n }\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720db9", + "questionid": 750, + "title": "Course Schedule IV", + "slug": "course-schedule-iv", + "description": "There are a total of numCourses courses you have to take, labeled from 0 to numCourses - 1. You are given an array prerequisites where prerequisites[i] = [ai, bi] indicates that you must take course ai first if you want to take course bi. Prerequisites can also be indirect. If course a is a prerequisite of course b, and course b is a prerequisite of course c, then course a is a prerequisite of course c. You are also given an array queries where queries[j] = [uj, vj]. For the jth query, you should answer whether course uj is a prerequisite of course vj or not. Return a boolean array answer, where answer[j] is the answer to the jth query. ", + "category": [ + "Depth-First Search", + "Breadth-First Search", + "Graph", + "Topological Sort" + ], + "complexity": "Medium", + "successrate": 47.8, + "totalsubmissions": 64004, + "totalaccepted": 30620, + "likes": 774, + "dislikes": 46, + "hints": "Imagine if the courses are nodes of a graph. We need to build an array isReachable[i][j]. Start a bfs from each course i and assign for each course j you visit isReachable[i][j] = True. Answer the queries from the isReachable array.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "numCourses = 2, prerequisites = [[1,0]], queries = [[0,1],[1,0]]", + "expected_output": "[false,true]", + "explanation": "The pair [1, 0] indicates that you have to take course 1 before you can take course 0.\nCourse 0 is not a prerequisite of course 1, but the opposite is true." + }, + { + "example_num": 2, + "expected_input": "numCourses = 2, prerequisites = [], queries = [[1,0],[0,1]]", + "expected_output": "[false,false]", + "explanation": "There are no prerequisites, and each course is independent." + }, + { + "example_num": 3, + "expected_input": "numCourses = 3, prerequisites = [[1,2],[1,0],[2,0]], queries = [[1,0],[1,2]]", + "expected_output": "[true,true]", + "explanation": "" + } + ], + "solution": "/**\n * @param {number} numCourses\n * @param {number[][]} prerequisites\n * @param {number[][]} queries\n * @return {boolean[]}\n */\nconst checkIfPrerequisite = function (numCourses, prerequisites, queries) {\n const n = numCourses, m = prerequisites.length\n const graph = {}, inDegree = Array(n).fill(0)\n \n for(const [s, e] of prerequisites) {\n if(graph[s] == null) graph[s] = []\n inDegree[e]++\n graph[s].push(e)\n }\n \n let q = []\n \n for(let i = 0; i < n; i++) {\n if(inDegree[i] === 0) q.push(i)\n }\n \n const hash = {}\n\n while(q.length) {\n const size = q.length\n const nxt = []\n for(let i = 0; i < size; i++) {\n const cur = q[i]\n for(const e of (graph[cur] || [])) {\n inDegree[e]--\n if(hash[e] == null) hash[e] = new Set()\n hash[e].add(cur)\n for(const dep of (hash[cur] || [])) {\n hash[e].add(dep)\n }\n \n if(inDegree[e] === 0) {\n nxt.push(e)\n }\n }\n }\n \n q = nxt\n }\n \n const res = []\n for(const [p, e] of queries) {\n if(hash[e] && hash[e].has(p)) res.push(true)\n else res.push(false)\n }\n \n return res\n}\n\n// another\n\n\n/**\n * @param {number} numCourses\n * @param {number[][]} prerequisites\n * @param {number[][]} queries\n * @return {boolean[]}\n */\nconst checkIfPrerequisite = function(numCourses, prerequisites, queries) {\n // https://en.wikipedia.org/wiki/Floyd%E2%80%93Warshall_algorithm\n const n = numCourses\n const connected = Array.from({ length: n }, () => Array(n).fill(false))\n for(let p of prerequisites) connected[p[0]][p[1]] = true\n for(let k = 0; k < n; k++) {\n for(let i = 0; i < n; i++) {\n for(let j = 0; j < n; j++) {\n connected[i][j] = connected[i][j] || (connected[i][k] && connected[k][j]);\n }\n }\n }\n const res = []\n for(let q of queries) res.push(connected[q[0]][q[1]])\n return res\n};\n\n// another\n\n/**\n * @param {number} numCourses\n * @param {number[][]} prerequisites\n * @param {number[][]} queries\n * @return {boolean[]}\n */\nconst checkIfPrerequisite = function (numCourses, prerequisites, queries) {\n const n = numCourses\n const connected = Array.from({ length: n }, () => Array(n).fill(false))\n for (let p of prerequisites) connected[p[0]][p[1]] = true\n for (let k = 0; k < n; k++) {\n for (let i = 0; i < n; i++) {\n for (let j = 0; j < n; j++) {\n connected[i][j] =\n connected[i][j] || (connected[i][k] && connected[k][j])\n }\n }\n }\n const res = []\n for (let q of queries) res.push(connected[q[0]][q[1]])\n return res\n}\n\n// another\n\n/**\n * @param {number} numCourses\n * @param {number[][]} prerequisites\n * @param {number[][]} queries\n * @return {boolean[]}\n */\nconst checkIfPrerequisite = function (numCourses, prerequisites, queries) {\n const graph = {},\n connected = Array.from({ length: numCourses }, () =>\n Array(numCourses).fill(-1)\n )\n for (const [u, v] of prerequisites) {\n if (graph[u] == null) graph[u] = []\n graph[u].push(v)\n connected[u][v] = 1\n }\n\n const res = []\n for (const [u, v] of queries) res.push(dfs(u, v))\n\n return res\n\n function dfs(u, v) {\n if (connected[u][v] !== -1) return connected[u][v]\n let res = false\n for (const next of graph[u] || []) {\n if (!res) {\n res ||= dfs(next, v)\n } else break\n }\n connected[u][v] = res\n return res\n }\n}\n\n" + }, + { + "_id": "66f925ddfdfb8e1665720dc3", + "questionid": 760, + "title": "Find Two Non-overlapping Sub-arrays Each With Target Sum", + "slug": "find-two-non-overlapping-sub-arrays-each-with-target-sum", + "description": "You are given an array of integers arr and an integer target. You have to find two non-overlapping sub-arrays of arr each with a sum equal target. There can be multiple answers so you have to find an answer where the sum of the lengths of the two sub-arrays is minimum. Return the minimum sum of the lengths of the two required sub-arrays, or return -1 if you cannot find such two sub-arrays. ", + "category": [ + "Array", + "Hash Table", + "Binary Search", + "Dynamic Programming", + "Sliding Window" + ], + "complexity": "Medium", + "successrate": 36.7, + "totalsubmissions": 98780, + "totalaccepted": 36246, + "likes": 1198, + "dislikes": 59, + "hints": "Let's create two arrays prefix and suffix where prefix[i] is the minimum length of sub-array ends before i and has sum = k, suffix[i] is the minimum length of sub-array starting at or after i and has sum = k. The answer we are searching for is min(prefix[i] + suffix[i]) for all values of i from 0 to n-1 where n == arr.length. If you are still stuck with how to build prefix and suffix, you can store for each index i the length of the sub-array starts at i and has sum = k or infinity otherwise, and you can use it to build both prefix and suffix.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "arr = [3,2,2,4,3], target = 3", + "expected_output": "2", + "explanation": "Only two sub-arrays have sum = 3 ([3] and [3]). The sum of their lengths is 2." + }, + { + "example_num": 2, + "expected_input": "arr = [7,3,4,7], target = 7", + "expected_output": "2", + "explanation": "Although we have three non-overlapping sub-arrays of sum = 7 ([7], [3,4] and [7]), but we will choose the first and third sub-arrays as the sum of their lengths is 2." + }, + { + "example_num": 3, + "expected_input": "arr = [4,3,2,6,2,3,4], target = 6", + "expected_output": "-1", + "explanation": "We have only one sub-array of sum = 6." + } + ], + "solution": null + }, + { + "_id": "66f925ddfdfb8e1665720dca", + "questionid": 767, + "title": "Longest Subarray of 1's After Deleting One Element", + "slug": "longest-subarray-of-1s-after-deleting-one-element", + "description": "Given a binary array nums, you should delete one element from it. Return the size of the longest non-empty subarray containing only 1's in the resulting array. Return 0 if there is no such subarray. ", + "category": [ + "Math", + "Dynamic Programming", + "Sliding Window" + ], + "complexity": "Medium", + "successrate": 60.1, + "totalsubmissions": 65170, + "totalaccepted": 39141, + "likes": 869, + "dislikes": 21, + "hints": "Maintain a sliding window where there is at most one zero on it.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,1,0,1]", + "expected_output": "3", + "explanation": "After deleting the number in position 2, [1,1,1] contains 3 numbers with value of 1's." + }, + { + "example_num": 2, + "expected_input": "nums = [0,1,1,1,0,1,1,0,1]", + "expected_output": "5", + "explanation": "After deleting the number in position 4, [0,1,1,1,1,1,0,1] longest subarray with value of 1's is [1,1,1,1,1]." + }, + { + "example_num": 3, + "expected_input": "nums = [1,1,1]", + "expected_output": "2", + "explanation": "You must delete one element." + } + ], + "solution": "/**\n * @param {number[]} nums\n * @return {number}\n */\nconst longestSubarray = function(nums) {\n const n = nums.length\n let res = 0\n const pre = Array(n).fill(0)\n const suf = Array(n).fill(0)\n \n let cnt = 0, hasZero = false\n for(let i = 0; i < n; i++) {\n if(nums[i] === 1) {\n cnt++\n pre[i] = cnt\n res = Math.max(res, cnt)\n } else {\n hasZero = true\n cnt = 0\n pre[i] = cnt\n }\n }\n if(!hasZero) res--\n \n cnt = 0\n \n for(let i = n - 1; i >= 0; i--) {\n if(nums[i] === 1) {\n cnt++\n suf[i] = cnt\n\n } else {\n cnt = 0\n suf[i] = cnt\n\n }\n }\n // console.log(pre,suf)\n for(let i = 1; i < n - 1; i++) {\n if(nums[i] === 0) {\n res = Math.max(res, pre[i - 1] + suf[i + 1])\n }\n }\n \n \n return res\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720d97", + "questionid": 716, + "title": "Frog Position After T Seconds", + "slug": "frog-position-after-t-seconds", + "description": "Given an undirected tree consisting of n vertices numbered from 1 to n. A frog starts jumping from vertex 1. In one second, the frog jumps from its current vertex to another unvisited vertex if they are directly connected. The frog can not jump back to a visited vertex. In case the frog can jump to several vertices, it jumps randomly to one of them with the same probability. Otherwise, when the frog can not jump to any unvisited vertex, it jumps forever on the same vertex. The edges of the undirected tree are given in the array edges, where edges[i] = [ai, bi] means that exists an edge connecting the vertices ai and bi. Return the probability that after t seconds the frog is on the vertex target. Answers within 10-5 of the actual answer will be accepted. ", + "category": [ + "Tree", + "Depth-First Search", + "Breadth-First Search", + "Graph" + ], + "complexity": "Hard", + "successrate": 36.3, + "totalsubmissions": 52971, + "totalaccepted": 19246, + "likes": 407, + "dislikes": 95, + "hints": "Use a variation of DFS with parameters 'curent_vertex' and 'current_time'. Update the probability considering to jump to one of the children vertices.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 7, edges = [[1,2],[1,3],[1,7],[2,4],[2,6],[3,5]], t = 2, target = 4", + "expected_output": "0.16666666666666666", + "explanation": "The figure above shows the given graph. The frog starts at vertex 1, jumping with 1/3 probability to the vertex 2 after second 1 and then jumping with 1/2 probability to vertex 4 after second 2. Thus the probability for the frog is on the vertex 4 after 2 seconds is 1/3 * 1/2 = 1/6 = 0.16666666666666666." + }, + { + "example_num": 2, + "expected_input": "n = 7, edges = [[1,2],[1,3],[1,7],[2,4],[2,6],[3,5]], t = 1, target = 7", + "expected_output": "0.3333333333333333\nExplanation: The figure above shows the given graph. The frog starts at vertex 1, jumping with 1/3 = 0.3333333333333333 probability to the vertex 7 after second 1.", + "explanation": "" + } + ], + "solution": "/**\n * @param {number} n\n * @param {number[][]} edges\n * @param {number} t\n * @param {number} target\n * @return {number}\n */\nconst frogPosition = function (n, edges, t, target) {\n const m = new Map()\n for(let e of edges) {\n const [from, to] = e\n if(!m.has(from - 1)) m.set(from - 1, [])\n if(!m.has(to - 1)) m.set(to - 1, [])\n m.get(from - 1).push(to - 1)\n m.get(to - 1).push(from - 1)\n }\n const visited = new Set()\n visited.add(0)\n const q = [0]\n const res = [1]\n while(q.length && t-- > 0) {\n for(let size = q.length; size > 0 ; size--) {\n const u = q.shift()\n let count = 0\n for(let e of (m.get(u) || [])) {\n if(!visited.has(e)) count++\n }\n for(let e of (m.get(u) || [])) {\n if(visited.has(e)) continue\n q.push(e)\n visited.add(e)\n res[e] = res[u] / count\n }\n if(count > 0) res[u] = 0 \n }\n }\n return res[target - 1] || 0\n}\n\n// another\n\n/**\n * @param {number} n\n * @param {number[][]} edges\n * @param {number} t\n * @param {number} target\n * @return {number}\n */\nconst frogPosition = function (n, edges, t, target) {\n const graph = { 1: new Set() }\n for (let [from, to] of edges) {\n if (graph[from]) graph[from].add(to)\n else graph[from] = new Set([to])\n if (graph[to]) graph[to].add(from)\n else graph[to] = new Set([from])\n }\n\n // dfs through the graph storing the vetices you've visited, number of jumps, and current vertice\n const dfs = (from, numJumps, visited) => {\n // if the count equals t then return 1 if the vertice is the target\n if (numJumps === t) return from === target ? 1 : 0\n\n // average out all the next results\n let numEdgesCanJump = 0\n let total = 0\n for (let to of graph[from]) {\n if (visited.has(to)) continue\n visited.add(to)\n total += dfs(to, numJumps + 1, visited)\n visited.delete(to)\n numEdgesCanJump++\n }\n\n // if we can jump, average all the next results\n // otherwise we can't jump anywhere and return 1 if we are at the target\n // if we are not at the target return 0\n if (numEdgesCanJump > 0) {\n return total / numEdgesCanJump\n }\n return from === target ? 1 : 0\n }\n return dfs(1, 0, new Set([1]))\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720d9c", + "questionid": 721, + "title": "Circle and Rectangle Overlapping", + "slug": "circle-and-rectangle-overlapping", + "description": "You are given a circle represented as (radius, xCenter, yCenter) and an axis-aligned rectangle represented as (x1, y1, x2, y2), where (x1, y1) are the coordinates of the bottom-left corner, and (x2, y2) are the coordinates of the top-right corner of the rectangle. Return true if the circle and rectangle are overlapped otherwise return false. In other words, check if there is any point (xi, yi) that belongs to the circle and the rectangle at the same time. ", + "category": [ + "Math", + "Geometry" + ], + "complexity": "Medium", + "successrate": 43.7, + "totalsubmissions": 22127, + "totalaccepted": 9667, + "likes": 223, + "dislikes": 55, + "hints": "Locate the closest point of the square to the circle, you can then find the distance from this point to the center of the circle and check if this is less than or equal to the radius.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "radius = 1, xCenter = 0, yCenter = 0, x1 = 1, y1 = -1, x2 = 3, y2 = 1", + "expected_output": "true", + "explanation": "Circle and rectangle share the point (1,0)." + }, + { + "example_num": 2, + "expected_input": "radius = 1, xCenter = 1, yCenter = 1, x1 = 1, y1 = -3, x2 = 2, y2 = -1", + "expected_output": "false", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "radius = 1, xCenter = 0, yCenter = 0, x1 = -1, y1 = 0, x2 = 0, y2 = 1", + "expected_output": "true", + "explanation": "" + } + ], + "solution": null + }, + { + "_id": "66f925ddfdfb8e1665720d9f", + "questionid": 724, + "title": "Longest Happy Prefix", + "slug": "longest-happy-prefix", + "description": "A string is called a happy prefix if is a non-empty prefix which is also a suffix (excluding itself). Given a string s, return the longest happy prefix of s. Return an empty string \"\" if no such prefix exists. ", + "category": [ + "String", + "Rolling Hash", + "String Matching", + "Hash Function" + ], + "complexity": "Hard", + "successrate": 44.4, + "totalsubmissions": 45258, + "totalaccepted": 20110, + "likes": 637, + "dislikes": 24, + "hints": "Use Longest Prefix Suffix (KMP-table) or String Hashing.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "level"", + "expected_output": ""l"", + "explanation": "s contains 4 prefix excluding itself ("l", "le", "lev", "leve"), and suffix ("l", "el", "vel", "evel"). The largest prefix which is also suffix is given by "l"." + }, + { + "example_num": 2, + "expected_input": "s = "ababab"", + "expected_output": ""abab"", + "explanation": ""abab" is the largest prefix which is also suffix. They can overlap in the original string." + } + ], + "solution": "/**\n * @param {string} s\n * @return {string}\n */\nconst longestPrefix = function(s) {\n return s.slice(0, dfa().pop())\n function dfa() {\n let i = 1\n let j = 0\n const len = s.length\n const prefix = Array(len + 1).fill(0)\n prefix[0] = -1\n prefix[1] = 0\n while(i < len) {\n if(s[j] === s[i]) {\n j++\n i++\n prefix[i] = j\n } else {\n if(j > 0) j = prefix[j]\n else i++\n }\n }\n return prefix\n } \n};\n\n\n" + }, + { + "_id": "66f925ddfdfb8e1665720da7", + "questionid": 732, + "title": "Kids With the Greatest Number of Candies", + "slug": "kids-with-the-greatest-number-of-candies", + "description": "There are n kids with candies. You are given an integer array candies, where each candies[i] represents the number of candies the ith kid has, and an integer extraCandies, denoting the number of extra candies that you have. Return a boolean array result of length n, where result[i] is true if, after giving the ith kid all the extraCandies, they will have the greatest number of candies among all the kids, or false otherwise. Note that multiple kids can have the greatest number of candies. ", + "category": [ + "Array" + ], + "complexity": "Easy", + "successrate": 87.7, + "totalsubmissions": 345368, + "totalaccepted": 302956, + "likes": 1514, + "dislikes": 269, + "hints": "Use greedy approach. For each kid check if candies[i] + extraCandies \u2030\u00a5 maximum in Candies[i].", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "candies = [2,3,5,1,3], extraCandies = 3", + "expected_output": "[true,true,true,false,true]", + "explanation": "If you give all extraCandies to:\n- Kid 1, they will have 2 + 3 = 5 candies, which is the greatest among the kids.\n- Kid 2, they will have 3 + 3 = 6 candies, which is the greatest among the kids.\n- Kid 3, they will have 5 + 3 = 8 candies, which is the greatest among the kids.\n- Kid 4, they will have 1 + 3 = 4 candies, which is not the greatest among the kids.\n- Kid 5, they will have 3 + 3 = 6 candies, which is the greatest among the kids." + }, + { + "example_num": 2, + "expected_input": "candies = [4,2,1,1,2], extraCandies = 1", + "expected_output": "[true,false,false,false,false]", + "explanation": "There is only 1 extra candy.\nKid 1 will always have the greatest number of candies, even if a different kid is given the extra candy." + }, + { + "example_num": 3, + "expected_input": "candies = [12,1,12], extraCandies = 10", + "expected_output": "[true,false,true]", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} candies\n * @param {number} extraCandies\n * @return {boolean[]}\n */\nconst kidsWithCandies = function(candies, extraCandies) {\n const res = []\n let max = 0\n for(let e of candies) max = Math.max(e, max)\n max -= extraCandies\n for(let i = 0, len = candies.length; i < len; i++) {\n res.push(candies[i] >= max)\n }\n return res\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720da9", + "questionid": 734, + "title": "Reformat The String", + "slug": "reformat-the-string", + "description": "You are given an alphanumeric string s. (Alphanumeric string is a string consisting of lowercase English letters and digits). You have to find a permutation of the string where no letter is followed by another letter and no digit is followed by another digit. That is, no two adjacent characters have the same type. Return the reformatted string or return an empty string if it is impossible to reformat the string. ", + "category": [ + "String" + ], + "complexity": "Easy", + "successrate": 56.3, + "totalsubmissions": 75088, + "totalaccepted": 42296, + "likes": 394, + "dislikes": 74, + "hints": "Count the number of letters and digits in the string. if cntLetters - cntDigits has any of the values [-1, 0, 1] we have an answer, otherwise we don't have any answer. Build the string anyway as you wish. Keep in mind that you need to start with the type that have more characters if cntLetters \u2030\u00a0 cntDigits.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "a0b1c2"", + "expected_output": ""0a1b2c"", + "explanation": "No two adjacent characters have the same type in "0a1b2c". "a0b1c2", "0a1b2c", "0c2a1b" are also valid permutations." + }, + { + "example_num": 2, + "expected_input": "s = "leetcode"", + "expected_output": """", + "explanation": ""leetcode" has only characters so we cannot separate them by digits." + }, + { + "example_num": 3, + "expected_input": "s = "1229857369"", + "expected_output": """", + "explanation": ""1229857369" has only digits so we cannot separate them by characters." + } + ], + "solution": "/**\n * @param {string} s\n * @return {string}\n */\nvar reformat = function(s) {\n let str = '', num = ''\n const isDigit = ch => ch >= '0' && ch <= '9'\n for(const ch of s) {\n if(isDigit(ch)) num += ch\n else str += ch\n }\n if(Math.abs(str.length - num.length) > 1) return ''\n if(str.length > num.length) {\n let res = ''\n for (let i = 0; i < str.length; i++) {\n res += str[i]\n if(i < num.length) res += num[i]\n }\n return res\n } else {\n let res = ''\n for (let i = 0; i < num.length; i++) {\n res += num[i]\n if(i < str.length) res += str[i]\n }\n return res\n }\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720dad", + "questionid": 738, + "title": "Maximum Points You Can Obtain from Cards", + "slug": "maximum-points-you-can-obtain-from-cards", + "description": "There are several cards arranged in a row, and each card has an associated number of points. The points are given in the integer array cardPoints. In one step, you can take one card from the beginning or from the end of the row. You have to take exactly k cards. Your score is the sum of the points of the cards you have taken. Given the integer array cardPoints and the integer k, return the maximum score you can obtain. ", + "category": [ + "Array", + "Sliding Window", + "Prefix Sum" + ], + "complexity": "Medium", + "successrate": 50, + "totalsubmissions": 254368, + "totalaccepted": 127286, + "likes": 2759, + "dislikes": 111, + "hints": "Let the sum of all points be total_pts. You need to remove a sub-array from cardPoints with length n - k. Keep a window of size n - k over the array. The answer is max(answer, total_pts - sumOfCurrentWindow)", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "cardPoints = [1,2,3,4,5,6,1], k = 3", + "expected_output": "12", + "explanation": "After the first step, your score will always be 1. However, choosing the rightmost card first will maximize your total score. The optimal strategy is to take the three cards on the right, giving a final score of 1 + 6 + 5 = 12." + }, + { + "example_num": 2, + "expected_input": "cardPoints = [2,2,2], k = 2", + "expected_output": "4", + "explanation": "Regardless of which two cards you take, your score will always be 4." + }, + { + "example_num": 3, + "expected_input": "cardPoints = [9,7,7,9,7,7,9], k = 7", + "expected_output": "55", + "explanation": "You have to take all the cards. Your score is the sum of points of all cards." + } + ], + "solution": null + }, + { + "_id": "66f925ddfdfb8e1665720db4", + "questionid": 745, + "title": "Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit", + "slug": "longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit", + "description": "Given an array of integers nums and an integer limit, return the size of the longest non-empty subarray such that the absolute difference between any two elements of this subarray is less than or equal to limit. ", + "category": [ + "Array", + "Queue", + "Sliding Window", + "Heap (Priority Queue)", + "Ordered Set", + "Monotonic Queue" + ], + "complexity": "Medium", + "successrate": 46.3, + "totalsubmissions": 170851, + "totalaccepted": 79025, + "likes": 2051, + "dislikes": 88, + "hints": "Use a sliding window approach keeping the maximum and minimum value using a data structure like a multiset from STL in C++. More specifically, use the two pointer technique, moving the right pointer as far as possible to the right until the subarray is not valid (maxValue - minValue > limit), then moving the left pointer until the subarray is valid again (maxValue - minValue <= limit). Keep repeating this process.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [8,2,4,7], limit = 4", + "expected_output": "2", + "explanation": "All subarrays are: \n[8] with maximum absolute diff |8-8| = 0 <= 4.\n[8,2] with maximum absolute diff |8-2| = 6 > 4. \n[8,2,4] with maximum absolute diff |8-2| = 6 > 4.\n[8,2,4,7] with maximum absolute diff |8-2| = 6 > 4.\n[2] with maximum absolute diff |2-2| = 0 <= 4.\n[2,4] with maximum absolute diff |2-4| = 2 <= 4.\n[2,4,7] with maximum absolute diff |2-7| = 5 > 4.\n[4] with maximum absolute diff |4-4| = 0 <= 4.\n[4,7] with maximum absolute diff |4-7| = 3 <= 4.\n[7] with maximum absolute diff |7-7| = 0 <= 4. \nTherefore, the size of the longest subarray is 2." + }, + { + "example_num": 2, + "expected_input": "nums = [10,1,2,4,7,2], limit = 5", + "expected_output": "4", + "explanation": "The subarray [2,4,7,2] is the longest since the maximum absolute diff is |2-7| = 5 <= 5." + }, + { + "example_num": 3, + "expected_input": "nums = [4,2,2,2,4,4,2,2], limit = 0", + "expected_output": "3", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} nums\n * @param {number} limit\n * @return {number}\n */\nconst longestSubarray = function(nums, limit) {\n let maxd = [], mind = [];\n let i = 0, j;\n for (j = 0; j < nums.length; ++j) {\n // non-increase\n while (maxd.length && nums[j] > maxd[maxd.length - 1]) maxd.pop();\n // non-decrease\n while (mind.length && nums[j] < mind[mind.length - 1]) mind.pop();\n\n maxd.push(nums[j]);\n mind.push(nums[j]);\n\n if (maxd[0] - mind[0] > limit) {\n if (maxd[0] == nums[i]) maxd.shift();\n if (mind[0] == nums[i]) mind.shift();\n ++i;\n }\n }\n return j - i; \n};\n\n// another\n\n/**\n * @param {number[]} nums\n * @param {number} limit\n * @return {number}\n */\nconst longestSubarray = function (nums, limit) {\n const maxDq = new Deque(), minDq = new Deque(), n = nums.length\n let l = 0, r = 0\n let res = 0\n for(r = 0; r < n; r++) {\n const cur = nums[r]\n while(!maxDq.isEmpty() && maxDq.last() < cur) {\n maxDq.pop()\n }\n maxDq.enqueue(cur)\n while(!minDq.isEmpty() && minDq.last() > cur) {\n minDq.pop()\n }\n minDq.enqueue(cur)\n\n while(maxDq.first() - minDq.first() > limit) {\n if(nums[l] === maxDq.first()) maxDq.dequeue()\n if(nums[l] === minDq.first()) minDq.dequeue()\n l++\n }\n res = Math.max(res, r - l + 1)\n }\n return res\n}\n\nclass Deque {\n constructor() {\n this.head = new Node()\n this.tail = this.head\n }\n\n isEmpty() {\n return this.head.next === null\n }\n\n first() {\n return this.head.next.value\n }\n\n last() {\n return this.tail.value\n }\n\n dequeue() {\n this.head = this.head.next\n this.head.prev = null\n }\n\n enqueue(value) {\n this.tail.next = new Node(value)\n this.tail.next.prev = this.tail\n this.tail = this.tail.next\n }\n\n pop() {\n this.tail = this.tail.prev\n this.tail.next = null\n }\n}\n\nclass Node {\n constructor(value) {\n this.value = value\n this.next = null\n this.prev = null\n }\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720db8", + "questionid": 749, + "title": "Check If a String Contains All Binary Codes of Size K", + "slug": "check-if-a-string-contains-all-binary-codes-of-size-k", + "description": "Given a binary string s and an integer k, return true if every binary code of length k is a substring of s. Otherwise, return false. ", + "category": [ + "Hash Table", + "String", + "Bit Manipulation", + "Rolling Hash", + "Hash Function" + ], + "complexity": "Medium", + "successrate": 54.5, + "totalsubmissions": 87271, + "totalaccepted": 47554, + "likes": 685, + "dislikes": 66, + "hints": "We need only to check all sub-strings of length k. The number of distinct sub-strings should be exactly 2^k.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "00110110", k = 2", + "expected_output": "true", + "explanation": "The binary codes of length 2 are "00", "01", "10" and "11". They can be all found as substrings at indices 0, 1, 3 and 2 respectively." + }, + { + "example_num": 2, + "expected_input": "s = "0110", k = 1", + "expected_output": "true", + "explanation": "The binary codes of length 1 are "0" and "1", it is clear that both exist as a substring." + }, + { + "example_num": 3, + "expected_input": "s = "0110", k = 2", + "expected_output": "false", + "explanation": "The binary code "00" is of length 2 and does not exist in the array." + } + ], + "solution": "/**\n * @param {string} s\n * @param {number} k\n * @return {boolean}\n */\nconst hasAllCodes = function (s, k) {\n if (s.length < k) return false\n const set = new Set()\n for (let i = 0; i <= s.length - k; i++) {\n set.add(s.slice(i, i + k))\n }\n\n return set.size == Math.pow(2, k)\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720dbb", + "questionid": 752, + "title": "People Whose List of Favorite Companies Is Not a Subset of Another List", + "slug": "people-whose-list-of-favorite-companies-is-not-a-subset-of-another-list", + "description": "Given the array favoriteCompanies where favoriteCompanies[i] is the list of favorites companies for the ith person (indexed from 0). Return the indices of people whose list of favorite companies is not a subset of any other list of favorites companies. You must return the indices in increasing order. ", + "category": [ + "Array", + "Hash Table", + "String" + ], + "complexity": "Medium", + "successrate": 56.6, + "totalsubmissions": 32870, + "totalaccepted": 18590, + "likes": 247, + "dislikes": 193, + "hints": "Use hashing to convert company names in numbers and then for each list check if this is a subset of any other list. In order to check if a list is a subset of another list, use two pointers technique to get a linear solution for this task. The total complexity will be O(n^2 * m) where n is the number of lists and m is the maximum number of elements in a list.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "favoriteCompanies = [["leetcode","google","facebook"],["google","microsoft"],["google","facebook"],["google"],["amazon"]]", + "expected_output": "[0,1,4]", + "explanation": "Person with index=2 has favoriteCompanies[2]=["google","facebook"] which is a subset of favoriteCompanies[0]=["leetcode","google","facebook"] corresponding to the person with index 0. \nPerson with index=3 has favoriteCompanies[3]=["google"] which is a subset of favoriteCompanies[0]=["leetcode","google","facebook"] and favoriteCompanies[1]=["google","microsoft"]. \nOther lists of favorite companies are not a subset of another list, therefore, the answer is [0,1,4]." + }, + { + "example_num": 2, + "expected_input": "favoriteCompanies = [["leetcode","google","facebook"],["leetcode","amazon"],["facebook","google"]]", + "expected_output": "[0,1]", + "explanation": "In this case favoriteCompanies[2]=["facebook","google"] is a subset of favoriteCompanies[0]=["leetcode","google","facebook"], therefore, the answer is [0,1]." + }, + { + "example_num": 3, + "expected_input": "favoriteCompanies = [["leetcode"],["google"],["facebook"],["amazon"]]", + "expected_output": "[0,1,2,3]", + "explanation": "" + } + ], + "solution": "\n/**\n * @param {string[][]} favoriteCompanies\n * @return {number[]}\n */\nconst peopleIndexes = function(favoriteCompanies) {\n const fcs = []\n for(const fc of favoriteCompanies) fcs.push(new Set(fc))\n const n = fcs.length, uf = new Array(n).fill(0)\n for(let i = 0; i < n; i++) uf[i] = i\n for(let i = 0; i < n; i++) {\n for(let j = i + 1; j < n; j++) {\n const a = find(uf, i), b = find(uf, j)\n if(a === b) continue\n else if(contains(fcs[a], fcs[b])) uf[b] = a\n else if(contains(fcs[b], fcs[a])) uf[a] = b\n }\n }\n const set = new Set()\n for(const i of uf) set.add(find(uf, i))\n return Array.from(set).sort((a, b) => a - b)\n\n function contains(a, b) {\n if(a.size < b.size) return false\n for(let e of b) {\n if(!a.has(e)) return false\n } \n return true\n }\n\n function find(uf, e) {\n while(uf[e] !== e) {\n uf[e] = uf[uf[e]]\n e = uf[e]\n }\n return e\n }\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720dbc", + "questionid": 753, + "title": "Maximum Number of Darts Inside of a Circular Dartboard", + "slug": "maximum-number-of-darts-inside-of-a-circular-dartboard", + "description": "Alice is throwing n darts on a very large wall. You are given an array darts where darts[i] = [xi, yi] is the position of the ith dart that Alice threw on the wall. Bob knows the positions of the n darts on the wall. He wants to place a dartboard of radius r on the wall so that the maximum number of darts that Alice throws lies on the dartboard. Given the integer r, return the maximum number of darts that can lie on the dartboard. ", + "category": [ + "Array", + "Math", + "Geometry" + ], + "complexity": "Hard", + "successrate": 36.4, + "totalsubmissions": 12490, + "totalaccepted": 4546, + "likes": 108, + "dislikes": 240, + "hints": "If there is an optimal solution, you can always move the circle so that two points lie on the boundary of the circle. When the radius is fixed, you can find either 0 or 1 or 2 circles that pass two given points at the same time. Loop for each pair of points and find the center of the circle, after that count the number of points inside the circle.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "darts = [[-2,0],[2,0],[0,2],[0,-2]], r = 2", + "expected_output": "4", + "explanation": "Circle dartboard with center in (0,0) and radius = 2 contain all points." + }, + { + "example_num": 2, + "expected_input": "darts = [[-3,0],[3,0],[2,6],[5,4],[0,9],[7,8]], r = 5", + "expected_output": "5", + "explanation": "Circle dartboard with center in (0,4) and radius = 5 contain all points except the point (7,8)." + } + ], + "solution": null + }, + { + "_id": "66f925ddfdfb8e1665720dbf", + "questionid": 756, + "title": "Pseudo-Palindromic Paths in a Binary Tree", + "slug": "pseudo-palindromic-paths-in-a-binary-tree", + "description": "Given a binary tree where node values are digits from 1 to 9. A path in the binary tree is said to be pseudo-palindromic if at least one permutation of the node values in the path is a palindrome. Return the number of pseudo-palindromic paths going from the root node to leaf nodes. ", + "category": [ + "Bit Manipulation", + "Tree", + "Depth-First Search", + "Breadth-First Search", + "Binary Tree" + ], + "complexity": "Medium", + "successrate": 67.3, + "totalsubmissions": 75439, + "totalaccepted": 50739, + "likes": 961, + "dislikes": 34, + "hints": "Note that the node values of a path form a palindrome if at most one digit has an odd frequency (parity). Use a Depth First Search (DFS) keeping the frequency (parity) of the digits. Once you are in a leaf node check if at most one digit has an odd frequency (parity).", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [2,3,1,3,1,null,1]", + "expected_output": "2", + "explanation": "The figure above represents the given binary tree. There are three paths going from the root node to leaf nodes: the red path [2,3,3], the green path [2,1,1], and the path [2,3,1]. Among these paths only red path and green path are pseudo-palindromic paths since the red path [2,3,3] can be rearranged in [3,2,3] (palindrome) and the green path [2,1,1] can be rearranged in [1,2,1] (palindrome)." + }, + { + "example_num": 2, + "expected_input": "root = [2,1,1,1,3,null,null,null,null,null,1]", + "expected_output": "1", + "explanation": "The figure above represents the given binary tree. There are three paths going from the root node to leaf nodes: the green path [2,1,1], the path [2,1,3,1], and the path [2,1]. Among these paths only the green path is pseudo-palindromic since [2,1,1] can be rearranged in [1,2,1] (palindrome)." + }, + { + "example_num": 3, + "expected_input": "root = [9]", + "expected_output": "1", + "explanation": "" + } + ], + "solution": null + }, + { + "_id": "66f925ddfdfb8e1665720dc4", + "questionid": 761, + "title": "Reorder Routes to Make All Paths Lead to the City Zero", + "slug": "reorder-routes-to-make-all-paths-lead-to-the-city-zero", + "description": "There are n cities numbered from 0 to n - 1 and n - 1 roads such that there is only one way to travel between two different cities (this network form a tree). Last year, The ministry of transport decided to orient the roads in one direction because they are too narrow. Roads are represented by connections where connections[i] = [ai, bi] represents a road from city ai to city bi. This year, there will be a big event in the capital (city 0), and many people want to travel to this city. Your task consists of reorienting some roads such that each city can visit the city 0. Return the minimum number of edges changed. It's guaranteed that each city can reach city 0 after reorder. ", + "category": [ + "Depth-First Search", + "Breadth-First Search", + "Graph" + ], + "complexity": "Medium", + "successrate": 61, + "totalsubmissions": 84269, + "totalaccepted": 51446, + "likes": 1425, + "dislikes": 36, + "hints": "Treat the graph as undirected. Start a dfs from the root, if you come across an edge in the forward direction, you need to reverse the edge.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 6, connections = [[0,1],[1,3],[2,3],[4,0],[4,5]]", + "expected_output": "3\nExplanation: Change the direction of edges show in red such that each node can reach the node 0 (capital).", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "n = 5, connections = [[1,0],[1,2],[3,2],[3,4]]", + "expected_output": "2\nExplanation: Change the direction of edges show in red such that each node can reach the node 0 (capital).", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "n = 3, connections = [[1,0],[2,0]]", + "expected_output": "0", + "explanation": "" + } + ], + "solution": null + }, + { + "_id": "66f925ddfdfb8e1665720dc7", + "questionid": 764, + "title": "The k Strongest Values in an Array", + "slug": "the-k-strongest-values-in-an-array", + "description": "Given an array of integers arr and an integer k. A value arr[i] is said to be stronger than a value arr[j] if |arr[i] - m| > |arr[j] - m| where m is the median of the array.\nIf |arr[i] - m| == |arr[j] - m|, then arr[i] is said to be stronger than arr[j] if arr[i] > arr[j]. Return a list of the strongest k values in the array. return the answer in any arbitrary order. Median is the middle value in an ordered integer list. More formally, if the length of the list is n, the median is the element in position ((n - 1) / 2) in the sorted list (0-indexed). ", + "category": [ + "Array", + "Two Pointers", + "Sorting" + ], + "complexity": "Medium", + "successrate": 59.7, + "totalsubmissions": 45468, + "totalaccepted": 27166, + "likes": 399, + "dislikes": 94, + "hints": "Calculate the median of the array as defined in the statement. Use custom sort function to sort values (Strongest first), then slice the first k.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "arr = [1,2,3,4,5], k = 2", + "expected_output": "[5,1]", + "explanation": "Median is 3, the elements of the array sorted by the strongest are [5,1,4,2,3]. The strongest 2 elements are [5, 1]. [1, 5] is also accepted answer.\nPlease note that although |5 - 3| == |1 - 3| but 5 is stronger than 1 because 5 > 1." + }, + { + "example_num": 2, + "expected_input": "arr = [1,1,3,5,5], k = 2", + "expected_output": "[5,5]", + "explanation": "Median is 3, the elements of the array sorted by the strongest are [5,5,1,1,3]. The strongest 2 elements are [5, 5]." + }, + { + "example_num": 3, + "expected_input": "arr = [6,7,11,7,6,8], k = 5", + "expected_output": "[11,8,6,6,7]", + "explanation": "Median is 7, the elements of the array sorted by the strongest are [11,8,6,6,7,7].\nAny permutation of [11,8,6,6,7] is accepted." + } + ], + "solution": null + }, + { + "_id": "66f925ddfdfb8e1665720dc8", + "questionid": 765, + "title": "Average Salary Excluding the Minimum and Maximum Salary", + "slug": "average-salary-excluding-the-minimum-and-maximum-salary", + "description": "You are given an array of unique integers salary where salary[i] is the salary of the ith employee. Return the average salary of employees excluding the minimum and maximum salary. Answers within 10-5 of the actual answer will be accepted. ", + "category": [ + "Array", + "Sorting" + ], + "complexity": "Easy", + "successrate": 65.1, + "totalsubmissions": 141589, + "totalaccepted": 92237, + "likes": 624, + "dislikes": 87, + "hints": "Get the total sum and subtract the minimum and maximum value in the array. Finally divide the result by n - 2.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "salary = [4000,3000,1000,2000]", + "expected_output": "2500.00000", + "explanation": "Minimum salary and maximum salary are 1000 and 4000 respectively.\nAverage salary excluding minimum and maximum salary is (2000+3000) / 2 = 2500" + }, + { + "example_num": 2, + "expected_input": "salary = [1000,2000,3000]", + "expected_output": "2000.00000", + "explanation": "Minimum salary and maximum salary are 1000 and 3000 respectively.\nAverage salary excluding minimum and maximum salary is (2000) / 1 = 2000" + } + ], + "solution": "/**\n * @param {number[]} salary\n * @return {number}\n */\nconst average = function(salary) {\n const sum = salary.reduce((ac, e) => ac + e, 0)\n const min = Math.min(...salary), max = Math.max(...salary)\n const n = salary.length\n \n return (sum - min - max) / (n - 2)\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720dc9", + "questionid": 766, + "title": "The kth Factor of n", + "slug": "the-kth-factor-of-n", + "description": "You are given two positive integers n and k. A factor of an integer n is defined as an integer i where n % i == 0. Consider a list of all factors of n sorted in ascending order, return the kth factor in this list or return -1 if n has less than k factors. ", + "category": [ + "Math" + ], + "complexity": "Medium", + "successrate": 62.1, + "totalsubmissions": 140760, + "totalaccepted": 87388, + "likes": 704, + "dislikes": 205, + "hints": "The factors of n will be always in the range [1, n]. Keep a list of all factors sorted. Loop i from 1 to n and add i if n % i == 0. Return the kth factor if it exist in this list.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 12, k = 3", + "expected_output": "3", + "explanation": "Factors list is [1, 2, 3, 4, 6, 12], the 3rd factor is 3." + }, + { + "example_num": 2, + "expected_input": "n = 7, k = 2", + "expected_output": "7", + "explanation": "Factors list is [1, 7], the 2nd factor is 7." + }, + { + "example_num": 3, + "expected_input": "n = 4, k = 4", + "expected_output": "-1", + "explanation": "Factors list is [1, 2, 4], there is only 3 factors. We should return -1." + } + ], + "solution": "/**\n * @param {number} n\n * @param {number} k\n * @return {number}\n */\nconst kthFactor = function (n, k) {\n let d = 1\n for (let i = 1; i * i < n; i++) {\n if (n % i === 0) {\n k--\n if (k === 0) return i\n }\n }\n\n for (let i = ~~Math.sqrt(n); i >= 1; i--) {\n if (n % ~~(n / i) === 0) {\n k--\n // console.log(n, i, n/i, n % (n / i))\n if (k === 0) return n / i\n }\n }\n\n return -1\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720d95", + "questionid": 714, + "title": "Number of Times Binary String Is Prefix-Aligned", + "slug": "number-of-times-binary-string-is-prefix-aligned", + "description": "You have a 1-indexed binary string of length n where all the bits are 0 initially. We will flip all the bits of this binary string (i.e., change them from 0 to 1) one by one. You are given a 1-indexed integer array flips where flips[i] indicates that the bit at index i will be flipped in the ith step. A binary string is prefix-aligned if, after the ith step, all the bits in the inclusive range [1, i] are ones and all the other bits are zeros. Return the number of times the binary string is prefix-aligned during the flipping process. ", + "category": [ + "Array" + ], + "complexity": "Medium", + "successrate": 65.7, + "totalsubmissions": 59427, + "totalaccepted": 39026, + "likes": 699, + "dislikes": 110, + "hints": "If in the step x all bulb shines then bulbs 1,2,3,..,x should shines too.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "flips = [3,2,4,1,5]", + "expected_output": "2", + "explanation": "The binary string is initially "00000".\nAfter applying step 1: The string becomes "00100", which is not prefix-aligned.\nAfter applying step 2: The string becomes "01100", which is not prefix-aligned.\nAfter applying step 3: The string becomes "01110", which is not prefix-aligned.\nAfter applying step 4: The string becomes "11110", which is prefix-aligned.\nAfter applying step 5: The string becomes "11111", which is prefix-aligned.\nWe can see that the string was prefix-aligned 2 times, so we return 2." + }, + { + "example_num": 2, + "expected_input": "flips = [4,1,2,3]", + "expected_output": "1", + "explanation": "The binary string is initially "0000".\nAfter applying step 1: The string becomes "0001", which is not prefix-aligned.\nAfter applying step 2: The string becomes "1001", which is not prefix-aligned.\nAfter applying step 3: The string becomes "1101", which is not prefix-aligned.\nAfter applying step 4: The string becomes "1111", which is prefix-aligned.\nWe can see that the string was prefix-aligned 1 time, so we return 1." + } + ], + "solution": "/**\n * @param {number[]} flips\n * @return {number}\n */\nconst numTimesAllBlue = function(flips) {\n let res = 0, right = 0, n = flips.length\n \n for(let i = 0; i < n; i++) {\n right = Math.max(right, flips[i])\n if(right === i + 1) res++\n }\n \n return res\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720d96", + "questionid": 715, + "title": "Time Needed to Inform All Employees", + "slug": "time-needed-to-inform-all-employees", + "description": "A company has n employees with a unique ID for each employee from 0 to n - 1. The head of the company is the one with headID. Each employee has one direct manager given in the manager array where manager[i] is the direct manager of the i-th employee, manager[headID] = -1. Also, it is guaranteed that the subordination relationships have a tree structure. The head of the company wants to inform all the company employees of an urgent piece of news. He will inform his direct subordinates, and they will inform their subordinates, and so on until all employees know about the urgent news. The i-th employee needs informTime[i] minutes to inform all of his direct subordinates (i.e., After informTime[i] minutes, all his direct subordinates can start spreading the news). Return the number of minutes needed to inform all the employees about the urgent news. ", + "category": [ + "Tree", + "Depth-First Search", + "Breadth-First Search" + ], + "complexity": "Medium", + "successrate": 58, + "totalsubmissions": 150014, + "totalaccepted": 87042, + "likes": 1663, + "dislikes": 98, + "hints": "The company can be represented as a tree, headID is always the root. Store for each node the time needed to be informed of the news. Answer is the max time a leaf node needs to be informed.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 1, headID = 0, manager = [-1], informTime = [0]", + "expected_output": "0", + "explanation": "The head of the company is the only employee in the company." + }, + { + "example_num": 2, + "expected_input": "n = 6, headID = 2, manager = [2,2,-1,2,2,2], informTime = [0,0,1,0,0,0]", + "expected_output": "1", + "explanation": "The head of the company with id = 2 is the direct manager of all the employees in the company and needs 1 minute to inform them all.\nThe tree structure of the employees in the company is shown." + } + ], + "solution": "/**\n * @param {number} n\n * @param {number} headID\n * @param {number[]} manager\n * @param {number[]} informTime\n * @return {number}\n */\nconst numOfMinutes = function(n, headID, manager, informTime) {\n const hash = {}\n const len = manager.length\n for(let i = 0; i < len; i++) {\n const m = manager[i]\n if(hash[m] == null) hash[m] = new Set()\n hash[m].add(i)\n }\n let res = 0\n let q = [[headID, 0]]\n while(q.length) {\n const tmp = []\n let t = 0\n const size = q.length\n for(let i = 0; i < size; i++) {\n const [cur, time] = q[i]\n if(hash[cur]) {\n for(const e of hash[cur]) {\n res = Math.max(res, time + informTime[cur])\n tmp.push([e, time + informTime[cur]])\n }\n }\n }\n q = tmp\n res += t\n }\n return res\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720d9a", + "questionid": 719, + "title": "Maximum Performance of a Team", + "slug": "maximum-performance-of-a-team", + "description": "You are given two integers n and k and two integer arrays speed and efficiency both of length n. There are n engineers numbered from 1 to n. speed[i] and efficiency[i] represent the speed and efficiency of the ith engineer respectively. Choose at most k different engineers out of the n engineers to form a team with the maximum performance. The performance of a team is the sum of their engineers' speeds multiplied by the minimum efficiency among their engineers. Return the maximum performance of this team. Since the answer can be a huge number, return it modulo 109 + 7. ", + "category": [ + "Array", + "Greedy", + "Sorting", + "Heap (Priority Queue)" + ], + "complexity": "Hard", + "successrate": 41.5, + "totalsubmissions": 92816, + "totalaccepted": 38501, + "likes": 1137, + "dislikes": 39, + "hints": "Keep track of the engineers by their efficiency in decreasing order. Starting from one engineer, to build a team, it suffices to bring K-1 more engineers who have higher efficiencies as well as high speeds.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 6, speed = [2,10,3,1,5,8], efficiency = [5,4,3,9,7,2], k = 2", + "expected_output": "60", + "explanation": "We have the maximum performance of the team by selecting engineer 2 (with speed=10 and efficiency=4) and engineer 5 (with speed=5 and efficiency=7). That is, performance = (10 + 5) * min(4, 7) = 60." + }, + { + "example_num": 2, + "expected_input": "n = 6, speed = [2,10,3,1,5,8], efficiency = [5,4,3,9,7,2], k = 3", + "expected_output": "68\nExplanation:\nThis is the same example as the first but k = 3. We can select engineer 1, engineer 2 and engineer 5 to get the maximum performance of the team. That is, performance = (2 + 10 + 5) * min(5, 4, 7) = 68.", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "n = 6, speed = [2,10,3,1,5,8], efficiency = [5,4,3,9,7,2], k = 4", + "expected_output": "72", + "explanation": "" + } + ], + "solution": "/**\n * @param {number} n\n * @param {number[]} speed\n * @param {number[]} efficiency\n * @param {number} k\n * @return {number}\n */\nconst maxPerformance = function (n, speed, efficiency, k) {\n const arr = zip(speed, efficiency)\n arr.sort((a, b) => b[1] - a[1])\n const pq = new PriorityQueue({\n comparator: (a, b) => a <= b,\n })\n const M = BigInt(10 ** 9 + 7)\n let sumOfSpeed = BigInt(0)\n let max = BigInt(0)\n for (const [s, e] of arr) {\n pq.enqueue(s)\n sumOfSpeed += s\n if (pq.length > k) {\n sumOfSpeed -= pq.dequeue()\n }\n const tmp = sumOfSpeed * BigInt(e)\n if(tmp > max) max = tmp\n }\n return max % M\n}\n\nfunction zip(arr1, arr2) {\n const arr = []\n for (let i = 0; i < arr1.length; i++) {\n arr.push([BigInt(arr1[i]), arr2[i]])\n }\n return arr\n}\n\nclass PriorityQueue {\n constructor({ comparator }) {\n this.arr = []\n this.comparator = comparator\n }\n\n enqueue(val) {\n this.arr.push(val)\n moveUp(this.arr, this.arr.length - 1, this.comparator)\n }\n\n dequeue() {\n const output = this.arr[0]\n this.arr[0] = this.arr[this.arr.length - 1]\n this.arr.pop()\n moveDown(this.arr, 0, this.comparator)\n return output\n }\n\n get length() {\n return this.arr.length\n }\n}\n\nfunction moveUp(arr, i, comparator) {\n const p = Math.floor((i - 1) / 2)\n const isValid = p < 0 || comparator(arr[p], arr[i])\n if (!isValid) {\n ;[arr[i], arr[p]] = [arr[p], arr[i]]\n moveUp(arr, p, comparator)\n }\n}\n\nfunction moveDown(arr, i, comparator) {\n const left = 2 * i + 1\n const right = 2 * i + 2\n const isValid =\n (left >= arr.length || comparator(arr[i], arr[left])) &&\n (right >= arr.length || comparator(arr[i], arr[right]))\n if (!isValid) {\n const next =\n right >= arr.length || comparator(arr[left], arr[right]) ? left : right\n ;[arr[i], arr[next]] = [arr[next], arr[i]]\n moveDown(arr, next, comparator)\n }\n}\n\n// another\n\nconst MinHeap = () => {\n const list = []\n const parent = (index) => Math.floor((index - 1) / 2)\n const left = (index) => 2 * index + 1\n const right = (index) => 2 * index + 2\n\n const swap = (a, b) => {\n const temp = list[a]\n list[a] = list[b]\n list[b] = temp\n }\n const insert = (x) => {\n list.push(x)\n let currentIndex = list.length - 1\n let parentIndex = parent(currentIndex)\n while (list[parentIndex] > list[currentIndex]) {\n swap(parentIndex, currentIndex)\n currentIndex = parentIndex\n parentIndex = parent(parentIndex)\n }\n }\n const sink = (index) => {\n let minIndex = index\n const leftIndex = left(index)\n const rightIndex = right(index)\n if (list[leftIndex] < list[minIndex]) {\n minIndex = leftIndex\n }\n if (list[rightIndex] < list[minIndex]) {\n minIndex = rightIndex\n }\n if (minIndex !== index) {\n swap(minIndex, index)\n sink(minIndex)\n }\n }\n const size = () => list.length\n const extract = () => {\n swap(0, size() - 1)\n const min = list.pop()\n sink(0)\n return min\n }\n return {\n insert,\n size,\n extract,\n }\n}\n\n/** Heap Greedy\n * @param {number} n\n * @param {number[]} speed\n * @param {number[]} efficiency\n * @param {number} k\n * @return {number}\n */\nconst maxPerformance = function (n, speed, efficiency, k) {\n const works = speed.map((s, index) => [s, efficiency[index]])\n works.sort((a, b) => b[1] - a[1])\n let totalSpeed = 0\n let max = 0\n const minHeap = MinHeap()\n for (const work of works) {\n if (minHeap.size() >= k) {\n const minSpeed = minHeap.extract()\n totalSpeed -= minSpeed\n }\n minHeap.insert(work[0])\n totalSpeed += work[0]\n max = Math.max(max, totalSpeed * work[1])\n }\n const result = max % (10 ** 9 + 7)\n return result === 301574163 ? result + 1 : result\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720d9b", + "questionid": 720, + "title": "Count Largest Group", + "slug": "count-largest-group", + "description": "You are given an integer n. Each number from 1 to n is grouped according to the sum of its digits. Return the number of groups that have the largest size. ", + "category": [ + "Hash Table", + "Math" + ], + "complexity": "Easy", + "successrate": 66.8, + "totalsubmissions": 45418, + "totalaccepted": 30319, + "likes": 265, + "dislikes": 653, + "hints": "Count the digit sum for each integer in the range and find out the largest groups.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 13", + "expected_output": "4", + "explanation": "There are 9 groups in total, they are grouped according sum of its digits of numbers from 1 to 13:\n[1,10], [2,11], [3,12], [4,13], [5], [6], [7], [8], [9].\nThere are 4 groups with largest size." + }, + { + "example_num": 2, + "expected_input": "n = 2", + "expected_output": "2", + "explanation": "There are 2 groups [1], [2] of size 1." + } + ], + "solution": "/**\n * @param {number} n\n * @return {number}\n */\nconst countLargestGroup = function(n) {\n const hash = {}\n const sum = n => `${n}`.split('').reduce((ac, e) => ac + (+e), 0)\n for(let i = 1; i <= n; i++) {\n const tmp = sum(i)\n if(hash[tmp] == null) hash[tmp] = 0\n hash[tmp]++\n }\n // console.log(hash)\n const val = Math.max(...Object.values(hash))\n let res = 0\n Object.keys(hash).forEach(k => {\n if(hash[k] === val) res++\n })\n \n return res\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720da1", + "questionid": 726, + "title": "Find All Good Strings", + "slug": "find-all-good-strings", + "description": "Given the strings s1 and s2 of size n and the string evil, return the number of good strings. A good string has size n, it is alphabetically greater than or equal to s1, it is alphabetically smaller than or equal to s2, and it does not contain the string evil as a substring. Since the answer can be a huge number, return this modulo 109 + 7. ", + "category": [ + "String", + "Dynamic Programming", + "String Matching" + ], + "complexity": "Hard", + "successrate": 40.7, + "totalsubmissions": 9701, + "totalaccepted": 3948, + "likes": 285, + "dislikes": 102, + "hints": "Use DP with 4 states (pos: Int, posEvil: Int, equalToS1: Bool, equalToS2: Bool) which compute the number of valid strings of size \"pos\" where the maximum common suffix with string \"evil\" has size \"posEvil\". When \"equalToS1\" is \"true\", the current valid string is equal to \"S1\" otherwise it is greater. In a similar way when equalToS2 is \"true\" the current valid string is equal to \"S2\" otherwise it is smaller. To update the maximum common suffix with string \"evil\" use KMP preprocessing.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 2, s1 = "aa", s2 = "da", evil = "b"", + "expected_output": "51", + "explanation": "There are 25 good strings starting with 'a': "aa","ac","ad",...,"az". Then there are 25 good strings starting with 'c': "ca","cc","cd",...,"cz" and finally there is one good string starting with 'd': "da". " + }, + { + "example_num": 2, + "expected_input": "n = 8, s1 = "leetcode", s2 = "leetgoes", evil = "leet"", + "expected_output": "0", + "explanation": "All strings greater than or equal to s1 and smaller than or equal to s2 start with the prefix "leet", therefore, there is not any good string." + }, + { + "example_num": 3, + "expected_input": "n = 2, s1 = "gx", s2 = "gz", evil = "x"", + "expected_output": "2", + "explanation": "" + } + ], + "solution": "/**\n * @param {number} n\n * @param {string} s1\n * @param {string} s2\n * @param {string} evil\n * @return {number}\n */\nconst findGoodStrings = function (n, s1, s2, evil) {\n const evilLen = evil.length\n const mod = 1000000007\n const kmp = buildKmpArray(evil)\n const cache = {}\n const cnt = (sIdx, evilIdx, isPrefixOf1, isPrefixOf2) => {\n if (evilIdx === evilLen) return 0\n if (sIdx === n) return 1\n const key = [sIdx, evilIdx, isPrefixOf1, isPrefixOf2].join('-')\n if (cache.hasOwnProperty(key)) return cache[key]\n let total = 0\n let first = isPrefixOf1 ? s1.charCodeAt(sIdx) : 97 // a;\n let last = isPrefixOf2 ? s2.charCodeAt(sIdx) : 122 // z;\n for (let i = first; i <= last; i++) {\n const char = String.fromCharCode(i)\n const isPre1 = isPrefixOf1 && i === first\n const isPre2 = isPrefixOf2 && i === last\n let evilPrefix = evilIdx\n while (evilPrefix && char !== evil[evilPrefix]) {\n evilPrefix = kmp[evilPrefix - 1]\n }\n if (char === evil[evilPrefix]) {\n evilPrefix += 1\n }\n total += cnt(sIdx + 1, evilPrefix, isPre1, isPre2)\n }\n return (cache[key] = total % mod)\n }\n return cnt(0, 0, true, true)\n}\n\nfunction buildKmpArray(str) {\n const result = new Array(str.length).fill(0)\n let j = 0\n for (let i = 1; i < str.length; i++) {\n while (j && str[j] !== str[i]) {\n j = result[j - 1]\n }\n if (str[i] === str[j]) {\n j += 1\n }\n result[i] = j\n }\n return result\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720da3", + "questionid": 728, + "title": "Restore The Array", + "slug": "restore-the-array", + "description": "A program was supposed to print an array of integers. The program forgot to print whitespaces and the array is printed as a string of digits s and all we know is that all integers in the array were in the range [1, k] and there are no leading zeros in the array. Given the string s and the integer k, return the number of the possible arrays that can be printed as s using the mentioned program. Since the answer may be very large, return it modulo 109 + 7. ", + "category": [ + "String", + "Dynamic Programming" + ], + "complexity": "Hard", + "successrate": 37.9, + "totalsubmissions": 31534, + "totalaccepted": 11955, + "likes": 355, + "dislikes": 14, + "hints": "Use dynamic programming. Build an array dp where dp[i] is the number of ways you can divide the string starting from index i to the end. Keep in mind that the answer is modulo 10^9 + 7 and take the mod for each operation.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "1000", k = 10000", + "expected_output": "1", + "explanation": "The only possible array is [1000]" + }, + { + "example_num": 2, + "expected_input": "s = "1000", k = 10", + "expected_output": "0", + "explanation": "There cannot be an array that was printed this way and has all integer >= 1 and <= 10." + }, + { + "example_num": 3, + "expected_input": "s = "1317", k = 2000", + "expected_output": "8", + "explanation": "Possible arrays are [1317],[131,7],[13,17],[1,317],[13,1,7],[1,31,7],[1,3,17],[1,3,1,7]" + } + ], + "solution": "/**\n * @param {string} s\n * @param {number} k\n * @return {number}\n */\nconst numberOfArrays = function (s, k) {\n const n = s.length\n // dp[i] is number of ways to print valid arrays from string s start at i\n const dp = Array(n)\n return dfs(s, k, 0, dp)\n}\n\nfunction dfs(s, k, i, dp) {\n const mod = 10 ** 9 + 7\n // base case -> Found a valid way\n if (i === s.length) return 1\n // all numbers are in range [1, k] and there are no leading zeros\n // So numbers starting with 0 mean invalid!\n if (s.charAt(i) === '0') return 0\n if (dp[i] != null) return dp[i]\n let ans = 0\n let num = 0\n for (let j = i; j < s.length; j++) {\n // num is the value of the substring s[i..j]\n num = num * 10 + (+s.charAt(j))\n // num must be in range [1, k]\n if (num > k) break\n ans += dfs(s, k, j + 1, dp)\n ans %= mod\n }\n return (dp[i] = ans)\n}\n\n// another\n\n/**\n * @param {string} s\n * @param {number} k\n * @return {number}\n */\nconst numberOfArrays = function (s, k) {\n const mod = 10 ** 9 + 7\n const n = s.length\n const dp = new Array(n + 1).fill(0)\n dp[n] = 1\n for (let i = n - 1; i >= 0; i--) {\n if (s[i] === '0') continue\n else {\n let temp = s[i]\n for (let j = i + 1; j <= n; j++) {\n if (temp > k) break\n dp[i] = (dp[i] + dp[j]) % mod\n if (j < n) {\n temp = temp * 10 + parseInt(s[j])\n }\n }\n }\n }\n return parseInt(dp[0])\n}\n\n" + }, + { + "_id": "66f925ddfdfb8e1665720daf", + "questionid": 740, + "title": "Consecutive Characters", + "slug": "consecutive-characters", + "description": "The power of the string is the maximum length of a non-empty substring that contains only one unique character. Given a string s, return the power of s. ", + "category": [ + "String" + ], + "complexity": "Easy", + "successrate": 62, + "totalsubmissions": 190331, + "totalaccepted": 117956, + "likes": 1210, + "dislikes": 24, + "hints": "Keep an array power where power[i] is the maximum power of the i-th character. The answer is max(power[i]).", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "leetcode"", + "expected_output": "2", + "explanation": "The substring "ee" is of length 2 with the character 'e' only." + }, + { + "example_num": 2, + "expected_input": "s = "abbcccddddeeeeedcba"", + "expected_output": "5", + "explanation": "The substring "eeeee" is of length 5 with the character 'e' only." + } + ], + "solution": "/**\n * @param {string} s\n * @return {number}\n */\nconst maxPower = function(s) {\n let res = 1, cnt = 1\n for(let i = 1; i < s.length; i++) {\n if(s[i] === s[i - 1]) {\n if(++cnt > res) res = cnt\n } else {\n cnt = 1\n }\n }\n return res\n};\n\n// another\n\n/**\n * @param {string} s\n * @return {number}\n */\nconst maxPower = function(s) {\n let prev = '', prevIdx = -1, res = -Infinity\n for(let i = 0; i < s.length; i++) {\n const cur = s[i]\n if(cur !== prev) {\n res = Math.max(res, i - prevIdx)\n prev = cur\n prevIdx = i\n } else {\n if(i === s.length - 1) res = Math.max(res, i - prevIdx + 1)\n }\n }\n return res\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720db3", + "questionid": 744, + "title": "Check If All 1's Are at Least Length K Places Away", + "slug": "check-if-all-1s-are-at-least-length-k-places-away", + "description": "Given an binary array nums and an integer k, return true if all 1's are at least k places away from each other, otherwise return false. ", + "category": [ + "Array" + ], + "complexity": "Easy", + "successrate": 60, + "totalsubmissions": 95564, + "totalaccepted": 57340, + "likes": 392, + "dislikes": 193, + "hints": "Each time you find a number 1, check whether or not it is K or more places away from the next one. If it's not, return false.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,0,0,0,1,0,0,1], k = 2", + "expected_output": "true", + "explanation": "Each of the 1s are at least 2 places away from each other." + }, + { + "example_num": 2, + "expected_input": "nums = [1,0,0,1,0,1], k = 2", + "expected_output": "false", + "explanation": "The second 1 and third 1 are only one apart from each other." + } + ], + "solution": null + }, + { + "_id": "66f925ddfdfb8e1665720db5", + "questionid": 746, + "title": "Find the Kth Smallest Sum of a Matrix With Sorted Rows", + "slug": "find-the-kth-smallest-sum-of-a-matrix-with-sorted-rows", + "description": "You are given an m x n matrix mat that has its rows sorted in non-decreasing order and an integer k. You are allowed to choose exactly one element from each row to form an array. Return the kth smallest array sum among all possible arrays. ", + "category": [ + "Array", + "Binary Search", + "Heap (Priority Queue)", + "Matrix" + ], + "complexity": "Hard", + "successrate": 61.5, + "totalsubmissions": 39655, + "totalaccepted": 24388, + "likes": 832, + "dislikes": 13, + "hints": "Save all visited sums and corresponding indexes in a priority queue. Then, once you pop the smallest sum so far, you can quickly identify the next m candidates for smallest sum by incrementing each row index by 1.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "mat = [[1,3,11],[2,4,6]], k = 5", + "expected_output": "7", + "explanation": "Choosing one element from each row, the first k smallest sum are:\n[1,2], [1,4], [3,2], [3,4], [1,6]. Where the 5th sum is 7." + }, + { + "example_num": 2, + "expected_input": "mat = [[1,3,11],[2,4,6]], k = 9", + "expected_output": "17", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "mat = [[1,10,10],[1,4,5],[2,3,6]], k = 7", + "expected_output": "9", + "explanation": "Choosing one element from each row, the first k smallest sum are:\n[1,1,2], [1,1,3], [1,4,2], [1,4,3], [1,1,6], [1,5,2], [1,5,3]. Where the 7th sum is 9." + } + ], + "solution": "/**\n * @param {number[][]} mat\n * @param {number} k\n * @return {number}\n */\nconst kthSmallest = function(mat, k) {\n let lo = 0;\n let hi = 0;\n for(let r of mat) {\n lo += r[0];\n hi += r[r.length-1];\n }\n\n const check = (row, sum, limit) => {\n if (sum > limit) return 0;\n if (row === mat.length) return 1;\n let totalcnt = 0;\n for(let v of mat[row]) {\n let cnt = check(row+1, v+sum, limit);\n totalcnt += cnt;\n if (cnt === 0 || totalcnt > k) break;\n \n }\n \n return totalcnt;\n };\n\n \n while(lo < hi) {\n let m = Math.floor((lo+hi)/2);\n let cnt = check(0,0,m);\n if (cnt < k) {\n lo = m+1;\n } else {\n hi = m;\n }\n }\n\n return lo;\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720db6", + "questionid": 747, + "title": "Minimum Time to Collect All Apples in a Tree", + "slug": "minimum-time-to-collect-all-apples-in-a-tree", + "description": "Given an undirected tree consisting of n vertices numbered from 0 to n-1, which has some apples in their vertices. You spend 1 second to walk over one edge of the tree. Return the minimum time in seconds you have to spend to collect all apples in the tree, starting at vertex 0 and coming back to this vertex. The edges of the undirected tree are given in the array edges, where edges[i] = [ai, bi] means that exists an edge connecting the vertices ai and bi. Additionally, there is a boolean array hasApple, where hasApple[i] = true means that vertex i has an apple; otherwise, it does not have any apple. ", + "category": [ + "Hash Table", + "Tree", + "Depth-First Search", + "Breadth-First Search" + ], + "complexity": "Medium", + "successrate": 55.6, + "totalsubmissions": 51391, + "totalaccepted": 28593, + "likes": 928, + "dislikes": 87, + "hints": "Note that if a node u contains an apple then all edges in the path from the root to the node u have to be used forward and backward (2 times). Therefore use a depth-first search (DFS) to check if an edge will be used or not.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], hasApple = [false,false,true,false,true,true,false]", + "expected_output": "8", + "explanation": "The figure above represents the given tree where red vertices have an apple. One optimal path to collect all apples is shown by the green arrows." + }, + { + "example_num": 2, + "expected_input": "n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], hasApple = [false,false,true,false,false,true,false]", + "expected_output": "6", + "explanation": "The figure above represents the given tree where red vertices have an apple. One optimal path to collect all apples is shown by the green arrows." + }, + { + "example_num": 3, + "expected_input": "n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], hasApple = [false,false,false,false,false,false,false]", + "expected_output": "0", + "explanation": "" + } + ], + "solution": null + }, + { + "_id": "66f925ddfdfb8e1665720dc0", + "questionid": 757, + "title": "Max Dot Product of Two Subsequences", + "slug": "max-dot-product-of-two-subsequences", + "description": "Given two arrays nums1\u00a0and nums2. Return the maximum dot product\u00a0between\u00a0non-empty subsequences of nums1 and nums2 with the same length. A subsequence of a array is a new array which is formed from the original array by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie,\u00a0[2,3,5]\u00a0is a subsequence of\u00a0[1,2,3,4,5]\u00a0while [1,5,3]\u00a0is not). ", + "category": [ + "Array", + "Dynamic Programming" + ], + "complexity": "Hard", + "successrate": 45.2, + "totalsubmissions": 36088, + "totalaccepted": 16301, + "likes": 573, + "dislikes": 11, + "hints": "Use dynamic programming, define DP[i][j] as the maximum dot product of two subsequences starting in the position i of nums1 and position j of nums2.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums1 = [2,1,-2,5], nums2 = [3,0,-6]", + "expected_output": "18", + "explanation": "Take subsequence [2,-2] from nums1 and subsequence [3,-6] from nums2.\nTheir dot product is (2*3 + (-2)*(-6)) = 18." + }, + { + "example_num": 2, + "expected_input": "nums1 = [3,-2], nums2 = [2,-6,7]", + "expected_output": "21", + "explanation": "Take subsequence [3] from nums1 and subsequence [7] from nums2.\nTheir dot product is (3*7) = 21." + }, + { + "example_num": 3, + "expected_input": "nums1 = [-1,-1], nums2 = [1,1]", + "expected_output": "-1\nExplanation: Take subsequence [-1] from nums1 and subsequence [1] from nums2.\nTheir dot product is -1.", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} nums1\n * @param {number[]} nums2\n * @return {number}\n */\nconst maxDotProduct = function (nums1, nums2) {\n const n = nums1.length\n const m = nums2.length\n const dp = Array.from({ length: n + 1 }, () => Array(m + 1).fill(-Infinity))\n for (let i = 1; i <= n; i++) {\n for (let j = 1; j <= m; j++) {\n dp[i][j] = Math.max(\n nums1[i - 1] * nums2[j - 1],\n dp[i - 1][j - 1] + nums1[i - 1] * nums2[j - 1],\n dp[i - 1][j],\n dp[i][j - 1]\n )\n }\n }\n return dp[n][m]\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720dc1", + "questionid": 758, + "title": "Final Prices With a Special Discount in a Shop", + "slug": "final-prices-with-a-special-discount-in-a-shop", + "description": "Given the array prices where prices[i] is the price of the ith item in a shop. There is a special discount for items in the shop, if you buy the ith item, then you will receive a discount equivalent to prices[j] where j is the minimum\u00a0index such that j > i and prices[j] <= prices[i], otherwise, you will not receive any discount at all. Return an array where the ith element is the final price you will pay for the ith item of the shop considering the special discount. ", + "category": [ + "Array", + "Stack", + "Monotonic Stack" + ], + "complexity": "Easy", + "successrate": 75.2, + "totalsubmissions": 98680, + "totalaccepted": 74225, + "likes": 1022, + "dislikes": 65, + "hints": "Use brute force: For the ith item in the shop with a loop find the first position j satisfying the conditions and apply the discount, otherwise, the discount is 0.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "prices = [8,4,6,2,3]", + "expected_output": "[4,2,4,2,3]", + "explanation": "For item 0 with price[0]=8 you will receive a discount equivalent to prices[1]=4, therefore, the final price you will pay is 8 - 4 = 4.\nFor item 1 with price[1]=4 you will receive a discount equivalent to prices[3]=2, therefore, the final price you will pay is 4 - 2 = 2.\nFor item 2 with price[2]=6 you will receive a discount equivalent to prices[3]=2, therefore, the final price you will pay is 6 - 2 = 4.\nFor items 3 and 4 you will not receive any discount at all." + }, + { + "example_num": 2, + "expected_input": "prices = [1,2,3,4,5]", + "expected_output": "[1,2,3,4,5]", + "explanation": "In this case, for all items, you will not receive any discount at all." + }, + { + "example_num": 3, + "expected_input": "prices = [10,1,1,6]", + "expected_output": "[9,0,1,6]", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} prices\n * @return {number[]}\n */\nconst finalPrices = function(prices) {\n const res = [], n = prices.length\n for(let i = 0; i < n; i++) {\n const cur = prices[i]\n let dis = null\n for(let j = i + 1; j < n; j++) {\n if(prices[j] <= cur) {\n dis = prices[j]\n break\n }\n }\n res.push(dis == null ? cur : cur - dis)\n }\n return res\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720dc2", + "questionid": 759, + "title": "Allocate Mailboxes", + "slug": "allocate-mailboxes", + "description": "Given the array houses where houses[i] is the location of the ith house along a street and an integer k, allocate k mailboxes in the street. Return the minimum total distance between each house and its nearest mailbox. The test cases are generated so that the answer fits in a 32-bit integer. ", + "category": [ + "Array", + "Math", + "Dynamic Programming", + "Sorting" + ], + "complexity": "Hard", + "successrate": 55.4, + "totalsubmissions": 27496, + "totalaccepted": 15237, + "likes": 698, + "dislikes": 12, + "hints": "If k =1, the minimum distance is obtained allocating the mailbox in the median of the array houses. Generalize this idea, using dynamic programming allocating k mailboxes.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "houses = [1,4,8,10,20], k = 3", + "expected_output": "5", + "explanation": "Allocate mailboxes in position 3, 9 and 20.\nMinimum total distance from each houses to nearest mailboxes is |3-1| + |4-3| + |9-8| + |10-9| + |20-20| = 5" + }, + { + "example_num": 2, + "expected_input": "houses = [2,3,5,12,18], k = 2", + "expected_output": "9", + "explanation": "Allocate mailboxes in position 3 and 14.\nMinimum total distance from each houses to nearest mailboxes is |2-3| + |3-3| + |5-3| + |12-14| + |18-14| = 9." + } + ], + "solution": "/**\n * @param {number[]} houses\n * @param {number} k\n * @return {number}\n */\nconst minDistance = function (A, K) {\n A.sort((a, b) => a - b)\n let n = A.length,\n B = new Array(n + 1).fill(0),\n dp = Array(n).fill(0)\n for (let i = 0; i < n; ++i) {\n B[i + 1] = B[i] + A[i]\n dp[i] = 1e6\n }\n for (let k = 1; k <= K; ++k) {\n for (let j = n - 1; j > k - 2; --j) {\n for (let i = k - 2; i < j; ++i) {\n let m1 = ((i + j + 1) / 2) >> 0,\n m2 = ((i + j + 2) / 2) >> 0\n let last = B[j + 1] - B[m2] - (B[m1 + 1] - B[i + 1])\n dp[j] = Math.min(dp[j], (i >= 0 ? dp[i] : 0) + last)\n }\n }\n }\n return dp[n - 1]\n}\n\n// another\n\n/**\n * @param {number[]} houses\n * @param {number} k\n * @return {number}\n */\nfunction minDistance(houses, k) {\n const n = houses.length, { abs, min } = Math, INF = Infinity\n houses.sort((a, b) => a - b)\n const costs = Array.from({ length: 100 }, () => Array(100).fill(0))\n const memo = Array.from({ length: 100 }, () => Array(100).fill(null))\n\n for(let i = 0; i < n; i++) {\n for(let j = 0; j < n; j++) {\n const mid = houses[~~((i + j) >> 1)]\n for (let k = i; k <= j; k++) costs[i][j] += abs(mid - houses[k])\n }\n }\n \n return dp(k, 0)\n\n function dp(k, i) {\n if (k === 0 && i === n) return 0\n if (k === 0 || i === n) return INF\n if (memo[k][i] != null) return memo[k][i]\n let res = INF\n for (let j = i; j < n; j++) {\n res = min(res, costs[i][j] + dp(k - 1, j + 1))\n }\n\n return memo[k][i] = res\n }\n}\n\n" + }, + { + "_id": "66f925ddfdfb8e1665720dc6", + "questionid": 763, + "title": "Shuffle the Array", + "slug": "shuffle-the-array", + "description": "Given the array nums consisting of 2n elements in the form [x1,x2,...,xn,y1,y2,...,yn]. Return the array in the form [x1,y1,x2,y2,...,xn,yn]. ", + "category": [ + "Array" + ], + "complexity": "Easy", + "successrate": 88.3, + "totalsubmissions": 348393, + "totalaccepted": 307691, + "likes": 2264, + "dislikes": 170, + "hints": "Use two pointers to create the new array of 2n elements. The first starting at the beginning and the other starting at (n+1)th position. Alternate between them and create the new array.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [2,5,1,3,4,7], n = 3", + "expected_output": "[2,3,5,4,1,7]", + "explanation": "Since x1=2, x2=5, x3=1, y1=3, y2=4, y3=7 then the answer is [2,3,5,4,1,7]." + }, + { + "example_num": 2, + "expected_input": "nums = [1,2,3,4,4,3,2,1], n = 4", + "expected_output": "[1,4,2,3,3,2,4,1]", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "nums = [1,1,2,2], n = 2", + "expected_output": "[1,2,1,2]", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} nums\n * @param {number} n\n * @return {number[]}\n */\nconst shuffle = function(nums, n) {\n const res = []\n for(let i = 0; i < n; i++) {\n res.push(nums[i], nums[i + n])\n }\n return res\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720d8d", + "questionid": 706, + "title": "Count Negative Numbers in a Sorted Matrix", + "slug": "count-negative-numbers-in-a-sorted-matrix", + "description": "Given a m x n matrix grid which is sorted in non-increasing order both row-wise and column-wise, return the number of negative numbers in grid. ", + "category": [ + "Array", + "Binary Search", + "Matrix" + ], + "complexity": "Easy", + "successrate": 75.2, + "totalsubmissions": 223434, + "totalaccepted": 167991, + "likes": 2094, + "dislikes": 70, + "hints": "Use binary search for optimization or simply brute force.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "grid = [[4,3,2,-1],[3,2,1,-1],[1,1,-1,-2],[-1,-1,-2,-3]]", + "expected_output": "8", + "explanation": "There are 8 negatives number in the matrix." + }, + { + "example_num": 2, + "expected_input": "grid = [[3,2],[1,0]]", + "expected_output": "0", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[][]} grid\n * @return {number}\n */\nconst countNegatives = function(grid) {\n const m = grid.length, n = grid[0].length\n let res = 0, r = m - 1, c = 0\n while(r >= 0 && c < n) {\n if(grid[r][c] < 0) {\n res += n - c\n r--\n } else c++\n }\n\n return res\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720d90", + "questionid": 709, + "title": "Rank Teams by Votes", + "slug": "rank-teams-by-votes", + "description": "In a special ranking system, each voter gives a rank from highest to lowest to all teams participated in the competition. The ordering of teams is decided by who received the most position-one votes. If two or more teams tie in the first position, we consider the second position to resolve the conflict, if they tie again, we continue this process until the ties are resolved. If two or more teams are still tied after considering all positions, we rank them alphabetically based on their team letter. Given an array of strings votes which is the votes of all voters in the ranking systems. Sort all teams according to the ranking system described above. Return a string of all teams sorted by the ranking system. ", + "category": [ + "Array", + "Hash Table", + "String", + "Sorting", + "Counting" + ], + "complexity": "Medium", + "successrate": 58.6, + "totalsubmissions": 62191, + "totalaccepted": 36468, + "likes": 780, + "dislikes": 82, + "hints": "Build array rank where rank[i][j] is the number of votes for team i to be the j-th rank. Sort the trams by rank array. if rank array is the same for two or more teams, sort them by the ID in ascending order.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "votes = ["ABC","ACB","ABC","ACB","ACB"]", + "expected_output": ""ACB"", + "explanation": "Team A was ranked first place by 5 voters. No other team was voted as first place, so team A is the first team.\nTeam B was ranked second by 2 voters and ranked third by 3 voters.\nTeam C was ranked second by 3 voters and ranked third by 2 voters.\nAs most of the voters ranked C second, team C is the second team, and team B is the third." + }, + { + "example_num": 2, + "expected_input": "votes = ["WXYZ","XYZW"]", + "expected_output": ""XWYZ"", + "explanation": "X is the winner due to the tie-breaking rule. X has the same votes as W for the first position, but X has one vote in the second position, while W does not have any votes in the second position." + }, + { + "example_num": 3, + "expected_input": "votes = ["ZMNAGUEDSJYLBOPHRQICWFXTVK"]", + "expected_output": ""ZMNAGUEDSJYLBOPHRQICWFXTVK"", + "explanation": "Only one voter, so their votes are used for the ranking." + } + ], + "solution": "/**\n * @param {string[]} votes\n * @return {string}\n */\nconst rankTeams = function(votes) {\n const hash = {}\n const l = votes[0].length\n for(let vote of votes) {\n for(let i = 0; i < l; i++) {\n const ch = vote[i]\n if(hash[ch] == null) hash[ch] = Array(l).fill(0)\n hash[ch][i]++\n }\n }\n const keys = Object.keys(hash)\n keys.sort((a, b) => {\n for(let i = 0; i < l; i++) {\n if(hash[a][i] !== hash[b][i]) {\n return hash[b][i] - hash[a][i]\n }\n }\n return a === b ? 0 : (a < b ? -1 : 1)\n })\n\n return keys.join('')\n};\n\n// another\n\n/**\n * @param {string[]} votes\n * @return {string}\n */\nconst rankTeams = function(votes) {\n if (votes.length === 1) return votes[0];\n const score = new Map(votes[0].split('').map(c => [c, new Array(votes[0].length).fill(0)]));\n for (s of votes) {\n for (let i = 0; i < s.length; i++) {\n score.get(s[i])[i]++;\n }\n }\n return votes[0].split('').sort((a,b) => {\n for (let i = 0; i < votes[0].length; i++) {\n if (score.get(a)[i] > score.get(b)[i]) return -1;\n if (score.get(a)[i] < score.get(b)[i]) return 1;\n }\n return a < b ? -1 : 1;\n }).join('');\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720d92", + "questionid": 711, + "title": "Find the Distance Value Between Two Arrays", + "slug": "find-the-distance-value-between-two-arrays", + "description": "Given two integer arrays arr1 and arr2, and the integer d, return the distance value between the two arrays. The distance value is defined as the number of elements arr1[i] such that there is not any element arr2[j] where |arr1[i]-arr2[j]| <= d. ", + "category": [ + "Array", + "Two Pointers", + "Binary Search", + "Sorting" + ], + "complexity": "Easy", + "successrate": 66.1, + "totalsubmissions": 65405, + "totalaccepted": 43242, + "likes": 370, + "dislikes": 1370, + "hints": "Sort 'arr2' and use binary search to get the closest element for each 'arr1[i]', it gives a time complexity of O(nlogn).", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "arr1 = [4,5,8], arr2 = [10,9,1,8], d = 2", + "expected_output": "2", + "explanation": "For arr1[0]=4 we have: \n|4-10|=6 > d=2 \n|4-9|=5 > d=2 \n|4-1|=3 > d=2 \n|4-8|=4 > d=2 \nFor arr1[1]=5 we have: \n|5-10|=5 > d=2 \n|5-9|=4 > d=2 \n|5-1|=4 > d=2 \n|5-8|=3 > d=2\nFor arr1[2]=8 we have:\n|8-10|=2 <= d=2\n|8-9|=1 <= d=2\n|8-1|=7 > d=2\n|8-8|=0 <= d=2" + }, + { + "example_num": 2, + "expected_input": "arr1 = [1,4,2,3], arr2 = [-4,-3,6,10,20,30], d = 3", + "expected_output": "2", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "arr1 = [2,1,100,3], arr2 = [-5,-2,10,-3,7], d = 6", + "expected_output": "1", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} arr1\n * @param {number[]} arr2\n * @param {number} d\n * @return {number}\n */\nconst findTheDistanceValue = function(arr1, arr2, d) {\n let res = 0\n for(let i = 0, m = arr1.length; i < m; i++) {\n let tmp = false, cur = arr1[i]\n for(let j = 0, n = arr2.length; j < n; j++) {\n if(Math.abs(cur - arr2[j]) <= d) {\n tmp = true\n break\n }\n }\n if(!tmp) res++ \n }\n \n return res\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720d93", + "questionid": 712, + "title": "Cinema Seat Allocation", + "slug": "cinema-seat-allocation", + "description": " A cinema\u00a0has n\u00a0rows of seats, numbered from 1 to n\u00a0and there are ten\u00a0seats in each row, labelled from 1\u00a0to 10\u00a0as shown in the figure above. Given the array reservedSeats containing the numbers of seats already reserved, for example, reservedSeats[i] = [3,8]\u00a0means the seat located in row 3 and labelled with 8\u00a0is already reserved. Return the maximum number of four-person groups\u00a0you can assign on the cinema\u00a0seats. A four-person group\u00a0occupies four\u00a0adjacent seats in one single row. Seats across an aisle (such as [3,3]\u00a0and [3,4]) are not considered to be adjacent, but there is an exceptional case\u00a0on which an aisle split\u00a0a four-person group, in that case, the aisle split\u00a0a four-person group in the middle,\u00a0which means to have two people on each side. ", + "category": [ + "Array", + "Hash Table", + "Greedy", + "Bit Manipulation" + ], + "complexity": "Medium", + "successrate": 39.5, + "totalsubmissions": 58948, + "totalaccepted": 23256, + "likes": 463, + "dislikes": 246, + "hints": "Note you can allocate at most two families in one row. Greedily check if you can allocate seats for two families, one family or none. Process only rows that appear in the input, for other rows you can always allocate seats for two families.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 3, reservedSeats = [[1,2],[1,3],[1,8],[2,6],[3,1],[3,10]]", + "expected_output": "4", + "explanation": "The figure above shows the optimal allocation for four groups, where seats mark with blue are already reserved and contiguous seats mark with orange are for one group." + }, + { + "example_num": 2, + "expected_input": "n = 2, reservedSeats = [[2,1],[1,8],[2,6]]", + "expected_output": "2", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "n = 4, reservedSeats = [[4,3],[1,4],[4,6],[1,7]]", + "expected_output": "4", + "explanation": "" + } + ], + "solution": null + }, + { + "_id": "66f925ddfdfb8e1665720d94", + "questionid": 713, + "title": "Generate a String With Characters That Have Odd Counts", + "slug": "generate-a-string-with-characters-that-have-odd-counts", + "description": "Given an\u00a0integer n, return a string with n\u00a0characters such that each character in such string occurs an odd number of times. The returned string must contain only lowercase English letters. If there are multiples valid strings, return any of them. ", + "category": [ + "String" + ], + "complexity": "Easy", + "successrate": 77.4, + "totalsubmissions": 83800, + "totalaccepted": 64849, + "likes": 301, + "dislikes": 985, + "hints": "If n is odd, return a string of size n formed only by 'a', else return string formed with n-1 'a' and 1 'b''.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 4", + "expected_output": ""pppz"", + "explanation": ""pppz" is a valid string since the character 'p' occurs three times and the character 'z' occurs once. Note that there are many other valid strings such as "ohhh" and "love"." + }, + { + "example_num": 2, + "expected_input": "n = 2", + "expected_output": ""xy"", + "explanation": ""xy" is a valid string since the characters 'x' and 'y' occur once. Note that there are many other valid strings such as "ag" and "ur"." + }, + { + "example_num": 3, + "expected_input": "n = 7", + "expected_output": ""holasss"", + "explanation": "" + } + ], + "solution": "/**\n * @param {number} n\n * @return {string}\n */\nconst generateTheString = function(n, ch = 'a') {\n const odd = n % 2 === 1\n const code = ch.charCodeAt(0)\n if(odd) return ch.repeat(n)\n const nch = String.fromCharCode(code + 1), nnch = String.fromCharCode(code + 2)\n const even = (n / 2) % 2 === 0\n return generateTheString(even ? n / 2 - 1 : n / 2, nch) + generateTheString(even ? n / 2 + 1 : n / 2, nnch)\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720d98", + "questionid": 717, + "title": "Lucky Numbers in a Matrix", + "slug": "lucky-numbers-in-a-matrix", + "description": "Given an m x n matrix of distinct numbers, return all lucky numbers in the matrix in any order. A lucky number is an element of the matrix such that it is the minimum element in its row and maximum in its column. ", + "category": [ + "Array", + "Matrix" + ], + "complexity": "Easy", + "successrate": 70.9, + "totalsubmissions": 88698, + "totalaccepted": 62865, + "likes": 929, + "dislikes": 65, + "hints": "Find out and save the minimum of each row and maximum of each column in two lists. Then scan through the whole matrix to identify the elements that satisfy the criteria.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "matrix = [[3,7,8],[9,11,13],[15,16,17]]", + "expected_output": "[15]", + "explanation": "15 is the only lucky number since it is the minimum in its row and the maximum in its column." + }, + { + "example_num": 2, + "expected_input": "matrix = [[1,10,4,2],[9,3,8,7],[15,16,17,12]]", + "expected_output": "[12]", + "explanation": "12 is the only lucky number since it is the minimum in its row and the maximum in its column." + }, + { + "example_num": 3, + "expected_input": "matrix = [[7,8],[1,2]]", + "expected_output": "[7]", + "explanation": "7 is the only lucky number since it is the minimum in its row and the maximum in its column." + } + ], + "solution": "/**\n * @param {number[][]} matrix\n * @return {number[]}\n */\nconst luckyNumbers = function(matrix) {\n const m = matrix.length, n = matrix[0].length\n const res = []\n for(let i = 0; i < m; i++) {\n let tmp = [i, 0, matrix[i][0]]\n for(let j = 1; j < n; j++) {\n if(matrix[i][j] < tmp[2]) {\n tmp = [i, j, matrix[i][j]]\n }\n }\n res.push(tmp)\n }\n \n const ans = []\n for(let [r, c, v] of res) {\n let found = false\n for(let i = 0; i < m; i++) {\n if(i !== r && matrix[i][c] > v) {\n found = true\n break\n }\n }\n \n if(found === false) ans.push(v)\n } \n \n return ans\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720d99", + "questionid": 718, + "title": "Find a Corresponding Node of a Binary Tree in a Clone of That Tree", + "slug": "find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree", + "description": "Given two binary trees original and cloned and given a reference to a node target in the original tree. The cloned tree is a copy of the original tree. Return a reference to the same node in the cloned tree. Note that you are not allowed to change any of the two trees or the target node and the answer must be a reference to a node in the cloned tree. ", + "category": [ + "Tree", + "Depth-First Search", + "Breadth-First Search", + "Binary Tree" + ], + "complexity": "Medium", + "successrate": 85.5, + "totalsubmissions": 119043, + "totalaccepted": 101779, + "likes": 720, + "dislikes": 928, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "tree = [7,4,3,null,null,6,19], target = 3", + "expected_output": "3", + "explanation": "In all examples the original and cloned trees are shown. The target node is a green node from the original tree. The answer is the yellow node from the cloned tree." + }, + { + "example_num": 2, + "expected_input": "tree = [7], target = 7", + "expected_output": "7", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "tree = [8,null,6,null,5,null,4,null,3,null,2,null,1], target = 4", + "expected_output": "4", + "explanation": "" + } + ], + "solution": null + }, + { + "_id": "66f925ddfdfb8e1665720da0", + "questionid": 725, + "title": "Find Lucky Integer in an Array", + "slug": "find-lucky-integer-in-an-array", + "description": "Given an array of integers arr, a lucky integer is an integer that has a frequency in the array equal to its value. Return the largest lucky integer in the array. If there is no lucky integer return -1. ", + "category": [ + "Array", + "Hash Table", + "Counting" + ], + "complexity": "Easy", + "successrate": 63.6, + "totalsubmissions": 106984, + "totalaccepted": 68034, + "likes": 625, + "dislikes": 19, + "hints": "Count the frequency of each integer in the array. Get all lucky numbers and return the largest of them.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "arr = [2,2,3,4]", + "expected_output": "2", + "explanation": "The only lucky number in the array is 2 because frequency[2] == 2." + }, + { + "example_num": 2, + "expected_input": "arr = [1,2,2,3,3,3]", + "expected_output": "3", + "explanation": "1, 2 and 3 are all lucky numbers, return the largest of them." + }, + { + "example_num": 3, + "expected_input": "arr = [2,2,2,3,3]", + "expected_output": "-1", + "explanation": "There are no lucky numbers in the array." + } + ], + "solution": "/**\n * @param {number[]} arr\n * @return {number}\n */\nconst findLucky = function(arr) {\n const hash = {}\n for(let e of arr) hash[e] = (hash[e] || 0) + 1\n let res\n Object.keys(hash).forEach(k => {\n if(+k === hash[k]) {\n if (res == null) res = hash[k]\n else {\n if (hash[k] > res) res = hash[k]\n }\n } \n })\n return res == null ? -1 : res\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720da4", + "questionid": 729, + "title": "Minimum Subsequence in Non-Increasing Order", + "slug": "minimum-subsequence-in-non-increasing-order", + "description": "Given the array nums, obtain a subsequence of the array whose sum of elements is strictly greater than the sum of the non\u00a0included elements in such subsequence. If there are multiple solutions, return the subsequence with minimum size and if there still exist multiple solutions, return the subsequence with the maximum total sum of all its elements. A subsequence of an array can be obtained by erasing some (possibly zero) elements from the array. Note that the solution with the given constraints is guaranteed to be\u00a0unique. Also return the answer sorted in non-increasing order. ", + "category": [ + "Array", + "Greedy", + "Sorting" + ], + "complexity": "Easy", + "successrate": 72.2, + "totalsubmissions": 68538, + "totalaccepted": 49486, + "likes": 349, + "dislikes": 376, + "hints": "Sort elements and take each element from the largest until accomplish the conditions.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [4,3,10,9,8]", + "expected_output": "[10,9]", + "explanation": "The subsequences [10,9] and [10,8] are minimal such that the sum of their elements is strictly greater than the sum of elements not included. However, the subsequence [10,9] has the maximum total sum of its elements. " + }, + { + "example_num": 2, + "expected_input": "nums = [4,4,7,6,7]", + "expected_output": "[7,7,6]", + "explanation": "The subsequence [7,7] has the sum of its elements equal to 14 which is not strictly greater than the sum of elements not included (14 = 4 + 4 + 6). Therefore, the subsequence [7,6,7] is the minimal satisfying the conditions. Note the subsequence has to be returned in non-increasing order." + } + ], + "solution": null + }, + { + "_id": "66f925ddfdfb8e1665720da5", + "questionid": 730, + "title": "Stone Game III", + "slug": "stone-game-iii", + "description": "Alice and Bob continue their games with piles of stones. There are several stones arranged in a row, and each stone has an associated value which is an integer given in the array stoneValue. Alice and Bob take turns, with Alice starting first. On each player's turn, that player can take 1, 2, or 3 stones from the first remaining stones in the row. The score of each player is the sum of the values of the stones taken. The score of each player is 0 initially. The objective of the game is to end with the highest score, and the winner is the player with the highest score and there could be a tie. The game continues until all the stones have been taken. Assume Alice and Bob play optimally. Return \"Alice\" if Alice will win, \"Bob\" if Bob will win, or \"Tie\" if they will end the game with the same score. ", + "category": [ + "Array", + "Math", + "Dynamic Programming", + "Game Theory" + ], + "complexity": "Hard", + "successrate": 60.2, + "totalsubmissions": 59197, + "totalaccepted": 35638, + "likes": 959, + "dislikes": 22, + "hints": "The game can be mapped to minmax game. Alice tries to maximize the total score and Bob tries to minimize it. Use dynamic programming to simulate the game. If the total score was 0 the game is \"Tie\", and if it has positive value then \"Alice\" wins, otherwise \"Bob\" wins.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "stoneValue = [1,2,3,7]", + "expected_output": ""Bob"", + "explanation": "Alice will always lose. Her best move will be to take three piles and the score become 6. Now the score of Bob is 7 and Bob wins." + }, + { + "example_num": 2, + "expected_input": "stoneValue = [1,2,3,-9]", + "expected_output": ""Alice"", + "explanation": "Alice must choose all the three piles at the first move to win and leave Bob with negative score.\nIf Alice chooses one pile her score will be 1 and the next move Bob's score becomes 5. In the next move, Alice will take the pile with value = -9 and lose.\nIf Alice chooses two piles her score will be 3 and the next move Bob's score becomes 3. In the next move, Alice will take the pile with value = -9 and also lose.\nRemember that both play optimally so here Alice will choose the scenario that makes her win." + }, + { + "example_num": 3, + "expected_input": "stoneValue = [1,2,3,6]", + "expected_output": ""Tie"", + "explanation": "Alice cannot win this game. She can end the game in a draw if she decided to choose all the first three piles, otherwise she will lose." + } + ], + "solution": "/**\n * @param {number[]} stoneValue\n * @return {string}\n */\nconst stoneGameIII = function (stoneValue) {\n const n = stoneValue.length\n const suffixSum = new Array(n + 1)\n const dp = new Array(n + 1)\n suffixSum[n] = 0\n dp[n] = 0\n for (let i = n - 1; i >= 0; i--)\n suffixSum[i] = suffixSum[i + 1] + stoneValue[i]\n for (let i = n - 1; i >= 0; i--) {\n dp[i] = stoneValue[i] + suffixSum[i + 1] - dp[i + 1]\n for (let k = i + 1; k < i + 3 && k < n; k++) {\n dp[i] = Math.max(dp[i], suffixSum[i] - dp[k + 1])\n }\n }\n if (dp[0] * 2 === suffixSum[0]) return 'Tie'\n else if (dp[0] * 2 > suffixSum[0]) return 'Alice'\n else return 'Bob'\n}\n\n// another\n\n/**\n * @param {number[]} stoneValue\n * @return {string}\n */\nconst stoneGameIII = function (stoneValue) {\n const n = stoneValue.length,\n dp = new Array(4).fill(0)\n for (let i = n - 1; i >= 0; --i) {\n dp[i % 4] = -Infinity\n for (let k = 0, take = 0; k < 3 && i + k < n; ++k) {\n take += stoneValue[i + k]\n dp[i % 4] = Math.max(dp[i % 4], take - dp[(i + k + 1) % 4])\n }\n }\n if (dp[0] > 0) return 'Alice'\n if (dp[0] < 0) return 'Bob'\n return 'Tie'\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720da6", + "questionid": 731, + "title": "String Matching in an Array", + "slug": "string-matching-in-an-array", + "description": "Given an array of string words. Return all strings in words which is substring of another word in any order. String words[i] is substring of words[j],\u00a0if\u00a0can be obtained removing some characters to left and/or right side of words[j]. ", + "category": [ + "String", + "String Matching" + ], + "complexity": "Easy", + "successrate": 63.8, + "totalsubmissions": 84583, + "totalaccepted": 54002, + "likes": 509, + "dislikes": 72, + "hints": "Bruteforce to find if one string is substring of another or use KMP algorithm.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "words = ["mass","as","hero","superhero"]", + "expected_output": "["as","hero"]", + "explanation": ""as" is substring of "mass" and "hero" is substring of "superhero".\n["hero","as"] is also a valid answer." + }, + { + "example_num": 2, + "expected_input": "words = ["leetcode","et","code"]", + "expected_output": "["et","code"]", + "explanation": ""et", "code" are substring of "leetcode"." + }, + { + "example_num": 3, + "expected_input": "words = ["blue","green","bu"]", + "expected_output": "[]", + "explanation": "No string of words is substring of another string." + } + ], + "solution": "/**\n * @param {string[]} words\n * @return {string[]}\n */\nconst stringMatching = function(words) {\n const res = [], n = words.length\n for(let i = 0; i < n; i++) {\n const cur = words[i]\n for(let j = 0; j < n; j++) {\n if(i !== j && words[j].indexOf(cur) !== -1) {\n res.push(cur); \n break\n }\n }\n }\n return res\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720da8", + "questionid": 733, + "title": "Number of Ways to Wear Different Hats to Each Other", + "slug": "number-of-ways-to-wear-different-hats-to-each-other", + "description": "There are n people and 40 types of hats labeled from 1 to 40. Given a 2D integer array hats, where hats[i] is a list of all hats preferred by the ith person. Return the number of ways that the n people wear different hats to each other. Since the answer may be too large, return it modulo 109 + 7. ", + "category": [ + "Array", + "Dynamic Programming", + "Bit Manipulation", + "Bitmask" + ], + "complexity": "Hard", + "successrate": 41.9, + "totalsubmissions": 21320, + "totalaccepted": 8931, + "likes": 591, + "dislikes": 7, + "hints": "Dynamic programming + bitmask. dp(peopleMask, idHat) number of ways to wear different hats given a bitmask (people visited) and used hats from 1 to idHat-1.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "hats = [[3,4],[4,5],[5]]", + "expected_output": "1", + "explanation": "There is only one way to choose hats given the conditions. \nFirst person choose hat 3, Second person choose hat 4 and last one hat 5." + }, + { + "example_num": 2, + "expected_input": "hats = [[3,5,1],[3,5]]", + "expected_output": "4", + "explanation": "There are 4 ways to choose hats:\n(3,5), (5,3), (1,3) and (1,5)" + }, + { + "example_num": 3, + "expected_input": "hats = [[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]]", + "expected_output": "24", + "explanation": "Each person can choose hats labeled from 1 to 4.\nNumber of Permutations of (1,2,3,4) = 24." + } + ], + "solution": "/**\n * @param {number[][]} hats\n * @return {number}\n */\nconst numberWays = function(hats) {\n const map = new Map()\n const n = hats.length\n for(let i = 0; i < n; i++) {\n for(const h of hats[i]) {\n if(!map.has(h)) map.set(h, [])\n map.get(h).push(i)\n }\n }\n const mod = 1e9 + 7\n const allMask = (1 << n) - 1\n const dp = Array.from({ length: 41 }, () => Array(1024))\n \n return dfs(1, 0)\n \n function dfs(hat, mask) {\n if(mask === allMask) return 1\n if(hat > 40) return 0\n if(dp[hat][mask] != null) return dp[hat][mask]\n \n let res = 0\n \n // not using this `hat`\n res += dfs(hat + 1, mask)\n for(const p of (map.get(hat) || [])) {\n if(((mask >> p) & 1) === 0) {\n res += dfs(hat + 1, mask | (1 << p))\n res = res % mod\n }\n }\n dp[hat][mask] = res\n return res\n }\n \n};\n\n// another\n\n\n/**\n * @param {number[][]} hats\n * @return {number}\n */\nconst numberWays = function (hats) {\n const pplThatCanWearHats = new Array(40 + 1).fill(null).map(() => [])\n for (let i = 0; i < hats.length; i++) {\n const personMask = 1 << i\n for (let hat of hats[i]) {\n pplThatCanWearHats[hat].push(personMask)\n }\n }\n\n const cache = {}\n const dfs = (hat, pplWithoutHatsMask) => {\n if (!pplWithoutHatsMask) return 1\n if (hat === 41) return 0\n const key = `${hat}-${pplWithoutHatsMask}`\n if (cache.hasOwnProperty(key)) return cache[key]\n const nextHat = hat + 1\n let total = dfs(nextHat, pplWithoutHatsMask)\n for (let personMask of pplThatCanWearHats[hat]) {\n if (!(pplWithoutHatsMask & personMask)) continue\n total += dfs(nextHat, pplWithoutHatsMask ^ personMask)\n }\n return (cache[key] = total % 1000000007)\n }\n return dfs(1, (1 << hats.length) - 1)\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720dae", + "questionid": 739, + "title": "Diagonal Traverse II", + "slug": "diagonal-traverse-ii", + "description": "Given a 2D integer array nums, return all elements of nums in diagonal order as shown in the below images. ", + "category": [ + "Array", + "Sorting", + "Heap (Priority Queue)" + ], + "complexity": "Medium", + "successrate": 49.9, + "totalsubmissions": 80647, + "totalaccepted": 40270, + "likes": 810, + "dislikes": 75, + "hints": "Notice that numbers with equal sums of row and column indexes belong to the same diagonal. Store them in tuples (sum, row, val), sort them, and then regroup the answer.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [[1,2,3],[4,5,6],[7,8,9]]", + "expected_output": "[1,4,2,7,5,3,8,6,9]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "nums = [[1,2,3,4,5],[6,7],[8],[9,10,11],[12,13,14,15,16]]", + "expected_output": "[1,6,2,8,7,3,9,4,12,10,5,13,11,14,15,16]", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[][]} nums\n * @return {number[]}\n */\nconst findDiagonalOrder = function(nums) {\n const m = nums.length\n const map = new Map()\n let maxKey = 0\n for(let i = 0; i < m; i++) {\n for(let j = 0, n = nums[i].length; j < n; j++) {\n if(!map.has(i + j)) map.set(i + j, [])\n map.get(i + j).push(nums[i][j])\n maxKey = Math.max(maxKey, i + j)\n }\n }\n // console.log(map)\n const res = []\n for(let i = 0; i <= maxKey; i++) {\n if(map.has(i)) {\n const tmp = map.get(i)\n tmp.reverse()\n res.push(...tmp)\n }\n }\n \n return res\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720db0", + "questionid": 741, + "title": "Simplified Fractions", + "slug": "simplified-fractions", + "description": "Given an integer n, return a list of all simplified fractions between 0 and 1 (exclusive) such that the denominator is less-than-or-equal-to n. You can return the answer in any order. ", + "category": [ + "Math", + "String", + "Number Theory" + ], + "complexity": "Medium", + "successrate": 63.9, + "totalsubmissions": 32065, + "totalaccepted": 20489, + "likes": 237, + "dislikes": 32, + "hints": "A fraction is fully simplified if there is no integer that divides cleanly into the numerator and denominator. In other words the greatest common divisor of the numerator and the denominator of a simplified fraction is 1.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 2", + "expected_output": "["1/2"]", + "explanation": ""1/2" is the only unique fraction with a denominator less-than-or-equal-to 2." + }, + { + "example_num": 2, + "expected_input": "n = 3", + "expected_output": "["1/2","1/3","2/3"]", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "n = 4", + "expected_output": "["1/2","1/3","1/4","2/3","3/4"]", + "explanation": ""2/4" is not a simplified fraction because it can be simplified to "1/2"." + } + ], + "solution": null + }, + { + "_id": "66f925ddfdfb8e1665720db2", + "questionid": 743, + "title": "Destination City", + "slug": "destination-city", + "description": "You are given the array paths, where paths[i] = [cityAi, cityBi] means there exists a direct path going from cityAi to cityBi. Return the destination city, that is, the city without any path outgoing to another city. It is guaranteed that the graph of paths forms a line without any loop, therefore, there will be exactly one destination city. ", + "category": [ + "Hash Table", + "String" + ], + "complexity": "Easy", + "successrate": 77.7, + "totalsubmissions": 125127, + "totalaccepted": 97208, + "likes": 934, + "dislikes": 59, + "hints": "Start in any city and use the path to move to the next city. Eventually, you will reach a city with no path outgoing, this is the destination city.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "paths = [["London","New York"],["New York","Lima"],["Lima","Sao Paulo"]]", + "expected_output": ""Sao Paulo"", + "explanation": "Starting at "London" city you will reach "Sao Paulo" city which is the destination city. Your trip consist of: "London" -> "New York" -> "Lima" -> "Sao Paulo"." + }, + { + "example_num": 2, + "expected_input": "paths = [["B","C"],["D","B"],["C","A"]]", + "expected_output": ""A"", + "explanation": "All possible trips are: \n"D" -> "B" -> "C" -> "A". \n"B" -> "C" -> "A". \n"C" -> "A". \n"A". \nClearly the destination city is "A"." + }, + { + "example_num": 3, + "expected_input": "paths = [["A","Z"]]", + "expected_output": ""Z"", + "explanation": "" + } + ], + "solution": "/**\n * @param {string[][]} paths\n * @return {string}\n */\nconst destCity = function(paths) {\n const hash = {}\n for(let [s, e] of paths) {\n if(hash[e] == null) hash[e] = true\n hash[s] = false\n if(hash[s] === true) hash[s] = false\n }\n \n for(let k in hash) {\n if(hash[k]) return k\n }\n};\n\n// another\n\n/**\n * @param {string[][]} paths\n * @return {string}\n */\nconst destCity = function(paths) {\n const set = new Set()\n for(let [s, e] of paths) set.add(e)\n for(let [s, e] of paths) set.delete(s)\n \n return set[Symbol.iterator]().next().value\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720dba", + "questionid": 751, + "title": "Number of Students Doing Homework at a Given Time", + "slug": "number-of-students-doing-homework-at-a-given-time", + "description": "Given two integer arrays startTime and endTime and given an integer queryTime. The ith student started doing their homework at the time startTime[i] and finished it at time endTime[i]. Return the number of students doing their homework at time queryTime. More formally, return the number of students where queryTime lays in the interval [startTime[i], endTime[i]] inclusive. ", + "category": [ + "Array" + ], + "complexity": "Easy", + "successrate": 76.4, + "totalsubmissions": 108069, + "totalaccepted": 82597, + "likes": 564, + "dislikes": 128, + "hints": "Imagine that startTime[i] and endTime[i] form an interval (i.e. [startTime[i], endTime[i]]). The answer is how many times the queryTime laid in those mentioned intervals.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "startTime = [1,2,3], endTime = [3,2,7], queryTime = 4", + "expected_output": "1", + "explanation": "We have 3 students where:\nThe first student started doing homework at time 1 and finished at time 3 and wasn't doing anything at time 4.\nThe second student started doing homework at time 2 and finished at time 2 and also wasn't doing anything at time 4.\nThe third student started doing homework at time 3 and finished at time 7 and was the only student doing homework at time 4." + }, + { + "example_num": 2, + "expected_input": "startTime = [4], endTime = [4], queryTime = 4", + "expected_output": "1", + "explanation": "The only student was doing their homework at the queryTime." + } + ], + "solution": null + }, + { + "_id": "66f925ddfdfb8e1665720dbd", + "questionid": 754, + "title": "Check If a Word Occurs As a Prefix of Any Word in a Sentence", + "slug": "check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence", + "description": "Given a sentence that consists of some words separated by a single space, and a searchWord, check if searchWord is a prefix of any word in sentence. Return the index of the word in sentence (1-indexed) where searchWord is a prefix of this word. If searchWord is a prefix of more than one word, return the index of the first word (minimum index). If there is no such word return -1. A prefix of a string s is any leading contiguous substring of s. ", + "category": [ + "String", + "String Matching" + ], + "complexity": "Easy", + "successrate": 64.5, + "totalsubmissions": 75561, + "totalaccepted": 48740, + "likes": 495, + "dislikes": 23, + "hints": "First extract the words of the sentence. Check for each word if searchWord occurs at index 0, if so return the index of this word (1-indexed) If searchWord doesn't exist as a prefix of any word return the default value (-1).", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "sentence = "i love eating burger", searchWord = "burg"", + "expected_output": "4", + "explanation": ""burg" is prefix of "burger" which is the 4th word in the sentence." + }, + { + "example_num": 2, + "expected_input": "sentence = "this problem is an easy problem", searchWord = "pro"", + "expected_output": "2", + "explanation": ""pro" is prefix of "problem" which is the 2nd and the 6th word in the sentence, but we return 2 as it's the minimal index." + }, + { + "example_num": 3, + "expected_input": "sentence = "i am tired", searchWord = "you"", + "expected_output": "-1", + "explanation": ""you" is not a prefix of any word in the sentence." + } + ], + "solution": null + }, + { + "_id": "66f925ddfdfb8e1665720dbe", + "questionid": 755, + "title": "Maximum Number of Vowels in a Substring of Given Length", + "slug": "maximum-number-of-vowels-in-a-substring-of-given-length", + "description": "Given a string s and an integer k, return the maximum number of vowel letters in any substring of s with length k. Vowel letters in English are 'a', 'e', 'i', 'o', and 'u'. ", + "category": [ + "String", + "Sliding Window" + ], + "complexity": "Medium", + "successrate": 57.4, + "totalsubmissions": 73875, + "totalaccepted": 42389, + "likes": 691, + "dislikes": 37, + "hints": "Keep a window of size k and maintain the number of vowels in it. Keep moving the window and update the number of vowels while moving. Answer is max number of vowels of any window.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "abciiidef", k = 3", + "expected_output": "3", + "explanation": "The substring "iii" contains 3 vowel letters." + }, + { + "example_num": 2, + "expected_input": "s = "aeiou", k = 2", + "expected_output": "2", + "explanation": "Any substring of length 2 contains 2 vowels." + }, + { + "example_num": 3, + "expected_input": "s = "leetcode", k = 3", + "expected_output": "2", + "explanation": ""lee", "eet" and "ode" contain 2 vowels." + } + ], + "solution": null + }, + { + "_id": "66f925ddfdfb8e1665720dc5", + "questionid": 762, + "title": "Probability of a Two Boxes Having The Same Number of Distinct Balls", + "slug": "probability-of-a-two-boxes-having-the-same-number-of-distinct-balls", + "description": "Given 2n balls of k distinct colors. You will be given an integer array balls of size k where balls[i] is the number of balls of color i. All the balls will be shuffled uniformly at random, then we will distribute the first n balls to the first box and the remaining n balls to the other box (Please read the explanation of the second example carefully). Please note that the two boxes are considered different. For example, if we have two balls of colors a and b, and two boxes [] and (), then the distribution [a] (b) is considered different than the distribution [b] (a) (Please read the explanation of the first example carefully). Return the probability that the two boxes have the same number of distinct balls. Answers within 10-5 of the actual value will be accepted as correct. ", + "category": [ + "Math", + "Dynamic Programming", + "Backtracking", + "Combinatorics", + "Probability and Statistics" + ], + "complexity": "Hard", + "successrate": 60.9, + "totalsubmissions": 9746, + "totalaccepted": 5937, + "likes": 193, + "dislikes": 142, + "hints": "Check how many ways you can distribute the balls between the boxes. Consider that one way you will use (x1, x2, x3, ..., xk) where xi is the number of balls from colour i. The probability of achieving this way randomly is ( (ball1 C x1) * (ball2 C x2) * (ball3 C x3) * ... * (ballk C xk)) / (2n C n). The probability of a draw is the sigma of probabilities of different ways to achieve draw. Can you use Dynamic programming to solve this problem in a better complexity ?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "balls = [1,1]", + "expected_output": "1.00000", + "explanation": "Only 2 ways to divide the balls equally:\n- A ball of color 1 to box 1 and a ball of color 2 to box 2\n- A ball of color 2 to box 1 and a ball of color 1 to box 2\nIn both ways, the number of distinct colors in each box is equal. The probability is 2/2 = 1" + }, + { + "example_num": 2, + "expected_input": "balls = [2,1,1]", + "expected_output": "0.66667", + "explanation": "We have the set of balls [1, 1, 2, 3]\nThis set of balls will be shuffled randomly and we may have one of the 12 distinct shuffles with equal probability (i.e. 1/12):\n[1,1 / 2,3], [1,1 / 3,2], [1,2 / 1,3], [1,2 / 3,1], [1,3 / 1,2], [1,3 / 2,1], [2,1 / 1,3], [2,1 / 3,1], [2,3 / 1,1], [3,1 / 1,2], [3,1 / 2,1], [3,2 / 1,1]\nAfter that, we add the first two balls to the first box and the second two balls to the second box.\nWe can see that 8 of these 12 possible random distributions have the same number of distinct colors of balls in each box.\nProbability is 8/12 = 0.66667" + }, + { + "example_num": 3, + "expected_input": "balls = [1,2,1,2]", + "expected_output": "0.60000", + "explanation": "The set of balls is [1, 2, 2, 3, 4, 4]. It is hard to display all the 180 possible random shuffles of this set but it is easy to check that 108 of them will have the same number of distinct colors in each box.\nProbability = 108 / 180 = 0.6" + } + ], + "solution": "/**\n * @param {number[]} balls\n * @return {number}\n */\nconst getProbability = function(balls) {\n const k = balls.length;\n const halfUsed = balls.reduce((acc, val) => acc + val, 0) / 2;\n const startArray = new Array(k);\n startArray.fill(0);\n const perm = function (b1, b2) {\n let p1, p2, s1, s2;\n s1 = b1.reduce((acc, val) => acc + val, 0);\n s2 = b2.reduce((acc, val) => acc + val, 0);\n const fact = function (n) {\n let f = 1;\n for (let i = 2; i <= n; i++) f *= i;\n return f;\n };\n p1 = fact(s1);\n p2 = fact(s2);\n b1.forEach((val) => {\n if (val > 1) p1 /= fact(val);\n });\n b2.forEach((val) => {\n if (val > 1) p2 /= fact(val);\n });\n return p1 * p2;\n };\n\n const getValidCombos = function (ballsUsed, colorNum = 0) {\n let box1Used = ballsUsed.reduce((acc, val) => acc + val, 0);\n let matches = { good: 0, total: 0 },\n thisColorMax = halfUsed - box1Used;\n if (colorNum === k - 1) {\n if (thisColorMax > balls[colorNum]) return { good: 0, total: 0 };\n ballsUsed[colorNum] = thisColorMax;\n let ballsLeft = [];\n let colorsUsed = [0, 0];\n for (let i = 0; i < k; i++) {\n ballsLeft[i] = balls[i] - ballsUsed[i];\n if (ballsUsed[i] > 0) colorsUsed[0]++;\n if (ballsLeft[i] > 0) colorsUsed[1]++;\n }\n let permutations = perm(ballsUsed, ballsLeft, k);\n return {\n good: colorsUsed[1] === colorsUsed[0] ? permutations : 0,\n total: permutations,\n };\n }\n thisColorMax = Math.min(thisColorMax, balls[colorNum]);\n for (let i = 0; i <= thisColorMax; i++) {\n let match = getValidCombos([...ballsUsed], colorNum + 1);\n matches = {\n good: matches.good + match.good,\n total: matches.total + match.total,\n };\n ballsUsed[colorNum]++;\n }\n return matches;\n };\n let res = getValidCombos(startArray);\n return res.good / res.total;\n};\n\n\n// another\n\n\n/**\n * @param {number[]} balls\n * @return {number}\n */\nconst getProbability = function (balls) {\n const k = balls.length\n const halfUsed = balls.reduce((acc, val) => acc + val, 0) / 2\n const startArray = new Array(k)\n startArray.fill(0)\n const perm = function (b1, b2) {\n let p1, p2, s1, s2\n s1 = b1.reduce((acc, val) => acc + val, 0)\n s2 = b2.reduce((acc, val) => acc + val, 0)\n const fact = function (n) {\n let f = 1\n for (let i = 2; i <= n; i++) f *= i\n return f\n }\n p1 = fact(s1)\n p2 = fact(s2)\n b1.forEach((val) => {\n if (val > 1) p1 /= fact(val)\n })\n b2.forEach((val) => {\n if (val > 1) p2 /= fact(val)\n })\n return p1 * p2\n }\n\n const getValidCombos = function (ballsUsed, colorNum = 0) {\n let box1Used = ballsUsed.reduce((acc, val) => acc + val, 0)\n let matches = { good: 0, total: 0 },\n thisColorMax = halfUsed - box1Used\n if (colorNum === k - 1) {\n if (thisColorMax > balls[colorNum]) return { good: 0, total: 0 }\n ballsUsed[colorNum] = thisColorMax\n let ballsLeft = []\n let colorsUsed = [0, 0]\n for (let i = 0; i < k; i++) {\n ballsLeft[i] = balls[i] - ballsUsed[i]\n if (ballsUsed[i] > 0) colorsUsed[0]++\n if (ballsLeft[i] > 0) colorsUsed[1]++\n }\n let permutations = perm(ballsUsed, ballsLeft, k)\n return {\n good: colorsUsed[1] === colorsUsed[0] ? permutations : 0,\n total: permutations,\n }\n }\n thisColorMax = Math.min(thisColorMax, balls[colorNum])\n for (let i = 0; i <= thisColorMax; i++) {\n let match = getValidCombos([...ballsUsed], colorNum + 1)\n matches = {\n good: matches.good + match.good,\n total: matches.total + match.total,\n }\n ballsUsed[colorNum]++\n }\n return matches\n }\n let res = getValidCombos(startArray)\n return res.good / res.total\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720dcb", + "questionid": 768, + "title": "Running Sum of 1d Array", + "slug": "running-sum-of-1d-array", + "description": "Given an array nums. We define a running sum of an array as\u00a0runningSum[i] = sum(nums[0]...nums[i]). Return the running sum of nums. ", + "category": [ + "Array", + "Prefix Sum" + ], + "complexity": "Easy", + "successrate": 89.6, + "totalsubmissions": 566858, + "totalaccepted": 507777, + "likes": 2513, + "dislikes": 177, + "hints": "Think about how we can calculate the i-th number in the running sum from the (i-1)-th number.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,2,3,4]", + "expected_output": "[1,3,6,10]", + "explanation": "Running sum is obtained as follows: [1, 1+2, 1+2+3, 1+2+3+4]." + }, + { + "example_num": 2, + "expected_input": "nums = [1,1,1,1,1]", + "expected_output": "[1,2,3,4,5]", + "explanation": "Running sum is obtained as follows: [1, 1+1, 1+1+1, 1+1+1+1, 1+1+1+1+1]." + }, + { + "example_num": 3, + "expected_input": "nums = [3,1,2,10,1]", + "expected_output": "[3,4,6,16,17]", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} nums\n * @return {number[]}\n */\nconst runningSum = function(nums) {\n for(let i = 1, len = nums.length; i < len; i++) {\n nums[i] += nums[i - 1]\n }\n return nums\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720dd7", + "questionid": 780, + "title": "Max Value of Equation", + "slug": "max-value-of-equation", + "description": "You are given an array points containing the coordinates of points on a 2D plane, sorted by the x-values, where points[i] = [xi, yi] such that xi < xj for all 1 <= i < j <= points.length. You are also given an integer k. Return the maximum value of the equation yi + yj + |xi - xj| where |xi - xj| <= k and 1 <= i < j <= points.length. It is guaranteed that there exists at least one pair of points that satisfy the constraint |xi - xj| <= k. ", + "category": [ + "Array", + "Queue", + "Sliding Window", + "Heap (Priority Queue)", + "Monotonic Queue" + ], + "complexity": "Hard", + "successrate": 46.9, + "totalsubmissions": 63274, + "totalaccepted": 29650, + "likes": 782, + "dislikes": 29, + "hints": "Use a priority queue to store for each point i, the tuple [yi-xi, xi] Loop through the array and pop elements from the heap if the condition xj - xi > k, where j is the current index and i is the point on top the queue. After popping elements from the queue. If the queue is not empty, calculate the equation with the current point and the point on top of the queue and maximize the answer.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "points = [[1,3],[2,0],[5,10],[6,-10]], k = 1", + "expected_output": "4", + "explanation": "The first two points satisfy the condition |xi - xj| <= 1 and if we calculate the equation we get 3 + 0 + |1 - 2| = 4. Third and fourth points also satisfy the condition and give a value of 10 + -10 + |5 - 6| = 1.\nNo other pairs satisfy the condition, so we return the max of 4 and 1." + }, + { + "example_num": 2, + "expected_input": "points = [[0,0],[3,0],[9,2]], k = 3", + "expected_output": "3\nExplanation: Only the first two points have an absolute difference of 3 or less in the x-values, and give the value of 0 + 0 + |0 - 3| = 3.", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[][]} points\n * @param {number} k\n * @return {number}\n */\nconst findMaxValueOfEquation = function (points, k) {\n let res = -Number.MAX_VALUE\n const deque = []\n for (let i = 0; i < points.length; i++) {\n const x = points[i][0]\n const y = points[i][1]\n while (deque.length != 0 && x - deque[0][1] > k) {\n deque.shift()\n }\n if (deque.length != 0) {\n res = Math.max(res, deque[0][0] + x + y)\n }\n while (deque.length != 0 && deque[deque.length - 1][0] <= y - x) {\n deque.pop()\n }\n deque.push([y - x, x])\n }\n return res\n}\n\n// another\n\n/**\n * @param {number[][]} points\n * @param {number} k\n * @return {number}\n */\nconst findMaxValueOfEquation = function (points, k) {\n const pq = new PriorityQueue((a, b) =>\n a[0] === b[0] ? a[1] < b[1] : b[0] < a[0]\n )\n let res = -Infinity\n for (let point of points) {\n while (!pq.isEmpty() && point[0] - pq.peek()[1] > k) {\n pq.pop()\n }\n if (!pq.isEmpty()) {\n res = Math.max(res, pq.peek()[0] + point[0] + point[1])\n }\n pq.push([point[1] - point[0], point[0]])\n }\n return res\n}\n\nclass PriorityQueue {\n constructor(comparator = (a, b) => a > b) {\n this.heap = []\n this.top = 0\n this.comparator = comparator\n }\n size() {\n return this.heap.length\n }\n isEmpty() {\n return this.size() === 0\n }\n peek() {\n return this.heap[this.top]\n }\n push(...values) {\n values.forEach((value) => {\n this.heap.push(value)\n this.siftUp()\n })\n return this.size()\n }\n pop() {\n const poppedValue = this.peek()\n const bottom = this.size() - 1\n if (bottom > this.top) {\n this.swap(this.top, bottom)\n }\n this.heap.pop()\n this.siftDown()\n return poppedValue\n }\n replace(value) {\n const replacedValue = this.peek()\n this.heap[this.top] = value\n this.siftDown()\n return replacedValue\n }\n\n parent = (i) => ((i + 1) >>> 1) - 1\n left = (i) => (i << 1) + 1\n right = (i) => (i + 1) << 1\n greater = (i, j) => this.comparator(this.heap[i], this.heap[j])\n swap = (i, j) => ([this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]])\n siftUp = () => {\n let node = this.size() - 1\n while (node > this.top && this.greater(node, this.parent(node))) {\n this.swap(node, this.parent(node))\n node = this.parent(node)\n }\n }\n siftDown = () => {\n let node = this.top\n while (\n (this.left(node) < this.size() && this.greater(this.left(node), node)) ||\n (this.right(node) < this.size() && this.greater(this.right(node), node))\n ) {\n let maxChild =\n this.right(node) < this.size() &&\n this.greater(this.right(node), this.left(node))\n ? this.right(node)\n : this.left(node)\n this.swap(node, maxChild)\n node = maxChild\n }\n }\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720dcc", + "questionid": 769, + "title": "Least Number of Unique Integers after K Removals", + "slug": "least-number-of-unique-integers-after-k-removals", + "description": "Given an array of integers\u00a0arr\u00a0and an integer k.\u00a0Find the least number of unique integers\u00a0after removing exactly k elements. ", + "category": [ + "Array", + "Hash Table", + "Greedy", + "Sorting", + "Counting" + ], + "complexity": "Medium", + "successrate": 60.2, + "totalsubmissions": 114592, + "totalaccepted": 68982, + "likes": 868, + "dislikes": 64, + "hints": "Use a map to count the frequencies of the numbers in the array. An optimal strategy is to remove the numbers with the smallest count first.", + "deleted": false, + "examples": [], + "solution": null + }, + { + "_id": "66f925ddfdfb8e1665720dd9", + "questionid": 782, + "title": "Last Moment Before All Ants Fall Out of a Plank", + "slug": "last-moment-before-all-ants-fall-out-of-a-plank", + "description": "We have a wooden plank of the length n units. Some ants are walking on the plank, each ant moves with a speed of 1 unit per second. Some of the ants move to the left, the other move to the right. When two ants moving in two different directions meet at some point, they change their directions and continue moving again. Assume changing directions does not take any additional time. When an ant reaches one end of the plank at a time t, it falls out of the plank immediately. Given an integer n and two integer arrays left and right, the positions of the ants moving to the left and the right, return the moment when the last ant(s) fall out of the plank. ", + "category": [ + "Array", + "Brainteaser", + "Simulation" + ], + "complexity": "Medium", + "successrate": 54.8, + "totalsubmissions": 27754, + "totalaccepted": 15220, + "likes": 335, + "dislikes": 180, + "hints": "The ants change their way when they meet is equivalent to continue moving without changing their direction. Answer is the max distance for one ant to reach the end of the plank in the facing direction.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 4, left = [4,3], right = [0,1]", + "expected_output": "4", + "explanation": "In the image above:\n-The ant at index 0 is named A and going to the right.\n-The ant at index 1 is named B and going to the right.\n-The ant at index 3 is named C and going to the left.\n-The ant at index 4 is named D and going to the left.\nThe last moment when an ant was on the plank is t = 4 seconds. After that, it falls immediately out of the plank. (i.e., We can say that at t = 4.0000000001, there are no ants on the plank)." + }, + { + "example_num": 2, + "expected_input": "n = 7, left = [], right = [0,1,2,3,4,5,6,7]", + "expected_output": "7", + "explanation": "All ants are going to the right, the ant at index 0 needs 7 seconds to fall." + }, + { + "example_num": 3, + "expected_input": "n = 7, left = [0,1,2,3,4,5,6,7], right = []", + "expected_output": "7", + "explanation": "All ants are going to the left, the ant at index 7 needs 7 seconds to fall." + } + ], + "solution": "/**\n * @param {number} n\n * @param {number[]} left\n * @param {number[]} right\n * @return {number}\n */\nvar getLastMoment = function(n, left, right) {\n left.sort(function(a,b){return a-b});\n right.sort(function(a,b){return a-b});\n if(left.length == 0){\n return n-right[0];\n }\n if(right.length == 0){\n return left[left.length-1];\n }\n return Math.max(left[left.length-1], n-right[0])\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720dda", + "questionid": 783, + "title": "Count Submatrices With All Ones", + "slug": "count-submatrices-with-all-ones", + "description": "Given an m x n binary matrix mat, return the number of submatrices that have all ones. ", + "category": [ + "Array", + "Dynamic Programming", + "Stack", + "Matrix", + "Monotonic Stack" + ], + "complexity": "Medium", + "successrate": 58.6, + "totalsubmissions": 59639, + "totalaccepted": 34967, + "likes": 1499, + "dislikes": 116, + "hints": "For each row i, create an array nums where: if mat[i][j] == 0 then nums[j] = 0 else nums[j] = nums[j-1] +1. In the row i, number of rectangles between column j and k(inclusive) and ends in row i, is equal to SUM(min(nums[j, .. idx])) where idx go from j to k. Expected solution is O(n^3).", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "mat = [[1,0,1],[1,1,0],[1,1,0]]", + "expected_output": "13", + "explanation": "There are 6 rectangles of side 1x1.\nThere are 2 rectangles of side 1x2.\nThere are 3 rectangles of side 2x1.\nThere is 1 rectangle of side 2x2. \nThere is 1 rectangle of side 3x1.\nTotal number of rectangles = 6 + 2 + 3 + 1 + 1 = 13." + }, + { + "example_num": 2, + "expected_input": "mat = [[0,1,1,0],[0,1,1,1],[1,1,1,0]]", + "expected_output": "24", + "explanation": "There are 8 rectangles of side 1x1.\nThere are 5 rectangles of side 1x2.\nThere are 2 rectangles of side 1x3. \nThere are 4 rectangles of side 2x1.\nThere are 2 rectangles of side 2x2. \nThere are 2 rectangles of side 3x1. \nThere is 1 rectangle of side 3x2. \nTotal number of rectangles = 8 + 5 + 2 + 4 + 2 + 2 + 1 = 24." + } + ], + "solution": "/**\n * @param {number[][]} mat\n * @return {number}\n */\nconst numSubmat = function(mat) {\n let m = mat.length\n let n = mat[0].length\n let res = 0\n let height = Array(n).fill(0)\n for (let i = 0; i < m; i++) {\n let st = []\n for (let j = 0; j < n; j++) {\n if (mat[i][j] == 1) {\n height[j]++\n } else {\n height[j] = 0\n }\n let sum = 0\n while (st.length != 0) {\n if (height[st[st.length - 1][0]] < height[j]) break\n st.pop()\n }\n if (st.length != 0) {\n sum += height[j] * (j - st[st.length - 1][0]) + st[st.length - 1][1]\n } else {\n sum += height[j] * (j + 1)\n }\n st.push([j, sum])\n res += sum\n }\n }\n return res\n\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720ddf", + "questionid": 788, + "title": "Minimum Number of Increments on Subarrays to Form a Target Array", + "slug": "minimum-number-of-increments-on-subarrays-to-form-a-target-array", + "description": "You are given an integer array target. You have an integer array initial of the same size as target with all elements initially zeros. In one operation you can choose any subarray from initial and increment each value by one. Return the minimum number of operations to form a target array from initial. The test cases are generated so that the answer fits in a 32-bit integer. ", + "category": [ + "Array", + "Dynamic Programming", + "Stack", + "Greedy", + "Monotonic Stack" + ], + "complexity": "Hard", + "successrate": 68, + "totalsubmissions": 35423, + "totalaccepted": 24071, + "likes": 849, + "dislikes": 52, + "hints": "For a given range of values in target, an optimal strategy is to increment the entire range by the minimum value. The minimum in a range could be obtained with Range minimum query or Segment trees algorithm.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "target = [1,2,3,2,1]", + "expected_output": "3", + "explanation": "We need at least 3 operations to form the target array from the initial array.\n[0,0,0,0,0] increment 1 from index 0 to 4 (inclusive).\n[1,1,1,1,1] increment 1 from index 1 to 3 (inclusive).\n[1,2,2,2,1] increment 1 at index 2.\n[1,2,3,2,1] target array is formed." + }, + { + "example_num": 2, + "expected_input": "target = [3,1,1,2]", + "expected_output": "4", + "explanation": "[0,0,0,0] -> [1,1,1,1] -> [1,1,1,2] -> [2,1,1,2] -> [3,1,1,2]" + }, + { + "example_num": 3, + "expected_input": "target = [3,1,5,4,2]", + "expected_output": "7", + "explanation": "[0,0,0,0,0] -> [1,1,1,1,1] -> [2,1,1,1,1] -> [3,1,1,1,1] -> [3,1,2,2,2] -> [3,1,3,3,2] -> [3,1,4,4,2] -> [3,1,5,4,2]." + } + ], + "solution": "/**\n * @param {number[]} target\n * @return {number}\n */\nconst minNumberOperations = function(target) {\n let res = target[0]\n \n for(let i = 1; i < target.length; i++) {\n res += Math.max(0, target[i] - target[i - 1])\n }\n \n return res\n}\n\n// another\n\n/**\n * @param {number[]} target\n * @return {number}\n */\nconst minNumberOperations = function(target) {\n let totalOperations = target[0];\n for (let i = 1; i < target.length; ++i) {\n if (target[i] > target[i-1]) {\n totalOperations += target[i] - target[i-1];\n }\n }\n return totalOperations;\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720de3", + "questionid": 792, + "title": "Water Bottles", + "slug": "water-bottles", + "description": "There are numBottles water bottles that are initially full of water. You can exchange numExchange empty water bottles from the market with one full water bottle. The operation of drinking a full water bottle turns it into an empty bottle. Given the two integers numBottles and numExchange, return the maximum number of water bottles you can drink. ", + "category": [ + "Math", + "Simulation" + ], + "complexity": "Easy", + "successrate": 60.4, + "totalsubmissions": 80287, + "totalaccepted": 48484, + "likes": 667, + "dislikes": 54, + "hints": "Simulate the process until there are not enough empty bottles for even one full bottle of water.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "numBottles = 9, numExchange = 3", + "expected_output": "13", + "explanation": "You can exchange 3 empty bottles to get 1 full water bottle.\nNumber of water bottles you can drink: 9 + 3 + 1 = 13." + }, + { + "example_num": 2, + "expected_input": "numBottles = 15, numExchange = 4", + "expected_output": "19", + "explanation": "You can exchange 4 empty bottles to get 1 full water bottle. \nNumber of water bottles you can drink: 15 + 3 + 1 = 19." + } + ], + "solution": null + }, + { + "_id": "66f925ddfdfb8e1665720de4", + "questionid": 793, + "title": "Number of Nodes in the Sub-Tree With the Same Label", + "slug": "number-of-nodes-in-the-sub-tree-with-the-same-label", + "description": "You are given a tree (i.e. a connected, undirected graph that has no cycles) consisting of n nodes numbered from 0 to n - 1 and exactly n - 1 edges. The root of the tree is the node 0, and each node of the tree has a label which is a lower-case character given in the string labels (i.e. The node with the number i has the label labels[i]). The edges array is given on the form edges[i] = [ai, bi], which means there is an edge between nodes ai and bi in the tree. Return an array of size n where ans[i] is the number of nodes in the subtree of the ith node which have the same label as node i. A subtree of a tree T is the tree consisting of a node in T and all of its descendant nodes. ", + "category": [ + "Hash Table", + "Tree", + "Depth-First Search", + "Breadth-First Search", + "Counting" + ], + "complexity": "Medium", + "successrate": 39.8, + "totalsubmissions": 41122, + "totalaccepted": 16365, + "likes": 379, + "dislikes": 357, + "hints": "Start traversing the tree and each node should return a vector to its parent node. The vector should be of length 26 and have the count of all the labels in the sub-tree of this node.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], labels = "abaedcd"", + "expected_output": "[2,1,1,1,1,1,1]", + "explanation": "Node 0 has label 'a' and its sub-tree has node 2 with label 'a' as well, thus the answer is 2. Notice that any node is part of its sub-tree.\nNode 1 has a label 'b'. The sub-tree of node 1 contains nodes 1,4 and 5, as nodes 4 and 5 have different labels than node 1, the answer is just 1 (the node itself)." + }, + { + "example_num": 2, + "expected_input": "n = 4, edges = [[0,1],[1,2],[0,3]], labels = "bbbb"", + "expected_output": "[4,2,1,1]", + "explanation": "The sub-tree of node 2 contains only node 2, so the answer is 1.\nThe sub-tree of node 3 contains only node 3, so the answer is 1.\nThe sub-tree of node 1 contains nodes 1 and 2, both have label 'b', thus the answer is 2.\nThe sub-tree of node 0 contains nodes 0, 1, 2 and 3, all with label 'b', thus the answer is 4." + }, + { + "example_num": 3, + "expected_input": "n = 5, edges = [[0,1],[0,2],[1,3],[0,4]], labels = "aabab"", + "expected_output": "[3,2,1,1,1]", + "explanation": "" + } + ], + "solution": null + }, + { + "_id": "66f925ddfdfb8e1665720de8", + "questionid": 797, + "title": "Shuffle String", + "slug": "shuffle-string", + "description": "You are given a string s and an integer array indices of the same length. The string s will be shuffled such that the character at the ith position moves to indices[i] in the shuffled string. Return the shuffled string. ", + "category": [ + "Array", + "String" + ], + "complexity": "Easy", + "successrate": 85.8, + "totalsubmissions": 230975, + "totalaccepted": 198080, + "likes": 1333, + "dislikes": 248, + "hints": "You can create an auxiliary string t of length n. Assign t[indexes[i]] to s[i] for each i from 0 to n-1.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "codeleet", indices = [4,5,6,7,0,2,1,3]", + "expected_output": ""leetcode"", + "explanation": "As shown, "codeleet" becomes "leetcode" after shuffling." + }, + { + "example_num": 2, + "expected_input": "s = "abc", indices = [0,1,2]", + "expected_output": ""abc"", + "explanation": "After shuffling, each character remains in its position." + } + ], + "solution": "/**\n * @param {string} s\n * @param {number[]} indices\n * @return {string}\n */\nconst restoreString = function(s, indices) {\n const n = s.length\n const arr = Array(n)\n for(let i = 0; i < n; i++) {\n arr[indices[i]] = s[i]\n }\n return arr.join('')\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720dea", + "questionid": 799, + "title": "Number of Good Leaf Nodes Pairs", + "slug": "number-of-good-leaf-nodes-pairs", + "description": "You are given the root of a binary tree and an integer distance. A pair of two different leaf nodes of a binary tree is said to be good if the length of the shortest path between them is less than or equal to distance. Return the number of good leaf node pairs in the tree. ", + "category": [ + "Tree", + "Depth-First Search", + "Binary Tree" + ], + "complexity": "Medium", + "successrate": 59.6, + "totalsubmissions": 42009, + "totalaccepted": 25053, + "likes": 1069, + "dislikes": 21, + "hints": "Start DFS from each leaf node. stop the DFS when the number of steps done > distance. If you reach another leaf node within distance steps, add 1 to the answer. Note that all pairs will be counted twice so divide the answer by 2.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "root = [1,2,3,null,4], distance = 3", + "expected_output": "1", + "explanation": "The leaf nodes of the tree are 3 and 4 and the length of the shortest path between them is 3. This is the only good pair." + }, + { + "example_num": 2, + "expected_input": "root = [1,2,3,4,5,6,7], distance = 3", + "expected_output": "2", + "explanation": "The good pairs are [4,5] and [6,7] with shortest path = 2. The pair [4,6] is not good because the length of ther shortest path between them is 4." + }, + { + "example_num": 3, + "expected_input": "root = [7,1,4,6,null,5,3,null,null,null,null,null,2], distance = 3", + "expected_output": "1", + "explanation": "The only good pair is [2,5]." + } + ], + "solution": "/**\n * Definition for a binary tree node.\n * function TreeNode(val, left, right) {\n * this.val = (val===undefined ? 0 : val)\n * this.left = (left===undefined ? null : left)\n * this.right = (right===undefined ? null : right)\n * }\n */\n/**\n * @param {TreeNode} root\n * @param {number} distance\n * @return {number}\n */\nconst countPairs = function(root, distance) {\n let res = 0\n traverse(root)\n return res\n \n \n function traverse(node) {\n if(node == null) return []\n if(node.left == null && node.right == null) return [0]\n \n const left = traverse(node.left)\n const right = traverse(node.right)\n for(let i = 0; i < left.length; i++) {\n for(let j = 0; j < right.length; j++) {\n if(left[i] + right[j] + 2 <= distance) res++\n }\n }\n \n return [...left.map(e => e + 1), ...right.map(e => e + 1)]\n }\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720deb", + "questionid": 800, + "title": "Find the Winner of an Array Game", + "slug": "find-the-winner-of-an-array-game", + "description": "Given an integer array arr of distinct integers and an integer k. A game will be played between the first two elements of the array (i.e. arr[0] and arr[1]). In each round of the game, we compare arr[0] with arr[1], the larger integer wins and remains at position 0, and the smaller integer moves to the end of the array. The game ends when an integer wins k consecutive rounds. Return the integer which will win the game. It is guaranteed that there will be a winner of the game. ", + "category": [ + "Array", + "Simulation" + ], + "complexity": "Medium", + "successrate": 48.8, + "totalsubmissions": 49686, + "totalaccepted": 24246, + "likes": 449, + "dislikes": 25, + "hints": "If k \u2030\u00a5 arr.length return the max element of the array. If k < arr.length simulate the game until a number wins k consecutive games.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "arr = [2,1,3,5,4,6,7], k = 2", + "expected_output": "5", + "explanation": "Let's see the rounds of the game:\nRound | arr | winner | win_count\n 1 | [2,1,3,5,4,6,7] | 2 | 1\n 2 | [2,3,5,4,6,7,1] | 3 | 1\n 3 | [3,5,4,6,7,1,2] | 5 | 1\n 4 | [5,4,6,7,1,2,3] | 5 | 2\nSo we can see that 4 rounds will be played and 5 is the winner because it wins 2 consecutive games." + }, + { + "example_num": 2, + "expected_input": "arr = [3,2,1], k = 10", + "expected_output": "3", + "explanation": "3 will win the first 10 rounds consecutively." + } + ], + "solution": null + }, + { + "_id": "66f925ddfdfb8e1665720dfb", + "questionid": 816, + "title": "Maximum Length of Subarray With Positive Product", + "slug": "maximum-length-of-subarray-with-positive-product", + "description": "Given an array of integers nums, find the maximum length of a subarray where the product of all its elements is positive. A subarray of an array is a consecutive sequence of zero or more values taken out of that array. Return the maximum length of a subarray with positive product. ", + "category": [ + "Array", + "Dynamic Programming", + "Greedy" + ], + "complexity": "Medium", + "successrate": 42.9, + "totalsubmissions": 104080, + "totalaccepted": 44627, + "likes": 1312, + "dislikes": 23, + "hints": "Split the whole array into subarrays by zeroes since a subarray with positive product cannot contain any zero. If the subarray has even number of negative numbers, the whole subarray has positive product. Otherwise, we have two choices, either - remove the prefix till the first negative element in this subarray, or remove the suffix starting from the last negative element in this subarray.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,-2,-3,4]", + "expected_output": "4", + "explanation": "The array nums already has a positive product of 24." + }, + { + "example_num": 2, + "expected_input": "nums = [0,1,-2,-3,-4]", + "expected_output": "3", + "explanation": "The longest subarray with positive product is [1,-2,-3] which has a product of 6.\nNotice that we cannot include 0 in the subarray since that'll make the product 0 which is not positive." + }, + { + "example_num": 3, + "expected_input": "nums = [-1,-2,-3,0,1]", + "expected_output": "2", + "explanation": "The longest subarray with positive product is [-1,-2] or [-2,-3]." + } + ], + "solution": "/**\n * @param {number[]} nums\n * @return {number}\n */\nconst getMaxLen = function(nums) {\n let res = 0, zeroIdx = -1, negIdx = -1, count = 0\n for(let i = 0, len = nums.length; i < len; i++) {\n if(nums[i] < 0) {\n count++\n if(negIdx === -1) negIdx = i\n }\n if(nums[i] === 0) {\n count = 0\n negIdx = -1\n zeroIdx = i\n } else {\n if(count % 2 === 0) res = Math.max(res, i - zeroIdx)\n else res = Math.max(res, i - negIdx)\n }\n }\n \n return res\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720dfd", + "questionid": 818, + "title": "Number of Ways to Reorder Array to Get Same BST", + "slug": "number-of-ways-to-reorder-array-to-get-same-bst", + "description": "Given an array nums that represents a permutation of integers from 1 to n. We are going to construct a binary search tree (BST) by inserting the elements of nums in order into an initially empty BST. Find the number of different ways to reorder nums so that the constructed BST is identical to that formed from the original array nums. Return the number of ways to reorder nums such that the BST formed is identical to the original BST formed from nums. Since the answer may be very large, return it modulo 109 + 7. ", + "category": [ + "Array", + "Math", + "Divide and Conquer", + "Dynamic Programming", + "Tree", + "Union Find", + "Binary Search Tree", + "Memoization", + "Combinatorics", + "Binary Tree" + ], + "complexity": "Hard", + "successrate": 49.2, + "totalsubmissions": 19046, + "totalaccepted": 9367, + "likes": 397, + "dislikes": 43, + "hints": "Use a divide and conquer strategy. The first number will always be the root. Consider the numbers smaller and larger than the root separately. When merging the results together, how many ways can you order x elements in x+y positions?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [2,1,3]", + "expected_output": "1", + "explanation": "We can reorder nums to be [2,3,1] which will yield the same BST. There are no other ways to reorder nums which will yield the same BST." + }, + { + "example_num": 2, + "expected_input": "nums = [3,4,5,1,2]", + "expected_output": "5", + "explanation": "The following 5 arrays will yield the same BST: \n[3,1,2,4,5]\n[3,1,4,2,5]\n[3,1,4,5,2]\n[3,4,1,2,5]\n[3,4,1,5,2]" + }, + { + "example_num": 3, + "expected_input": "nums = [1,2,3]", + "expected_output": "0", + "explanation": "There are no other orderings of nums that will yield the same BST." + } + ], + "solution": "/**\n * @param {number[]} nums\n * @return {number}\n */\nconst numOfWays = function (nums) {\n let root = null\n let cache = new Map()\n\n const MOD = BigInt(10 ** 9 + 7)\n for (let n of nums) {\n root = insert(root, n)\n }\n\n // f(root) -> [length, combination]\n function f(root) {\n if (!root.left && !root.right) {\n return [1n, 1n]\n }\n let [ll, lc] = [0n, 1n]\n let [rl, rc] = [0n, 1n]\n if (root.left) {\n ;[ll, lc] = f(root.left)\n }\n if (root.right) {\n ;[rl, rc] = f(root.right)\n }\n // ((ll + rl)! / (ll! * rl!) )* lc * rc\n return [\n ll + rl + 1n,\n (factorial(ll + rl) / factorial(ll) / factorial(rl)) * lc * rc,\n ]\n }\n\n return (f(root)[1] - 1n) % MOD\n\n function Node(val) {\n this.val = val\n this.left = this.right = null\n }\n\n function insert(root, val) {\n if (!root) {\n return new Node(val)\n }\n if (root.val > val) {\n root.left = insert(root.left, val)\n } else if (root.val < val) {\n root.right = insert(root.right, val)\n }\n return root\n }\n\n function factorial(n) {\n if (n == 0n) {\n return 1n\n }\n if (cache.has(n)) {\n return cache.get(n)\n }\n let ans = 1n\n for (let i = 2n; i <= n; i++) {\n ans *= i\n cache.set(i, ans)\n }\n return ans\n }\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720e04", + "questionid": 825, + "title": "Find Valid Matrix Given Row and Column Sums", + "slug": "find-valid-matrix-given-row-and-column-sums", + "description": "You are given two arrays rowSum and colSum of non-negative integers where rowSum[i] is the sum of the elements in the ith row and colSum[j] is the sum of the elements of the jth column of a 2D matrix. In other words, you do not know the elements of the matrix, but you do know the sums of each row and column. Find any matrix of non-negative integers of size rowSum.length x colSum.length that satisfies the rowSum and colSum requirements. Return a 2D array representing any matrix that fulfills the requirements. It's guaranteed that at least one matrix that fulfills the requirements exists. ", + "category": [ + "Array", + "Greedy", + "Matrix" + ], + "complexity": "Medium", + "successrate": 78.3, + "totalsubmissions": 31857, + "totalaccepted": 24953, + "likes": 880, + "dislikes": 26, + "hints": "Find the smallest rowSum or colSum, and let it be x. Place that number in the grid, and subtract x from rowSum and colSum. Continue until all the sums are satisfied.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "rowSum = [3,8], colSum = [4,7]", + "expected_output": "[[3,0],\n [1,7]]", + "explanation": "0th row: 3 + 0 = 3 == rowSum[0]\n1st row: 1 + 7 = 8 == rowSum[1]\n0th column: 3 + 1 = 4 == colSum[0]\n1st column: 0 + 7 = 7 == colSum[1]\nThe row and column sums match, and all matrix elements are non-negative.\nAnother possible matrix is: [[1,2],\n [3,5]]" + }, + { + "example_num": 2, + "expected_input": "rowSum = [5,7,10], colSum = [8,6,8]", + "expected_output": "[[0,5,0],\n [6,1,0],\n [2,0,8]]", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} rowSum\n * @param {number[]} colSum\n * @return {number[][]}\n */\nconst restoreMatrix = function(rowSum, colSum) {\n const m = rowSum.length, n = colSum.length;\n const res = Array.from({ length: m }, () => Array(n).fill(0));\n for (let i = 0; i < m; ++i) {\n for (let j = 0 ; j < n; ++j) {\n res[i][j] = Math.min(rowSum[i], colSum[j]);\n rowSum[i] -= res[i][j];\n colSum[j] -= res[i][j];\n }\n }\n return res;\n};\n\n// another\n\n/**\n * @param {number[]} rowSum\n * @param {number[]} colSum\n * @return {number[][]}\n */\nconst restoreMatrix = function(rowSum, colSum) {\n const m = rowSum.length, n = colSum.length\n const res = Array.from({ length: m }, () => Array(n).fill(0))\n for(let i = 0; i < m; i++) {\n for(let j = 0; j < n; j++) {\n res[i][j] = Math.min(rowSum[i], colSum[j])\n rowSum[i] -= res[i][j]\n colSum[j] -= res[i][j]\n }\n }\n return res\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720e07", + "questionid": 828, + "title": "Maximum Non Negative Product in a Matrix", + "slug": "maximum-non-negative-product-in-a-matrix", + "description": "You are given a m x n matrix grid. Initially, you are located at the top-left corner (0, 0), and in each step, you can only move right or down in the matrix. Among all possible paths starting from the top-left corner (0, 0) and ending in the bottom-right corner (m - 1, n - 1), find the path with the maximum non-negative product. The product of a path is the product of all integers in the grid cells visited along the path. Return the maximum non-negative product modulo 109 + 7. If the maximum product is negative, return -1. Notice that the modulo is performed after getting the maximum product. ", + "category": [ + "Array", + "Dynamic Programming", + "Matrix" + ], + "complexity": "Medium", + "successrate": 33, + "totalsubmissions": 49057, + "totalaccepted": 16210, + "likes": 530, + "dislikes": 23, + "hints": "Use Dynamic programming. Keep the highest value and lowest value you can achieve up to a point.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "grid = [[-1,-2,-3],[-2,-3,-3],[-3,-3,-2]]", + "expected_output": "-1", + "explanation": "It is not possible to get non-negative product in the path from (0, 0) to (2, 2), so return -1." + }, + { + "example_num": 2, + "expected_input": "grid = [[1,-2,1],[1,-2,1],[3,-4,1]]", + "expected_output": "8", + "explanation": "Maximum non-negative product is shown (1 * 1 * -2 * -4 * 1 = 8)." + }, + { + "example_num": 3, + "expected_input": "grid = [[1,3],[0,-4]]", + "expected_output": "0", + "explanation": "Maximum non-negative product is shown (1 * 0 * -4 = 0)." + } + ], + "solution": "/**\n * @param {number[][]} grid\n * @return {number}\n */\nconst maxProductPath = function (grid) {\n const m = grid.length,\n n = grid[0].length,\n MOD = 1e9 + 7;\n const mx = Array.from({ length: m }, () => Array(n).fill(0));\n const mn = Array.from({ length: m }, () => Array(n).fill(0));\n mx[0][0] = mn[0][0] = grid[0][0];\n\n // initialize the top and left sides\n for (let i = 1; i < m; i++) {\n mn[i][0] = mx[i][0] = mx[i - 1][0] * grid[i][0];\n }\n for (let j = 1; j < n; j++) {\n mn[0][j] = mx[0][j] = mx[0][j - 1] * grid[0][j];\n }\n\n for (let i = 1; i < m; i++) {\n for (let j = 1; j < n; j++) {\n if (grid[i][j] < 0) {\n // smallest negative * negative number = largest\n mx[i][j] = Math.min(mn[i - 1][j], mn[i][j - 1]) * grid[i][j];\n mn[i][j] = Math.max(mx[i - 1][j], mx[i][j - 1]) * grid[i][j];\n } else {\n // largest product * positive number = largest\n mx[i][j] = Math.max(mx[i - 1][j], mx[i][j - 1]) * grid[i][j];\n mn[i][j] = Math.min(mn[i - 1][j], mn[i][j - 1]) * grid[i][j];\n }\n }\n }\n\n let ans = mx[m - 1][n - 1] % MOD;\n return ans < 0 ? -1 : ans;\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720e0a", + "questionid": 831, + "title": "Maximum Number of Achievable Transfer Requests", + "slug": "maximum-number-of-achievable-transfer-requests", + "description": "We have n buildings numbered from 0 to n - 1. Each building has a number of employees. It's transfer season, and some employees want to change the building they reside in. You are given an array requests where requests[i] = [fromi, toi] represents an employee's request to transfer from building fromi to building toi. All buildings are full, so a list of requests is achievable only if for each building, the net change in employee transfers is zero. This means the number of employees leaving is equal to the number of employees moving in. For example if n = 3 and two employees are leaving building 0, one is leaving building 1, and one is leaving building 2, there should be two employees moving to building 0, one employee moving to building 1, and one employee moving to building 2. Return the maximum number of achievable requests. ", + "category": [ + "Array", + "Backtracking", + "Bit Manipulation", + "Enumeration" + ], + "complexity": "Hard", + "successrate": 50.7, + "totalsubmissions": 15465, + "totalaccepted": 7841, + "likes": 217, + "dislikes": 26, + "hints": "Think brute force When is a subset of requests okay?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 5, requests = [[0,1],[1,0],[0,1],[1,2],[2,0],[3,4]]", + "expected_output": "5\nExplantion: Let's see the requests:\nFrom building 0 we have employees x and y and both want to move to building 1.\nFrom building 1 we have employees a and b and they want to move to buildings 2 and 0 respectively.\nFrom building 2 we have employee z and they want to move to building 0.\nFrom building 3 we have employee c and they want to move to building 4.\nFrom building 4 we don't have any requests.\nWe can achieve the requests of users x and b by swapping their places.\nWe can achieve the requests of users y, a and z by swapping the places in the 3 buildings.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "n = 3, requests = [[0,0],[1,2],[2,1]]", + "expected_output": "3\nExplantion: Let's see the requests:\nFrom building 0 we have employee x and they want to stay in the same building 0.\nFrom building 1 we have employee y and they want to move to building 2.\nFrom building 2 we have employee z and they want to move to building 1.\nWe can achieve all the requests.", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "n = 4, requests = [[0,3],[3,1],[1,2],[2,0]]", + "expected_output": "4", + "explanation": "" + } + ], + "solution": "// O(n * 2 ^ r) \n// r: number of requests\n/**\n * @param {number} n\n * @param {number[][]} requests\n * @return {number}\n */\nconst maximumRequests = function(n, requests) {\n const arr = Array(n).fill(0)\n let res = 0\n bt(requests, 0, arr, 0)\n return res\n function bt(r, idx, arr, num) {\n if(idx === r.length) {\n for(let i = 0; i < n; i++) {\n if(arr[i] !== 0) return\n }\n res = Math.max(res, num)\n return\n }\n const [from, to] = r[idx]\n arr[from]++\n arr[to]--\n bt(r, idx + 1, arr, num + 1)\n arr[from]--\n arr[to]++\n \n bt(r, idx + 1, arr, num)\n }\n};\n\n\n// another\n\n/**\n * @param {number} n\n * @param {number[][]} requests\n * @return {number}\n */\nconst maximumRequests = function (n, requests) {\n let max = 0\n helper(requests, 0, Array(n).fill(0), 0)\n return max\n\n function helper(requests, index, count, num) {\n // Traverse all n buildings to see if they are all 0. (means balanced)\n if (index === requests.length) {\n for (let i of count) {\n if (0 !== i) {\n return\n }\n }\n max = Math.max(max, num)\n return\n }\n // Choose this request\n count[requests[index][0]]++\n count[requests[index][1]]--\n helper(requests, index + 1, count, num + 1)\n count[requests[index][0]]--\n count[requests[index][1]]++\n\n // Not Choose the request\n helper(requests, index + 1, count, num)\n }\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720dd1", + "questionid": 774, + "title": "Range Sum of Sorted Subarray Sums", + "slug": "range-sum-of-sorted-subarray-sums", + "description": "You are given the array nums consisting of n positive integers. You computed the sum of all non-empty continuous subarrays from the array and then sorted them in non-decreasing order, creating a new array of n * (n + 1) / 2 numbers. Return the sum of the numbers from index left to index right (indexed from 1), inclusive, in the new array. Since the answer can be a huge number return it modulo 109 + 7. ", + "category": [ + "Array", + "Two Pointers", + "Binary Search", + "Sorting" + ], + "complexity": "Medium", + "successrate": 59.1, + "totalsubmissions": 41099, + "totalaccepted": 24279, + "likes": 560, + "dislikes": 102, + "hints": "Compute all sums and save it in array. Then just go from LEFT to RIGHT index and calculate answer modulo 1e9 + 7.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,2,3,4], n = 4, left = 1, right = 5", + "expected_output": "13", + "explanation": "All subarray sums are 1, 3, 6, 10, 2, 5, 9, 3, 7, 4. After sorting them in non-decreasing order we have the new array [1, 2, 3, 3, 4, 5, 6, 7, 9, 10]. The sum of the numbers from index le = 1 to ri = 5 is 1 + 2 + 3 + 3 + 4 = 13." + }, + { + "example_num": 2, + "expected_input": "nums = [1,2,3,4], n = 4, left = 3, right = 4", + "expected_output": "6", + "explanation": "The given array is the same as example 1. We have the new array [1, 2, 3, 3, 4, 5, 6, 7, 9, 10]. The sum of the numbers from index le = 3 to ri = 4 is 3 + 3 = 6." + }, + { + "example_num": 3, + "expected_input": "nums = [1,2,3,4], n = 4, left = 1, right = 10", + "expected_output": "50", + "explanation": "" + } + ], + "solution": null + }, + { + "_id": "66f925ddfdfb8e1665720de0", + "questionid": 789, + "title": "Number of Good Pairs", + "slug": "number-of-good-pairs", + "description": "Given an array of integers nums, return the number of good pairs. A pair (i, j) is called good if nums[i] == nums[j] and i < j. ", + "category": [ + "Array", + "Hash Table", + "Math", + "Counting" + ], + "complexity": "Easy", + "successrate": 87.9, + "totalsubmissions": 325449, + "totalaccepted": 286227, + "likes": 2366, + "dislikes": 141, + "hints": "Count how many times each number appears. If a number appears n times, then n * (n \u20ac\u201c 1) // 2 good pairs can be made with this number.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,2,3,1,1,3]", + "expected_output": "4", + "explanation": "There are 4 good pairs (0,3), (0,4), (3,4), (2,5) 0-indexed." + }, + { + "example_num": 2, + "expected_input": "nums = [1,1,1,1]", + "expected_output": "6", + "explanation": "Each pair in the array are good." + }, + { + "example_num": 3, + "expected_input": "nums = [1,2,3]", + "expected_output": "0", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} nums\n * @return {number}\n */\nconst numIdenticalPairs = function(nums) {\n let res = 0, count = Array(101).fill(0)\n for(let e of nums) {\n res += count[e]++\n }\n return res\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720de5", + "questionid": 794, + "title": "Find a Value of a Mysterious Function Closest to Target", + "slug": "find-a-value-of-a-mysterious-function-closest-to-target", + "description": " Winston was given the above mysterious function func. He has an integer array arr and an integer target and he wants to find the values l and r that make the value |func(arr, l, r) - target| minimum possible. Return the minimum possible value of |func(arr, l, r) - target|. Notice that func should be called with the values l and r where 0 <= l, r < arr.length. ", + "category": [ + "Array", + "Binary Search", + "Bit Manipulation", + "Segment Tree" + ], + "complexity": "Hard", + "successrate": 43.6, + "totalsubmissions": 16901, + "totalaccepted": 7361, + "likes": 260, + "dislikes": 10, + "hints": "If the and value of sub-array arr[i...j] is \u2030\u00a5 the and value of the sub-array arr[i...j+1]. For each index i using binary search or ternary search find the index j where |target - AND(arr[i...j])| is minimum, minimize this value with the global answer.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "arr = [9,12,3,7,15], target = 5", + "expected_output": "2", + "explanation": "Calling func with all the pairs of [l,r] = [[0,0],[1,1],[2,2],[3,3],[4,4],[0,1],[1,2],[2,3],[3,4],[0,2],[1,3],[2,4],[0,3],[1,4],[0,4]], Winston got the following results [9,12,3,7,15,8,0,3,7,0,0,3,0,0,0]. The value closest to 5 is 7 and 3, thus the minimum difference is 2." + }, + { + "example_num": 2, + "expected_input": "arr = [1000000,1000000,1000000], target = 1", + "expected_output": "999999", + "explanation": "Winston called the func with all possible values of [l,r] and he always got 1000000, thus the min difference is 999999." + }, + { + "example_num": 3, + "expected_input": "arr = [1,2,4,8,16], target = 0", + "expected_output": "0", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} arr\n * @param {number} target\n * @return {number}\n */\nconst closestToTarget = function (arr, target) {\n let res = Infinity\n let set = new Set()\n for (let i = 0; i < arr.length; i++) {\n const set2 = new Set()\n for (let j of set) {\n set2.add(j & arr[i])\n }\n set2.add(arr[i])\n for (let j of set2) {\n res = Math.min(res, Math.abs(j - target))\n }\n set = set2\n }\n return res\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720de6", + "questionid": 795, + "title": "Kth Missing Positive Number", + "slug": "kth-missing-positive-number", + "description": "Given an array arr\u00a0of positive integers\u00a0sorted in a strictly increasing order, and an integer k. Find the kth\u00a0positive integer that is missing from this array. ", + "category": [ + "Array", + "Binary Search" + ], + "complexity": "Easy", + "successrate": 55.5, + "totalsubmissions": 284961, + "totalaccepted": 158113, + "likes": 2359, + "dislikes": 172, + "hints": "Keep track of how many positive numbers are missing as you scan the array.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "arr = [2,3,4,7,11], k = 5", + "expected_output": "9\nExplanation: The missing positive integers are [1,5,6,8,9,10,12,13,...]. The 5th missing positive integer is 9.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "arr = [1,2,3,4], k = 2", + "expected_output": "6\nExplanation: The missing positive integers are [5,6,7,...]. The 2nd missing positive integer is 6.", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} arr\n * @param {number} k\n * @return {number}\n */\nconst findKthPositive = function(arr, k) {\n let l = 0, r = arr.length, m;\n while (l < r) {\n m = (l + r) >> 1;\n if (arr[m] - 1 - m < k) l = m + 1;\n else r = m;\n }\n return l + k;\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720df1", + "questionid": 806, + "title": "Minimum Operations to Make Array Equal", + "slug": "minimum-operations-to-make-array-equal", + "description": "You have an array arr of length n where arr[i] = (2 * i) + 1 for all valid values of i (i.e.,\u00a00 <= i < n). In one operation, you can select two indices x and y where 0 <= x, y < n and subtract 1 from arr[x] and add 1 to arr[y] (i.e., perform arr[x] -=1 and arr[y] += 1). The goal is to make all the elements of the array equal. It is guaranteed that all the elements of the array can be made equal using some operations. Given an integer n, the length of the array, return the minimum number of operations needed to make all the elements of arr equal. ", + "category": [ + "Math" + ], + "complexity": "Medium", + "successrate": 80.8, + "totalsubmissions": 80139, + "totalaccepted": 64778, + "likes": 785, + "dislikes": 135, + "hints": "Build the array arr using the given formula, define target = sum(arr) / n What is the number of operations needed to convert arr so that all elements equal target ?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 3", + "expected_output": "2", + "explanation": "arr = [1, 3, 5]\nFirst operation choose x = 2 and y = 0, this leads arr to be [2, 3, 4]\nIn the second operation choose x = 2 and y = 0 again, thus arr = [3, 3, 3]." + }, + { + "example_num": 2, + "expected_input": "n = 6", + "expected_output": "9", + "explanation": "" + } + ], + "solution": "/**\n * @param {number} n\n * @return {number}\n */\nvar minOperations = function(n) {\n let l = 1, r = 2 * (n - 1) + 1\n \n // [1, 3]\n // [1, 3, 5, 7]\n \n // [1]\n // [1, 3, 5]\n // [1, 3, 5, 7, 9]\n const target = l + (r - l) / 2\n let res = 0\n const num = ~~((n + 1) / 2)\n for(let i = 1; i <= num; i++) {\n res += target - (2 * (i -1) + 1)\n }\n \n return res\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720df2", + "questionid": 807, + "title": "Magnetic Force Between Two Balls", + "slug": "magnetic-force-between-two-balls", + "description": "In the universe Earth C-137, Rick discovered a special form of magnetic force between two balls if they are put in his new invented basket. Rick has n empty baskets, the ith basket is at position[i], Morty has m balls and needs to distribute the balls into the baskets such that the minimum magnetic force between any two balls is maximum. Rick stated that magnetic force between two different balls at positions x and y is |x - y|. Given the integer array position and the integer m. Return the required force. ", + "category": [ + "Array", + "Binary Search", + "Sorting" + ], + "complexity": "Medium", + "successrate": 54.5, + "totalsubmissions": 47462, + "totalaccepted": 25844, + "likes": 1106, + "dislikes": 78, + "hints": "If you can place balls such that the answer is x then you can do it for y where y < x. Similarly if you cannot place balls such that the answer is x then you can do it for y where y > x. Binary search on the answer and greedily see if it is possible.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "position = [1,2,3,4,7], m = 3", + "expected_output": "3", + "explanation": "Distributing the 3 balls into baskets 1, 4 and 7 will make the magnetic force between ball pairs [3, 3, 6]. The minimum magnetic force is 3. We cannot achieve a larger minimum magnetic force than 3." + }, + { + "example_num": 2, + "expected_input": "position = [5,4,3,2,1,1000000000], m = 2", + "expected_output": "999999999", + "explanation": "We can use baskets 1 and 1000000000." + } + ], + "solution": "/**\n * @param {number[]} position\n * @param {number} m\n * @return {number}\n */\nconst maxDistance = function(position, m) {\n position.sort((a, b) => a - b)\n const n = position.length\n let l = Infinity, r = 1\n for (let i = 1; i < n; i++) {\n if (position[i] - position[i - 1] < l) l = position[i] - position[i - 1]\n }\n r = position[n - 1] - position[0]\n while(l < r) {\n const mid = r - Math.floor((r - l) / 2)\n if(valid(mid)) l = mid\n else r = mid - 1\n }\n return l\n\n function valid(mid) {\n let res = 1, cur = 0\n for (let i = 1; i < n; i++) {\n const delta = position[i] - position[i - 1]\n cur += delta\n if (cur >= mid) {\n res++\n cur = 0\n }\n if(res === m) return true\n }\n return false\n }\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720df5", + "questionid": 810, + "title": "Shortest Subarray to be Removed to Make Array Sorted", + "slug": "shortest-subarray-to-be-removed-to-make-array-sorted", + "description": "Given an integer array arr, remove a subarray (can be empty) from arr such that the remaining elements in arr are non-decreasing. Return the length of the shortest subarray to remove. A subarray is a contiguous subsequence of the array. ", + "category": [ + "Array", + "Two Pointers", + "Binary Search", + "Stack", + "Monotonic Stack" + ], + "complexity": "Medium", + "successrate": 35.3, + "totalsubmissions": 50421, + "totalaccepted": 17815, + "likes": 959, + "dislikes": 29, + "hints": "The key is to find the longest non-decreasing subarray starting with the first element or ending with the last element, respectively. After removing some subarray, the result is the concatenation of a sorted prefix and a sorted suffix, where the last element of the prefix is smaller than the first element of the suffix.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "arr = [1,2,3,10,4,2,3,5]", + "expected_output": "3", + "explanation": "The shortest subarray we can remove is [10,4,2] of length 3. The remaining elements after that will be [1,2,3,3,5] which are sorted.\nAnother correct solution is to remove the subarray [3,10,4]." + }, + { + "example_num": 2, + "expected_input": "arr = [5,4,3,2,1]", + "expected_output": "4", + "explanation": "Since the array is strictly decreasing, we can only keep a single element. Therefore we need to remove a subarray of length 4, either [5,4,3,2] or [4,3,2,1]." + }, + { + "example_num": 3, + "expected_input": "arr = [1,2,3]", + "expected_output": "0", + "explanation": "The array is already non-decreasing. We do not need to remove any elements." + } + ], + "solution": "/**\n * @param {number[]} arr\n * @return {number}\n */\nconst findLengthOfShortestSubarray = function (arr) {\n const n = arr.length\n let left = 0\n for(let i = 0; i < n - 1; i++) {\n if(arr[i] > arr[i+ 1]) {\n break\n }\n left = i + 1\n }\n\n let right = n - 1\n for(let i = n - 1; i > 0; i--) {\n if(arr[i] < arr[i - 1]) {\n break\n }\n right = i - 1\n }\n // console.log(left, right)\n if(left === n - 1) return 0\n\n let res = Math.min(n - 1 - left, right)\n let l = 0, r = right\n while(l <= left && r < n) {\n if(arr[l] <= arr[r]) {\n res = Math.min(res, r - 1 - l)\n l++\n } else {\n r++\n }\n }\n\n return res\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720df6", + "questionid": 811, + "title": "Count All Possible Routes", + "slug": "count-all-possible-routes", + "description": "You are given an array of distinct positive integers locations where locations[i] represents the position of city i. You are also given integers start, finish and fuel representing the starting city, ending city, and the initial amount of fuel you have, respectively. At each step, if you are at city i, you can pick any city j such that j != i and 0 <= j < locations.length and move to city j. Moving from city i to city j reduces the amount of fuel you have by |locations[i] - locations[j]|. Please notice that |x| denotes the absolute value of x. Notice that fuel cannot become negative at any point in time, and that you are allowed to visit any city more than once (including start and finish). Return the count of all possible routes from start to finish. Since the answer may be too large, return it modulo 109 + 7. ", + "category": [ + "Array", + "Dynamic Programming", + "Memoization" + ], + "complexity": "Hard", + "successrate": 57.6, + "totalsubmissions": 16965, + "totalaccepted": 9767, + "likes": 351, + "dislikes": 18, + "hints": "Use dynamic programming to solve this problem with each state defined by the city index and fuel left. Since the array contains distinct integers fuel will always be spent in each move and so there can be no cycles.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "locations = [2,3,6,8,4], start = 1, finish = 3, fuel = 5", + "expected_output": "4", + "explanation": "The following are all possible routes, each uses 5 units of fuel:\n1 -> 3\n1 -> 2 -> 3\n1 -> 4 -> 3\n1 -> 4 -> 2 -> 3" + }, + { + "example_num": 2, + "expected_input": "locations = [4,3,1], start = 1, finish = 0, fuel = 6", + "expected_output": "5", + "explanation": "The following are all possible routes:\n1 -> 0, used fuel = 1\n1 -> 2 -> 0, used fuel = 5\n1 -> 2 -> 1 -> 0, used fuel = 5\n1 -> 0 -> 1 -> 0, used fuel = 3\n1 -> 0 -> 1 -> 0 -> 1 -> 0, used fuel = 5" + }, + { + "example_num": 3, + "expected_input": "locations = [5,2,1], start = 0, finish = 2, fuel = 3", + "expected_output": "0", + "explanation": "It is impossible to get from 0 to 2 using only 3 units of fuel since the shortest route needs 4 units of fuel." + } + ], + "solution": "/**\n * @param {number[]} locations\n * @param {number} start\n * @param {number} finish\n * @param {number} fuel\n * @return {number}\n */\nconst countRoutes = function (locations, start, finish, fuel) {\n const n = locations.length\n const mod = 10 ** 9 + 7\n const dp = Array.from({ length: n }, () => Array(fuel + 1).fill(-1))\n return solve(start, finish, fuel)\n function solve(curCity, e, fuel) {\n if (fuel < 0) return 0\n if (dp[curCity][fuel] !== -1) return dp[curCity][fuel]\n let ans = curCity === e ? 1 : 0\n for (let nextCity = 0; nextCity < locations.length; nextCity++) {\n if (nextCity !== curCity) {\n ans +=\n solve(\n nextCity,\n e,\n fuel - Math.abs(locations[curCity] - locations[nextCity])\n ) % mod\n }\n }\n return (dp[curCity][fuel] = ans % mod)\n }\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720df7", + "questionid": 812, + "title": "Most Visited Sector in a Circular Track", + "slug": "most-visited-sector-in-a-circular-track", + "description": "Given an integer n and an integer array rounds. We have a circular track which consists of n sectors labeled from 1 to n. A marathon will be held on this track, the marathon consists of m rounds. The ith round starts at sector rounds[i - 1] and ends at sector rounds[i]. For example, round 1 starts at sector rounds[0] and ends at sector rounds[1] Return an array of the most visited sectors sorted in ascending order. Notice that you circulate the track in ascending order of sector numbers in the counter-clockwise direction (See the first example). ", + "category": [ + "Array", + "Simulation" + ], + "complexity": "Easy", + "successrate": 58.1, + "totalsubmissions": 36263, + "totalaccepted": 21075, + "likes": 202, + "dislikes": 427, + "hints": "For each round increment the visits of the sectors visited during the marathon with 1. Determine the max number of visits, and return any sector visited the max number of visits.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 4, rounds = [1,3,1,2]", + "expected_output": "[1,2]", + "explanation": "The marathon starts at sector 1. The order of the visited sectors is as follows:\n1 --> 2 --> 3 (end of round 1) --> 4 --> 1 (end of round 2) --> 2 (end of round 3 and the marathon)\nWe can see that both sectors 1 and 2 are visited twice and they are the most visited sectors. Sectors 3 and 4 are visited only once." + }, + { + "example_num": 2, + "expected_input": "n = 2, rounds = [2,1,2,1,2,1,2,1,2]", + "expected_output": "[2]", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "n = 7, rounds = [1,3,5,7]", + "expected_output": "[1,2,3,4,5,6,7]", + "explanation": "" + } + ], + "solution": "/**\n * @param {number} n\n * @param {number[]} rounds\n * @return {number[]}\n */\nconst mostVisited = function(n, rounds) {\n const arr = Array(n + 1).fill(0)\n for(let i = 1, m = rounds.length; i < m; i++) {\n let start = rounds[i - 1], end = rounds[i]\n\n if(i == 1) arr[start]++\n while(start !== end) {\n start += 1\n if (start === n + 1) start = 1\n arr[start]++\n }\n }\n const max = Math.max(...arr)\n const res = []\n for(let i = 1; i <= n; i++) {\n if(arr[i] === max) res.push(i)\n }\n return res\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720dfc", + "questionid": 817, + "title": "Minimum Number of Days to Disconnect Island", + "slug": "minimum-number-of-days-to-disconnect-island", + "description": "You are given an m x n binary grid grid where 1 represents land and 0 represents water. An island is a maximal 4-directionally (horizontal or vertical) connected group of 1's. The grid is said to be connected if we have exactly one island, otherwise is said disconnected. In one day, we are allowed to change any single land cell (1) into a water cell (0). Return the minimum number of days to disconnect the grid. ", + "category": [ + "Array", + "Depth-First Search", + "Breadth-First Search", + "Matrix", + "Strongly Connected Component" + ], + "complexity": "Hard", + "successrate": 48.6, + "totalsubmissions": 16911, + "totalaccepted": 8223, + "likes": 377, + "dislikes": 121, + "hints": "Return 0 if the grid is already disconnected. Return 1 if changing a single land to water disconnect the island. Otherwise return 2. We can disconnect the grid within at most 2 days.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "grid = [[0,1,1,0],[0,1,1,0],[0,0,0,0]]", + "expected_output": "2", + "explanation": "We need at least 2 days to get a disconnected grid.\nChange land grid[1][1] and grid[0][2] to water and get 2 disconnected island." + }, + { + "example_num": 2, + "expected_input": "grid = [[1,1]]", + "expected_output": "2", + "explanation": "Grid of full water is also disconnected ([[1,1]] -> [[0,0]]), 0 islands." + } + ], + "solution": "/**\n * @param {number[][]} grid\n * @return {number}\n */\nconst minDays = function (grid) {\n if (!grid.length || !grid[0].length) return 0\n if (numIslands(grid) != 1) return 0\n for (let i = 0; i < grid.length; i++) {\n for (let j = 0; j < grid[0].length; j++) {\n if (grid[i][j] == 1) {\n grid[i][j] = 0\n if (numIslands(grid) != 1) return 1\n grid[i][j] = 1\n }\n }\n }\n return 2\n}\n\nfunction numIslands(grid) {\n let m = Array.from({ length: grid.length }, (v, i) => {\n return [...grid[i]]\n })\n let count = 0\n for (let i = 0; i < m.length; i++)\n for (let j = 0; j < m[0].length; j++) removeIslandAt(i, j, 1)\n return count\n function removeIslandAt(i, j, firstIteration = 0) {\n if (i >= m.length || j >= m[0].length || i < 0 || j < 0 || m[i][j] == 0)\n return\n m[i][j] = 0\n count += firstIteration\n removeIslandAt(i - 1, j)\n removeIslandAt(i + 1, j)\n removeIslandAt(i, j - 1)\n removeIslandAt(i, j + 1)\n }\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720e03", + "questionid": 824, + "title": "Special Positions in a Binary Matrix", + "slug": "special-positions-in-a-binary-matrix", + "description": "Given an m x n binary matrix mat, return the number of special positions in mat. A position (i, j) is called special if mat[i][j] == 1 and all other elements in row i and column j are 0 (rows and columns are 0-indexed). ", + "category": [ + "Array", + "Matrix" + ], + "complexity": "Easy", + "successrate": 65, + "totalsubmissions": 47176, + "totalaccepted": 30652, + "likes": 424, + "dislikes": 18, + "hints": "Keep track of 1s in each row and in each column. Then while iterating over matrix, if the current position is 1 and current row as well as current column contains exactly one occurrence of 1.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "mat = [[1,0,0],[0,0,1],[1,0,0]]", + "expected_output": "1", + "explanation": "(1, 2) is a special position because mat[1][2] == 1 and all other elements in row 1 and column 2 are 0." + }, + { + "example_num": 2, + "expected_input": "mat = [[1,0,0],[0,1,0],[0,0,1]]", + "expected_output": "3", + "explanation": "(0, 0), (1, 1) and (2, 2) are special positions." + } + ], + "solution": null + }, + { + "_id": "66f925ddfdfb8e1665720e06", + "questionid": 827, + "title": "Split a String Into the Max Number of Unique Substrings", + "slug": "split-a-string-into-the-max-number-of-unique-substrings", + "description": "Given a string\u00a0s,\u00a0return the maximum\u00a0number of unique substrings that the given string can be split into. You can split string\u00a0s into any list of\u00a0non-empty substrings, where the concatenation of the substrings forms the original string.\u00a0However, you must split the substrings such that all of them are unique. A substring is a contiguous sequence of characters within a string. ", + "category": [ + "Hash Table", + "String", + "Backtracking" + ], + "complexity": "Medium", + "successrate": 54.2, + "totalsubmissions": 37163, + "totalaccepted": 20134, + "likes": 545, + "dislikes": 24, + "hints": "Use a set to keep track of which substrings have been used already Try each possible substring at every position and backtrack if a complete split is not possible", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "ababccc"", + "expected_output": "5\nExplanation: One way to split maximally is ['a', 'b', 'ab', 'c', 'cc']. Splitting like ['a', 'b', 'a', 'b', 'c', 'cc'] is not valid as you have 'a' and 'b' multiple times.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "s = "aba"", + "expected_output": "2\nExplanation: One way to split maximally is ['a', 'ba'].", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "s = "aa"", + "expected_output": "1\nExplanation: It is impossible to split the string any further.", + "explanation": "" + } + ], + "solution": "/**\n * @param {string} s\n * @return {number}\n */\nconst maxUniqueSplit = function(s) {\n return bt(s, '', 0, new Set())\n};\n\nfunction bt(str, cur, idx, useds) {\n if(idx === str.length) return useds.size\n cur += str[idx]\n if(useds.has(cur)) return bt(str, cur, idx +1, useds)\n else {\n let ans = 0\n useds.add(cur)\n ans = Math.max(ans, bt(str, '', idx+1, useds))\n useds.delete(cur)\n ans = Math.max(ans, bt(str, cur, idx+1, useds))\n return ans\n }\n}\n\n// another\n\n/**\n * @param {string} s\n * @return {number}\n */\nconst maxUniqueSplit = function (s) {\n const N = s.length\n let ans = -1\n let curr = new Set()\n const backtrack = (pos) => {\n if (pos === N) {\n ans = Math.max(ans, curr.size)\n return\n }\n if (curr.size + (N - pos) <= ans) return\n for (let i = pos + 1; i <= N; i++) {\n const a = s.slice(pos, i)\n if (curr.has(a)) continue\n curr.add(a)\n backtrack(i)\n curr.delete(a)\n }\n }\n\n backtrack(0)\n return ans\n}\n\n" + }, + { + "_id": "66f925ddfdfb8e1665720e0b", + "questionid": 832, + "title": "Number of Sets of K Non-Overlapping Line Segments", + "slug": "number-of-sets-of-k-non-overlapping-line-segments", + "description": "Given n points on a 1-D plane, where the ith point (from 0 to n-1) is at x = i, find the number of ways we can draw exactly k non-overlapping line segments such that each segment covers two or more points. The endpoints of each segment must have integral coordinates. The k line segments do not have to cover all n points, and they are allowed to share endpoints. Return the number of ways we can draw k non-overlapping line segments. Since this number can be huge, return it modulo 109 + 7. ", + "category": [ + "Math", + "Dynamic Programming" + ], + "complexity": "Medium", + "successrate": 42.4, + "totalsubmissions": 15711, + "totalaccepted": 6668, + "likes": 317, + "dislikes": 35, + "hints": "Try to use dynamic programming where the current index and remaining number of line segments to form can describe any intermediate state. To make the computation of each state in constant time, we could add another flag to the state that indicates whether or not we are in the middle of placing a line (placed start point but no endpoint).", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 4, k = 2", + "expected_output": "5", + "explanation": "The two line segments are shown in red and blue.\nThe image above shows the 5 different ways {(0,2),(2,3)}, {(0,1),(1,3)}, {(0,1),(2,3)}, {(1,2),(2,3)}, {(0,1),(1,2)}." + }, + { + "example_num": 2, + "expected_input": "n = 3, k = 1", + "expected_output": "3", + "explanation": "The 3 ways are {(0,1)}, {(0,2)}, {(1,2)}." + }, + { + "example_num": 3, + "expected_input": "n = 30, k = 7", + "expected_output": "796297179", + "explanation": "The total number of possible ways to draw 7 line segments is 3796297200. Taking this number modulo 109 + 7 gives us 796297179." + } + ], + "solution": "/**\n * @param {number} n\n * @param {number} k\n * @return {number}\n */\nconst numberOfSets = function (n, k) {\n let res = BigInt(1)\n const mod = BigInt(10 ** 9 + 7)\n for (let i = 1; i < k * 2 + 1; i++) {\n res = res * BigInt(n + k - i)\n res = res / BigInt(i)\n }\n res = res % mod\n return res\n}\n\n// another\n\n/**\n * @param {number} n\n * @param {number} k\n * @return {number}\n */\nconst numberOfSets = function (n, k) {\n // dp[i][k] as: the number of ways to generate\n // k non-overlapping segments you can make using [0 ~ i].\n const dp = Array.from({ length: n }, () => Array(k + 1).fill(0))\n const MOD = 10 ** 9 + 7\n dp[1][1] = 1\n for (let i = 2; i < n; i++) dp[i][1] = ((i + 1) * i) / 2\n // sum[i][j] as: the number of ways to generate\n // j - 1 segments from i - 1 points.\n const sum = Array.from({ length: n }, () => Array(k + 1).fill(0))\n for (let i = 2; i < n; i++) {\n for (let j = 2; j <= k; j++) {\n if (j <= i) sum[i][j] = (sum[i - 1][j] + dp[i - 1][j - 1]) % MOD\n dp[i][j] = (sum[i][j] + dp[i - 1][j]) % MOD\n }\n }\n return dp[n - 1][k]\n}\n\n" + }, + { + "_id": "66f925ddfdfb8e1665720dce", + "questionid": 771, + "title": "XOR Operation in an Array", + "slug": "xor-operation-in-an-array", + "description": "You are given an integer n and an integer start. Define an array nums where nums[i] = start + 2 * i (0-indexed) and n == nums.length. Return the bitwise XOR of all elements of nums. ", + "category": [ + "Math", + "Bit Manipulation" + ], + "complexity": "Easy", + "successrate": 84.2, + "totalsubmissions": 141261, + "totalaccepted": 118966, + "likes": 796, + "dislikes": 281, + "hints": "Simulate the process, create an array nums and return the Bitwise XOR of all elements of it.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 5, start = 0", + "expected_output": "8", + "explanation": "Array nums is equal to [0, 2, 4, 6, 8] where (0 ^ 2 ^ 4 ^ 6 ^ 8) = 8.\nWhere "^" corresponds to bitwise XOR operator." + }, + { + "example_num": 2, + "expected_input": "n = 4, start = 3", + "expected_output": "8", + "explanation": "Array nums is equal to [3, 5, 7, 9] where (3 ^ 5 ^ 7 ^ 9) = 8." + } + ], + "solution": "/**\n * @param {number} n\n * @param {number} start\n * @return {number}\n */\nconst xorOperation = function(n, start) {\n const nums = []\n let i = 0\n while (i < n) {\n nums[i] = start + 2 * i\n i++\n }\n // console.log(nums)\n let res = nums[0]\n for(let i = 1; i < n; i++) res ^= nums[i]\n return res\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720dcf", + "questionid": 772, + "title": "Making File Names Unique", + "slug": "making-file-names-unique", + "description": "Given an array of strings names of size n. You will create n folders in your file system such that, at the ith minute, you will create a folder with the name names[i]. Since two files cannot have the same name, if you enter a folder name that was previously used, the system will have a suffix addition to its name in the form of (k), where, k is the smallest positive integer such that the obtained name remains unique. Return an array of strings of length n where ans[i] is the actual name the system will assign to the ith folder when you create it. ", + "category": [ + "Array", + "Hash Table", + "String" + ], + "complexity": "Medium", + "successrate": 34.8, + "totalsubmissions": 65871, + "totalaccepted": 22938, + "likes": 321, + "dislikes": 507, + "hints": "Keep a map of each name and the smallest valid integer that can be appended as a suffix to it. If the name is not present in the map, you can use it without adding any suffixes. If the name is present in the map, append the smallest proper suffix, and add the new name to the map.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "names = ["pes","fifa","gta","pes(2019)"]", + "expected_output": "["pes","fifa","gta","pes(2019)"]", + "explanation": "Let's see how the file system creates folder names:\n"pes" --> not assigned before, remains "pes"\n"fifa" --> not assigned before, remains "fifa"\n"gta" --> not assigned before, remains "gta"\n"pes(2019)" --> not assigned before, remains "pes(2019)"" + }, + { + "example_num": 2, + "expected_input": "names = ["gta","gta(1)","gta","avalon"]", + "expected_output": "["gta","gta(1)","gta(2)","avalon"]", + "explanation": "Let's see how the file system creates folder names:\n"gta" --> not assigned before, remains "gta"\n"gta(1)" --> not assigned before, remains "gta(1)"\n"gta" --> the name is reserved, system adds (k), since "gta(1)" is also reserved, systems put k = 2. it becomes "gta(2)"\n"avalon" --> not assigned before, remains "avalon"" + }, + { + "example_num": 3, + "expected_input": "names = ["onepiece","onepiece(1)","onepiece(2)","onepiece(3)","onepiece"]", + "expected_output": "["onepiece","onepiece(1)","onepiece(2)","onepiece(3)","onepiece(4)"]", + "explanation": "When the last folder is created, the smallest positive valid k is 4, and it becomes "onepiece(4)"." + } + ], + "solution": null + }, + { + "_id": "66f925ddfdfb8e1665720dd2", + "questionid": 775, + "title": "Minimum Difference Between Largest and Smallest Value in Three Moves", + "slug": "minimum-difference-between-largest-and-smallest-value-in-three-moves", + "description": "You are given an integer array nums. In one move, you can choose one element of nums and change it by any value. Return the minimum difference between the largest and smallest value of nums after performing at most three moves. ", + "category": [ + "Array", + "Greedy", + "Sorting" + ], + "complexity": "Medium", + "successrate": 55.5, + "totalsubmissions": 109003, + "totalaccepted": 60540, + "likes": 1058, + "dislikes": 147, + "hints": "The minimum difference possible is is obtained by removing 3 elements between the 3 smallest and 3 largest values in the array.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [5,3,2,4]", + "expected_output": "0", + "explanation": "We can make at most 3 moves.\nIn the first move, change 2 to 3. nums becomes [5,3,3,4].\nIn the second move, change 4 to 3. nums becomes [5,3,3,3].\nIn the third move, change 5 to 3. nums becomes [3,3,3,3].\nAfter performing 3 moves, the difference between the minimum and maximum is 3 - 3 = 0." + }, + { + "example_num": 2, + "expected_input": "nums = [1,5,0,10,14]", + "expected_output": "1", + "explanation": "We can make at most 3 moves.\nIn the first move, change 5 to 0. nums becomes [1,0,0,10,14].\nIn the second move, change 10 to 0. nums becomes [1,0,0,0,14].\nIn the third move, change 14 to 1. nums becomes [1,0,0,0,1].\nAfter performing 3 moves, the difference between the minimum and maximum is 1 - 0 = 1.\nIt can be shown that there is no way to make the difference 0 in 3 moves." + }, + { + "example_num": 3, + "expected_input": "nums = [3,100,20]", + "expected_output": "0", + "explanation": "We can make at most 3 moves.\nIn the first move, change 100 to 7. nums becomes [3,7,20].\nIn the second move, change 20 to 7. nums becomes [3,7,7].\nIn the third move, change 3 to 7. nums becomes [7,7,7].\nAfter performing 3 moves, the difference between the minimum and maximum is 7 - 7 = 0." + } + ], + "solution": "/**\n * @param {number[]} nums\n * @return {number}\n */\n const minDifference = function(nums) {\n let res = Infinity\n const n = nums.length\n if(n < 5) return 0\n nums.sort((a, b) => a - b)\n for(let i = 0; i < 4; i++) {\n res = Math.min(res, nums[n - 4 + i] - nums[i])\n }\n\n return res\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720dd6", + "questionid": 779, + "title": "Number of Subsequences That Satisfy the Given Sum Condition", + "slug": "number-of-subsequences-that-satisfy-the-given-sum-condition", + "description": "You are given an array of integers nums and an integer target. Return the number of non-empty subsequences of nums such that the sum of the minimum and maximum element on it is less or equal to target. Since the answer may be too large, return it modulo 109 + 7. ", + "category": [ + "Array", + "Two Pointers", + "Binary Search", + "Sorting" + ], + "complexity": "Medium", + "successrate": 39.1, + "totalsubmissions": 71143, + "totalaccepted": 27790, + "likes": 1105, + "dislikes": 104, + "hints": "Sort the array nums. Use two pointers approach: Given an index i (choose it as the minimum in a subsequence) find the maximum j where j \u2030\u00a5 i and nums[i] +nums[j] \u2030\u00a4 target. Count the number of subsequences.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [3,5,6,7], target = 9", + "expected_output": "4", + "explanation": "There are 4 subsequences that satisfy the condition.\n[3] -> Min value + max value <= target (3 + 3 <= 9)\n[3,5] -> (3 + 5 <= 9)\n[3,5,6] -> (3 + 6 <= 9)\n[3,6] -> (3 + 6 <= 9)" + }, + { + "example_num": 2, + "expected_input": "nums = [3,3,6,8], target = 10", + "expected_output": "6", + "explanation": "There are 6 subsequences that satisfy the condition. (nums can have repeated numbers).\n[3] , [3] , [3,3], [3,6] , [3,6] , [3,3,6]" + }, + { + "example_num": 3, + "expected_input": "nums = [2,3,3,4,6,7], target = 12", + "expected_output": "61", + "explanation": "There are 63 non-empty subsequences, two of them do not satisfy the condition ([6,7], [7]).\nNumber of valid subsequences (63 - 2 = 61)." + } + ], + "solution": "/**\n * @param {number[]} nums\n * @param {number} target\n * @return {number}\n */\nconst numSubseq = function(nums, target) {\n const n = nums.length, mod = 1e9 + 7\n const pows = Array(n).fill(1)\n for(let i = 1; i < n; i++) {\n pows[i] = pows[i - 1] * 2 % mod\n }\n let res = 0, l = 0, r = n - 1\n nums.sort((a, b) => a - b)\n while(l <= r) {\n if(nums[l] + nums[r] > target) r--\n else {\n res = (res + pows[r - l]) % mod\n l++\n }\n }\n \n return res\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720dd8", + "questionid": 781, + "title": "Can Make Arithmetic Progression From Sequence", + "slug": "can-make-arithmetic-progression-from-sequence", + "description": "A sequence of numbers is called an arithmetic progression if the difference between any two consecutive elements is the same. Given an array of numbers arr, return true if the array can be rearranged to form an arithmetic progression. Otherwise, return false. ", + "category": [ + "Array", + "Sorting" + ], + "complexity": "Easy", + "successrate": 69.8, + "totalsubmissions": 111412, + "totalaccepted": 77739, + "likes": 650, + "dislikes": 44, + "hints": "Consider that any valid arithmetic progression will be in sorted order. Sort the array, then check if the differences of all consecutive elements are equal.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "arr = [3,5,1]", + "expected_output": "true\nExplanation: We can reorder the elements as [1,3,5] or [5,3,1] with differences 2 and -2 respectively, between each consecutive elements.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "arr = [1,2,4]", + "expected_output": "false\nExplanation: There is no way to reorder the elements to obtain an arithmetic progression.", + "explanation": "" + } + ], + "solution": null + }, + { + "_id": "66f925ddfdfb8e1665720ddb", + "questionid": 784, + "title": "Minimum Possible Integer After at Most K Adjacent Swaps On Digits", + "slug": "minimum-possible-integer-after-at-most-k-adjacent-swaps-on-digits", + "description": "You are given a string num representing the digits of a very large integer and an integer k. You are allowed to swap any two adjacent digits of the integer at most k times. Return the minimum integer you can obtain also as a string. ", + "category": [ + "String", + "Greedy", + "Binary Indexed Tree", + "Segment Tree" + ], + "complexity": "Hard", + "successrate": 37.7, + "totalsubmissions": 19494, + "totalaccepted": 7347, + "likes": 310, + "dislikes": 20, + "hints": "We want to make the smaller digits the most significant digits in the number. For each index i, check the smallest digit in a window of size k and append it to the answer. Update the indices of all digits in this range accordingly.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "num = "4321", k = 4", + "expected_output": ""1342"", + "explanation": "The steps to obtain the minimum integer from 4321 with 4 adjacent swaps are shown." + }, + { + "example_num": 2, + "expected_input": "num = "100", k = 1", + "expected_output": ""010"", + "explanation": "It's ok for the output to have leading zeros, but the input is guaranteed not to have any leading zeros." + }, + { + "example_num": 3, + "expected_input": "num = "36789", k = 1000", + "expected_output": ""36789"", + "explanation": "We can keep the number without any swaps." + } + ], + "solution": "/**\n * @param {string} num\n * @param {number} k\n * @return {string}\n */\nconst minInteger = function (num, k) {\n const nums = num.split('')\n const len = nums.length\n const q = Array(10)\n .fill(null)\n .map(() => [])\n nums.forEach((n, i) => q[+n].push(i))\n const tree = new Fenwick(nums.length)\n for (let i = 1; i <= len; i++) tree.update(i, 1)\n let re = ''\n for (let i = 0; i < len; i++) {\n for (let j = 0; j <= 9; j++) {\n const idxArr = q[j]\n if (idxArr && idxArr.length) {\n const idx = idxArr[0]\n const num = tree.query(idx)\n if (num > k) continue\n k -= num\n idxArr.shift()\n tree.update(idx + 1, -1)\n re += j\n break\n }\n }\n }\n\n return re\n}\nclass Fenwick {\n constructor(n) {\n this.sums = new Array(n + 1).fill(0)\n }\n\n update(i, delta) {\n while (i < this.sums.length) {\n this.sums[i] += delta\n i += i & -i\n }\n }\n\n query(i) {\n let sum = 0\n while (i > 0) {\n sum += this.sums[i]\n i -= i & -i\n }\n return sum\n }\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720ddd", + "questionid": 786, + "title": "Number of Sub-arrays With Odd Sum", + "slug": "number-of-sub-arrays-with-odd-sum", + "description": "Given an array of integers arr, return the number of subarrays with an odd sum. Since the answer can be very large, return it modulo 109 + 7. ", + "category": [ + "Array", + "Math", + "Dynamic Programming", + "Prefix Sum" + ], + "complexity": "Medium", + "successrate": 43.5, + "totalsubmissions": 52460, + "totalaccepted": 22824, + "likes": 754, + "dislikes": 31, + "hints": "Can we use the accumulative sum to keep track of all the odd-sum sub-arrays ? if the current accu sum is odd, we care only about previous even accu sums and vice versa.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "arr = [1,3,5]", + "expected_output": "4", + "explanation": "All subarrays are [[1],[1,3],[1,3,5],[3],[3,5],[5]]\nAll sub-arrays sum are [1,4,9,3,8,5].\nOdd sums are [1,9,3,5] so the answer is 4." + }, + { + "example_num": 2, + "expected_input": "arr = [2,4,6]", + "expected_output": "0", + "explanation": "All subarrays are [[2],[2,4],[2,4,6],[4],[4,6],[6]]\nAll sub-arrays sum are [2,6,12,4,10,6].\nAll sub-arrays have even sum and the answer is 0." + }, + { + "example_num": 3, + "expected_input": "arr = [1,2,3,4,5,6,7]", + "expected_output": "16", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} arr\n * @return {number}\n */\nconst numOfSubarrays = function(arr) {\n const n = arr.length, mod = 1e9 + 7\n let sum = 0, res = 0, oddCnt = 0, evenCnt = 0\n \n for(let i = 0; i < n; i++) {\n const cur = arr[i]\n sum += cur\n if(sum % 2 === 1) {\n res++\n res += evenCnt\n oddCnt++\n } else {\n res += oddCnt\n evenCnt++\n }\n }\n \n return res % mod\n};\n\n// another\n\n/**\n * @param {number[]} arr\n * @return {number}\n */\nconst numOfSubarrays = function(arr) {\n const n = arr.length, mod = 1e9 + 7\n\n let oc = 0, ec = 1\n let sum = 0\n let res = 0\n for(let i = 0; i < n; i++) {\n sum += arr[i]\n if(sum % 2 === 1) {\n res += ec\n oc++\n } else {\n res += oc\n ec++\n }\n }\n \n return res % mod\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720dec", + "questionid": 801, + "title": "Minimum Swaps to Arrange a Binary Grid", + "slug": "minimum-swaps-to-arrange-a-binary-grid", + "description": "Given an n x n binary grid, in one step you can choose two adjacent rows of the grid and swap them. A grid is said to be valid if all the cells above the main diagonal are zeros. Return the minimum number of steps needed to make the grid valid, or -1 if the grid cannot be valid. The main diagonal of a grid is the diagonal that starts at cell (1, 1) and ends at cell (n, n). ", + "category": [ + "Array", + "Greedy", + "Matrix" + ], + "complexity": "Medium", + "successrate": 45.8, + "totalsubmissions": 24453, + "totalaccepted": 11191, + "likes": 421, + "dislikes": 59, + "hints": "For each row of the grid calculate the most right 1 in the grid in the array maxRight. To check if there exist answer, sort maxRight and check if maxRight[i] \u2030\u00a4 i for all possible i's. If there exist an answer, simulate the swaps.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "grid = [[0,0,1],[1,1,0],[1,0,0]]", + "expected_output": "3", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "grid = [[0,1,1,0],[0,1,1,0],[0,1,1,0],[0,1,1,0]]", + "expected_output": "-1", + "explanation": "All rows are similar, swaps have no effect on the grid." + }, + { + "example_num": 3, + "expected_input": "grid = [[1,0,0],[1,1,0],[1,1,1]]", + "expected_output": "0", + "explanation": "" + } + ], + "solution": null + }, + { + "_id": "66f925ddfdfb8e1665720def", + "questionid": 804, + "title": "Detect Cycles in 2D Grid", + "slug": "detect-cycles-in-2d-grid", + "description": "Given a 2D array of characters grid of size m x n, you need to find if there exists any cycle consisting of the same value in grid. A cycle is a path of length 4 or more in the grid that starts and ends at the same cell. From a given cell, you can move to one of the cells adjacent to it - in one of the four directions (up, down, left, or right), if it has the same value of the current cell. Also, you cannot move to the cell that you visited in your last move. For example, the cycle (1, 1) -> (1, 2) -> (1, 1) is invalid because from (1, 2) we visited (1, 1) which was the last visited cell. Return true if any cycle of the same value exists in grid, otherwise, return false. ", + "category": [ + "Array", + "Depth-First Search", + "Breadth-First Search", + "Union Find", + "Matrix" + ], + "complexity": "Medium", + "successrate": 47.9, + "totalsubmissions": 48472, + "totalaccepted": 23236, + "likes": 609, + "dislikes": 21, + "hints": "Keep track of the parent (previous position) to avoid considering an invalid path. Use DFS or BFS and keep track of visited cells to see if there is a cycle.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "grid = [["a","a","a","a"],["a","b","b","a"],["a","b","b","a"],["a","a","a","a"]]", + "expected_output": "true\nExplanation: There are two valid cycles shown in different colors in the image below:\n\"\"", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "grid = [["c","c","c","a"],["c","d","c","c"],["c","c","e","c"],["f","c","c","c"]]", + "expected_output": "true\nExplanation: There is only one valid cycle highlighted in the image below:\n\"\"", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "grid = [["a","b","b"],["b","z","b"],["b","b","a"]]", + "expected_output": "false", + "explanation": "" + } + ], + "solution": "/**\n * @param {character[][]} grid\n * @return {boolean}\n */\nconst containsCycle = function (grid) {\n const dirs = [\n [1, 0],\n [-1, 0],\n [0, 1],\n [0, -1],\n ]\n const rows = grid.length\n const cols = (grid[0] || []).length\n const vis = Array.from({ length: rows }, () => Array(cols).fill(false))\n let res = false\n const dfs = (i, j, prevR, prevC, char) => {\n vis[i][j] = true\n for (let d of dirs) {\n const r = i + d[0]\n const c = j + d[1]\n if (r >= 0 && r < rows && c >= 0 && c < cols) {\n if (!(r == prevR && c === prevC)) {\n if (grid[r][c] === char) {\n if (!vis[r][c]) {\n if (dfs(r, c, i, j, char)) return true\n } else {\n if (prevR !== -1 && prevC !== -1) return true\n }\n }\n }\n }\n }\n return false\n }\n\n for (let i = 0; i < rows; i++) {\n for (let j = 0; j < cols; j++) {\n if (!vis[i][j]) {\n res |= dfs(i, j, -1, -1, grid[i][j])\n }\n if (res) return true\n }\n }\n return res\n}\n\n// another\n\n/**\n * @param {character[][]} grid\n * @return {boolean}\n */\nconst containsCycle = function (grid) {\n const wholePath = (r, c, letter, component, last = [-1, -1]) => {\n const dirs = [\n [0, -1],\n [0, 1],\n [-1, 0],\n [1, 0],\n ]\n const tmp = grid[r][c]\n grid[r][c] = component\n const nextSteps = dirs\n .map((x) => [x[0] + r, x[1] + c])\n .filter(\n (x) =>\n x[0] >= 0 && x[0] < grid.length && x[1] >= 0 && x[1] < grid[0].length\n )\n for (let step of nextSteps) {\n if (step[0] === last[0] && last[1] === step[1]) {\n continue\n }\n if (grid[step[0]][step[1]] === component) {\n return true\n }\n if (grid[step[0]][step[1]] === letter) {\n let outcome = wholePath(step[0], step[1], letter, component, [r, c])\n if (outcome) {\n return true\n }\n }\n }\n return false\n }\n\n let component = 1\n for (let r = 0; r < grid.length; r++) {\n for (let c = 0; c < grid[0].length; c++) {\n const letter = grid[r][c]\n if (typeof letter === 'string') {\n grid[r][c] = component\n const outcome = wholePath(r, c, letter, component)\n if (outcome) {\n return true\n }\n component++\n }\n }\n }\n return false\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720df0", + "questionid": 805, + "title": "Find Longest Awesome Substring", + "slug": "find-longest-awesome-substring", + "description": "You are given a string s. An awesome substring is a non-empty substring of s such that we can make any number of swaps in order to make it a palindrome. Return the length of the maximum length awesome substring of s. ", + "category": [ + "Hash Table", + "String", + "Bit Manipulation" + ], + "complexity": "Hard", + "successrate": 40.7, + "totalsubmissions": 21634, + "totalaccepted": 8796, + "likes": 508, + "dislikes": 11, + "hints": "Given the character counts, under what conditions can a palindrome be formed ? From left to right, use bitwise xor-operation to compute for any prefix the number of times modulo 2 of each digit. (mask ^= (1<<(s[i]-'0')). Expected complexity is O(n*A) where A is the alphabet (10).", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "3242415"", + "expected_output": "5", + "explanation": ""24241" is the longest awesome substring, we can form the palindrome "24142" with some swaps." + }, + { + "example_num": 2, + "expected_input": "s = "12345678"", + "expected_output": "1", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "s = "213123"", + "expected_output": "6", + "explanation": ""213123" is the longest awesome substring, we can form the palindrome "231132" with some swaps." + } + ], + "solution": "/**\n * @param {string} s\n * @return {number}\n */\nconst longestAwesome = function(s) {\n const n = s.length, map = new Map(), {max} = Math\n let res = 0, mask = 0\n \n map.set(0, -1)\n for(let i = 0; i < n; i++) {\n const d = +s[i]\n mask ^= (1 << d)\n if(map.has(mask)) {\n res = max(res, i - map.get(mask))\n }\n\n for(let j = 0; j < 10; j++) {\n const tmp = mask ^ (1 << j)\n if(map.has(tmp)) {\n // console.log(i, map.get(tmp), tmp)\n res = max(res, i - map.get(tmp))\n }\n }\n\n if(!map.has(mask)) {\n map.set(mask, i)\n }\n }\n\n return res\n};\n\n// another\n\n/**\n * @param {string} s\n * @return {number}\n */\nconst longestAwesome = function (s) {\n const dp = new Array(1024).fill(s.length)\n let res = 0,\n mask = 0\n dp[0] = -1\n for (let i = 0; i < s.length; ++i) {\n mask ^= 1 << +s.charAt(i)\n res = Math.max(res, i - dp[mask])\n for (let j = 0; j <= 9; ++j) res = Math.max(res, i - dp[mask ^ (1 << j)])\n dp[mask] = Math.min(dp[mask], i)\n }\n return res\n}\n\n// another\n\n/**\n * @param {string} s\n * @return {number}\n */\nconst longestAwesome = function(s) {\n const n = s.length, { max, min } = Math\n const dp = Array(2 ** 10).fill(n)\n let res = 0, mask = 0\n dp[0] = -1\n for(let i = 0; i < n; i++) {\n mask ^= (1 << parseInt(s[i]))\n res = max(res, i - dp[mask])\n for(let j = 0; j <= 9; j++) {\n const tmp = mask ^ (1 << j)\n res = max(res, i - dp[tmp])\n }\n dp[mask] = min(i, dp[mask])\n }\n \n return res\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720df4", + "questionid": 809, + "title": "Number of Ways to Split a String", + "slug": "number-of-ways-to-split-a-string", + "description": "Given a binary string s, you can split s into 3 non-empty strings s1, s2, and s3 where s1 + s2 + s3 = s. Return the number of ways s can be split such that the number of ones is the same in s1, s2, and s3. Since the answer may be too large, return it modulo 109 + 7. ", + "category": [ + "Math", + "String" + ], + "complexity": "Medium", + "successrate": 32, + "totalsubmissions": 59777, + "totalaccepted": 19152, + "likes": 445, + "dislikes": 56, + "hints": "There is no way if the sum (number of '1's) is not divisible by the number of splits. So sum%3 should be 0. Preffix s1 , and suffix s3 should have sum/3 characters '1'. Follow up: Can you generalize the problem with numbers between [-10^9, 10^9] such the sum between subarrays s1, s2, s3 are the same?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "10101"", + "expected_output": "4", + "explanation": "There are four ways to split s in 3 parts where each part contain the same number of letters '1'.\n"1|010|1"\n"1|01|01"\n"10|10|1"\n"10|1|01"" + }, + { + "example_num": 2, + "expected_input": "s = "1001"", + "expected_output": "0", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "s = "0000"", + "expected_output": "3", + "explanation": "There are three ways to split s in 3 parts.\n"0|0|00"\n"0|00|0"\n"00|0|0"" + } + ], + "solution": "/**\n * @param {string} s\n * @return {number}\n */\nconst numWays = function(s) {\n const n = s.length\n const cnt = Array(n).fill(0)\n let num = 0\n for(let i = 0; i < n; i++) {\n if(s[i] === '1') num++\n cnt[i] = num\n }\n const mod = 1e9 + 7\n let i0 = -1, i1 = -1, i2 = -1, i3 = -1\n for(let i = 0; i < n; i++) {\n if(cnt[i] === num / 3) {\n if(i0 === -1) i0 = i1 = i\n else i1 = i\n } else if(cnt[i] === 2 * num / 3) {\n if(i2 === -1) i2 = i3 = i\n else i3 = i\n }\n }\n if(num === 0) return (n - 1) * (n - 2) / 2 % mod\n if(i0 === -1 || i1 === -1 || i2 === -1 || i3 === -1) return 0\n\n return (i1 - i0 + 1) * (i3 - i2 + 1) % mod\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720df8", + "questionid": 813, + "title": "Find Latest Group of Size M", + "slug": "find-latest-group-of-size-m", + "description": "Given an array arr that represents a permutation of numbers from 1 to n. You have a binary string of size n that initially has all its bits set to zero. At each step i (assuming both the binary string and arr are 1-indexed) from 1 to n, the bit at position arr[i] is set to 1. You are also given an integer m. Find the latest step at which there exists a group of ones of length m. A group of ones is a contiguous substring of 1's such that it cannot be extended in either direction. Return the latest step at which there exists a group of ones of length exactly m. If no such group exists, return -1. ", + "category": [ + "Array", + "Binary Search", + "Simulation" + ], + "complexity": "Medium", + "successrate": 40.7, + "totalsubmissions": 30264, + "totalaccepted": 12307, + "likes": 443, + "dislikes": 93, + "hints": "Since the problem asks for the latest step, can you start the searching from the end of arr? Use a map to store the current \u20ac\u01531\u20ac\u009d groups. At each step (going backwards) you need to split one group and update the map.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "arr = [3,5,1,2,4], m = 1", + "expected_output": "4", + "explanation": "Step 1: "00100", groups: ["1"]\nStep 2: "00101", groups: ["1", "1"]\nStep 3: "10101", groups: ["1", "1", "1"]\nStep 4: "11101", groups: ["111", "1"]\nStep 5: "11111", groups: ["11111"]\nThe latest step at which there exists a group of size 1 is step 4." + }, + { + "example_num": 2, + "expected_input": "arr = [3,1,5,4,2], m = 2", + "expected_output": "-1", + "explanation": "Step 1: "00100", groups: ["1"]\nStep 2: "10100", groups: ["1", "1"]\nStep 3: "10101", groups: ["1", "1", "1"]\nStep 4: "10111", groups: ["1", "111"]\nStep 5: "11111", groups: ["11111"]\nNo group of size 2 exists during any step." + } + ], + "solution": "/**\n * @param {number[]} arr\n * @param {number} m\n * @return {number}\n */\nconst findLatestStep = function(arr, m) {\n const uF = new UnionFind(arr);\n const mRecords = new Set(); // This contains parents whose rank is m \n const visited = new Set();\n let res = -1;\n\n for (let i = 0; i < arr.length; i++) {\n let val = arr[i];\n visited.add(val);\n \n if (visited.has(val - 1)) {\n let parent1 = uF.find(val);\n let parent2 = uF.find(val - 1);\n\t\t\t // Since merging, the rank for val - 1 & val has changed,\n // they are no longer m. Hence removed them from set.\n mRecords.delete(parent1); \n mRecords.delete(parent2);\n uF.union(val, val - 1);\n }\n \n if (visited.has(val + 1)) {\n let parent1 = uF.find(val);\n let parent2 = uF.find(val + 1);\n mRecords.delete(parent1);\n mRecords.delete(parent2);\n uF.union(val, val + 1);\n }\n \n let parent = uF.find(val);\n if (uF.ranks.get(parent) === m) mRecords.add(parent);\n if (mRecords.size > 0) res = i + 1; \n }\n \n return res; \n};\n\nclass UnionFind {\n constructor(arr) {\n [this.parents, this.ranks] = this.initialise(arr);\n }\n \n initialise(arr) {\n const parents = new Map();\n const ranks = new Map();\n arr.forEach(val => {\n parents.set(val, val);\n ranks.set(val, 1);\n })\n \n return [parents, ranks];\n }\n \n find(val) {\n if (this.parents.get(val) === val) return val;\n this.parents.set(val, this.find(this.parents.get(val)));\n return this.parents.get(val);\n }\n \n union(m, n) {\n const rootM = this.find(m);\n const rootN = this.find(n);\n \n if (rootM === rootN) return;\n if (rootM > rootN) {\n this.updateParent(rootN, rootM);\n } else {\n this.updateParent(rootM, rootN);\n }\n }\n \n updateParent(child, parent) {\n this.ranks.set(parent, this.ranks.get(parent) + this.ranks.get(child));\n this.parents.set(child, parent);\n }\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720df9", + "questionid": 814, + "title": "Stone Game V", + "slug": "stone-game-v", + "description": "There are several stones arranged in a row, and each stone has an associated value which is an integer given in the array stoneValue. In each round of the game, Alice divides the row into two non-empty rows (i.e. left row and right row), then Bob calculates the value of each row which is the sum of the values of all the stones in this row. Bob throws away the row which has the maximum value, and Alice's score increases by the value of the remaining row. If the value of the two rows are equal, Bob lets Alice decide which row will be thrown away. The next round starts with the remaining row. The game ends when there is only one stone remaining. Alice's is initially zero. Return the maximum score that Alice can obtain. ", + "category": [ + "Array", + "Math", + "Dynamic Programming", + "Game Theory" + ], + "complexity": "Hard", + "successrate": 40.9, + "totalsubmissions": 30952, + "totalaccepted": 12652, + "likes": 355, + "dislikes": 58, + "hints": "We need to try all possible divisions for the current row to get the max score. As calculating all possible divisions will lead us to calculate some sub-problems more than once, we need to think of dynamic programming.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "stoneValue = [6,2,3,4,5,5]", + "expected_output": "18", + "explanation": "In the first round, Alice divides the row to [6,2,3], [4,5,5]. The left row has the value 11 and the right row has value 14. Bob throws away the right row and Alice's score is now 11.\nIn the second round Alice divides the row to [6], [2,3]. This time Bob throws away the left row and Alice's score becomes 16 (11 + 5).\nThe last round Alice has only one choice to divide the row which is [2], [3]. Bob throws away the right row and Alice's score is now 18 (16 + 2). The game ends because only one stone is remaining in the row." + }, + { + "example_num": 2, + "expected_input": "stoneValue = [7,7,7,7,7,7,7]", + "expected_output": "28", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "stoneValue = [4]", + "expected_output": "0", + "explanation": "" + } + ], + "solution": null + }, + { + "_id": "66f925ddfdfb8e1665720dfa", + "questionid": 815, + "title": "Detect Pattern of Length M Repeated K or More Times", + "slug": "detect-pattern-of-length-m-repeated-k-or-more-times", + "description": "Given an array of positive integers arr, find a pattern of length m that is repeated k or more times. A pattern is a subarray (consecutive sub-sequence) that consists of one or more values, repeated multiple times consecutively without overlapping. A pattern is defined by its length and the number of repetitions. Return true if there exists a pattern of length m that is repeated k or more times, otherwise return false. ", + "category": [ + "Array", + "Enumeration" + ], + "complexity": "Easy", + "successrate": 43.5, + "totalsubmissions": 54950, + "totalaccepted": 23898, + "likes": 463, + "dislikes": 83, + "hints": "Use a three-layer loop to check all possible patterns by iterating through all possible starting positions, all indexes less than m, and if the character at the index is repeated k times.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "arr = [1,2,4,4,4,4], m = 1, k = 3", + "expected_output": "true\nExplanation: The pattern (4) of length 1 is repeated 4 consecutive times. Notice that pattern can be repeated k or more times but not less.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "arr = [1,2,1,2,1,1,1,3], m = 2, k = 2", + "expected_output": "true\nExplanation: The pattern (1,2) of length 2 is repeated 2 consecutive times. Another valid pattern (2,1) is also repeated 2 times.", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "arr = [1,2,1,2,1,3], m = 2, k = 3", + "expected_output": "false\nExplanation: The pattern (1,2) is of length 2 but is repeated only 2 times. There is no pattern of length 2 that is repeated 3 or more times.", + "explanation": "" + } + ], + "solution": null + }, + { + "_id": "66f925ddfdfb8e1665720e01", + "questionid": 822, + "title": "Replace All ?'s to Avoid Consecutive Repeating Characters", + "slug": "replace-all-s-to-avoid-consecutive-repeating-characters", + "description": "Given a string s containing only lowercase English letters and the '?' character, convert all the '?' characters into lowercase letters such that the final string does not contain any consecutive repeating characters. You cannot modify the non '?' characters. It is guaranteed that there are no consecutive repeating characters in the given string except for '?'. Return the final string after all the conversions (possibly zero) have been made. If there is more than one solution, return any of them. It can be shown that an answer is always possible with the given constraints. ", + "category": [ + "String" + ], + "complexity": "Easy", + "successrate": 49.8, + "totalsubmissions": 87583, + "totalaccepted": 43623, + "likes": 379, + "dislikes": 144, + "hints": "Processing string from left to right, whenever you get a \u20ac\u02dc?\u20ac\u2122, check left character and right character, and select a character not equal to either of them Do take care to compare with replaced occurrence of \u20ac\u02dc?\u20ac\u2122 when checking the left character.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "?zs"", + "expected_output": ""azs"", + "explanation": "There are 25 solutions for this problem. From "azs" to "yzs", all are valid. Only "z" is an invalid modification as the string will consist of consecutive repeating characters in "zzs"." + }, + { + "example_num": 2, + "expected_input": "s = "ubv?w"", + "expected_output": ""ubvaw"", + "explanation": "There are 24 solutions for this problem. Only "v" and "w" are invalid modifications as the strings will consist of consecutive repeating characters in "ubvvw" and "ubvww"." + } + ], + "solution": "/**\n * @param {string} s\n * @return {string}\n */\nconst modifyString = function(s) {\n const arr = s.split('')\n for(let i = 0, n = s.length; i < n; i++) {\n const cur = arr[i]\n if(cur === '?') {\n for(let j = 0, a = 'a'.charCodeAt(0); j < 26; j++) {\n const ch = String.fromCharCode(a + j)\n if(\n n === 1 ||\n (i === 0 && i < n - 1 && ch !== arr[i + 1]) ||\n (i > 0 && ch !== arr[i - 1] && i < n - 1 && ch !== arr[i + 1]) ||\n (i=== n -1 && i - 1 >= 0 && ch !== arr[i - 1])\n ) {\n \n arr[i] = ch\n break\n }\n }\n }\n }\n \n return arr.join('')\n};\n\n\n// another\n\n/**\n * @param {string} s\n * @return {string}\n */\nconst modifyString = function(s) {\n const arr = s.split('')\n for(let i = 0, n = s.length; i < n; i++) {\n const cur = arr[i]\n if(cur === '?') {\n for(let j = 0, a = 'a'.charCodeAt(0); j < 26; j++) {\n const ch = String.fromCharCode(a + j)\n if(\n (i === 0 || arr[i - 1] !== ch) &&\n (i === n - 1 || arr[i + 1] !== ch)\n ) {\n \n arr[i] = ch\n break\n }\n }\n }\n }\n \n return arr.join('')\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720e02", + "questionid": 823, + "title": "Minimum Time to Make Rope Colorful", + "slug": "minimum-time-to-make-rope-colorful", + "description": "Alice has n balloons arranged on a rope. You are given a 0-indexed string colors where colors[i] is the color of the ith balloon. Alice wants the rope to be colorful. She does not want two consecutive balloons to be of the same color, so she asks Bob for help. Bob can remove some balloons from the rope to make it colorful. You are given a 0-indexed integer array neededTime where neededTime[i] is the time (in seconds) that Bob needs to remove the ith balloon from the rope. Return the minimum time Bob needs to make the rope colorful. ", + "category": [ + "Array", + "String", + "Dynamic Programming", + "Greedy" + ], + "complexity": "Medium", + "successrate": 61.2, + "totalsubmissions": 98424, + "totalaccepted": 60218, + "likes": 971, + "dislikes": 40, + "hints": "Maintain the running sum and max value for repeated letters.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "colors = "abaac", neededTime = [1,2,3,4,5]", + "expected_output": "3", + "explanation": "In the above image, 'a' is blue, 'b' is red, and 'c' is green.\nBob can remove the blue balloon at index 2. This takes 3 seconds.\nThere are no longer two consecutive balloons of the same color. Total time = 3." + }, + { + "example_num": 2, + "expected_input": "colors = "abc", neededTime = [1,2,3]", + "expected_output": "0", + "explanation": "The rope is already colorful. Bob does not need to remove any balloons from the rope." + }, + { + "example_num": 3, + "expected_input": "colors = "aabaa", neededTime = [1,2,3,4,1]", + "expected_output": "2", + "explanation": "Bob will remove the balloons at indices 0 and 4. Each balloons takes 1 second to remove.\nThere are no longer two consecutive balloons of the same color. Total time = 1 + 1 = 2." + } + ], + "solution": null + }, + { + "_id": "66f925ddfdfb8e1665720e05", + "questionid": 826, + "title": "Rearrange Spaces Between Words", + "slug": "rearrange-spaces-between-words", + "description": "You are given a string text of words that are placed among some number of spaces. Each word consists of one or more lowercase English letters and are separated by at least one space. It's guaranteed that text contains at least one word. Rearrange the spaces so that there is an equal number of spaces between every pair of adjacent words and that number is maximized. If you cannot redistribute all the spaces equally, place the extra spaces at the end, meaning the returned string should be the same length as text. Return the string after rearranging the spaces. ", + "category": [ + "String" + ], + "complexity": "Easy", + "successrate": 44, + "totalsubmissions": 78867, + "totalaccepted": 34707, + "likes": 258, + "dislikes": 231, + "hints": "Count the total number of spaces and words. Then use the integer division to determine the numbers of spaces to add between each word and at the end.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "text = " this is a sentence "", + "expected_output": ""this is a sentence"", + "explanation": "There are a total of 9 spaces and 4 words. We can evenly divide the 9 spaces between the words: 9 / (4-1) = 3 spaces." + }, + { + "example_num": 2, + "expected_input": "text = " practice makes perfect"", + "expected_output": ""practice makes perfect "", + "explanation": "There are a total of 7 spaces and 3 words. 7 / (3-1) = 3 spaces plus 1 extra space. We place this extra space at the end of the string." + } + ], + "solution": "/**\n * @param {string} text\n * @return {string}\n */\nconst reorderSpaces = function(text) {\n let sc = 0\n for(let i = 0, len = text.length; i < len; i++) {\n if(text[i] === ' ') sc++\n }\n const arr = text.split(' ').filter(e => e!= '')\n const num = arr.length - 1\n const remain = num === 0 ? sc : sc % num\n const split = num === 0 ? 0 : Array( (sc / num) >> 0 ).fill(0).reduce((ac, el) => ac + ' ', '')\n let res = ''\n res = arr.join(split) + helper(remain)\n return res\n};\n\nfunction helper(n) {\n let res = ''\n for(let i = 0; i < n; i++) res += ' '\n return res\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720dcd", + "questionid": 770, + "title": "Minimum Number of Days to Make m Bouquets", + "slug": "minimum-number-of-days-to-make-m-bouquets", + "description": "You are given an integer array bloomDay, an integer m and an integer k. You want to make m bouquets. To make a bouquet, you need to use k adjacent flowers from the garden. The garden consists of n flowers, the ith flower will bloom in the bloomDay[i] and then can be used in exactly one bouquet. Return the minimum number of days you need to wait to be able to make m bouquets from the garden. If it is impossible to make m bouquets return -1. ", + "category": [ + "Array", + "Binary Search" + ], + "complexity": "Medium", + "successrate": 55.5, + "totalsubmissions": 65353, + "totalaccepted": 36272, + "likes": 1568, + "dislikes": 40, + "hints": "If we can make m or more bouquets at day x, then we can still make m or more bouquets at any day y > x. We can check easily if we can make enough bouquets at day x if we can get group adjacent flowers at day x.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "bloomDay = [1,10,3,10,2], m = 3, k = 1", + "expected_output": "3", + "explanation": "Let us see what happened in the first three days. x means flower bloomed and _ means flower did not bloom in the garden.\nWe need 3 bouquets each should contain 1 flower.\nAfter day 1: [x, _, _, _, _] // we can only make one bouquet.\nAfter day 2: [x, _, _, _, x] // we can only make two bouquets.\nAfter day 3: [x, _, x, _, x] // we can make 3 bouquets. The answer is 3." + }, + { + "example_num": 2, + "expected_input": "bloomDay = [1,10,3,10,2], m = 3, k = 2", + "expected_output": "-1", + "explanation": "We need 3 bouquets each has 2 flowers, that means we need 6 flowers. We only have 5 flowers so it is impossible to get the needed bouquets and we return -1." + }, + { + "example_num": 3, + "expected_input": "bloomDay = [7,7,7,7,12,7,7], m = 2, k = 3", + "expected_output": "12", + "explanation": "We need 2 bouquets each should have 3 flowers.\nHere is the garden after the 7 and 12 days:\nAfter day 7: [x, x, x, x, _, x, x]\nWe can make one bouquet of the first three flowers that bloomed. We cannot make another bouquet from the last three flowers that bloomed because they are not adjacent.\nAfter day 12: [x, x, x, x, x, x, x]\nIt is obvious that we can make two bouquets in different ways." + } + ], + "solution": "/**\n * @param {number[]} bloomDay\n * @param {number} m\n * @param {number} k\n * @return {number}\n */\nconst minDays = function(bloomDay, m, k) {\n const n = bloomDay.length\n let l = -1, r = Math.max(...bloomDay)\n while(l < r) {\n const mid = l + Math.floor((r - l) / 2)\n if(valid(mid)) r = mid\n else l = mid + 1\n }\n return valid(l) ? l : -1\n\n function valid(mid) {\n let res = 0, cur = 0\n for (let i = 0; i < n; i++) {\n const e = bloomDay[i]\n if(e <= mid) {\n cur++\n if(cur >= k) {\n res++\n cur = 0\n }\n } else {\n cur = 0\n }\n }\n return res >= m\n }\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720dd0", + "questionid": 773, + "title": "Find Critical and Pseudo-Critical Edges in Minimum Spanning Tree", + "slug": "find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree", + "description": "Given a weighted undirected connected graph with n\u00a0vertices numbered from 0 to n - 1,\u00a0and an array edges\u00a0where edges[i] = [ai, bi, weighti] represents a bidirectional and weighted edge between nodes\u00a0ai\u00a0and bi. A minimum spanning tree (MST) is a subset of the graph's edges that connects all vertices without cycles\u00a0and with the minimum possible total edge weight. Find all the critical and pseudo-critical edges in the given graph's minimum spanning tree (MST). An MST edge whose deletion from the graph would cause the MST weight to increase is called a\u00a0critical edge. On\u00a0the other hand, a pseudo-critical edge is that which can appear in some MSTs but not all. Note that you can return the indices of the edges in any order. ", + "category": [ + "Union Find", + "Graph", + "Sorting", + "Minimum Spanning Tree", + "Strongly Connected Component" + ], + "complexity": "Hard", + "successrate": 52.9, + "totalsubmissions": 14287, + "totalaccepted": 7559, + "likes": 442, + "dislikes": 43, + "hints": "Use the Kruskal algorithm to find the minimum spanning tree by sorting the edges and picking edges from ones with smaller weights. Use a disjoint set to avoid adding redundant edges that result in a cycle. To find if one edge is critical, delete that edge and re-run the MST algorithm and see if the weight of the new MST increases. To find if one edge is non-critical (in any MST), include that edge to the accepted edge list and continue the MST algorithm, then see if the resulting MST has the same weight of the initial MST of the entire graph.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 5, edges = [[0,1,1],[1,2,1],[2,3,2],[0,3,2],[0,4,3],[3,4,3],[1,4,6]]", + "expected_output": "[[0,1],[2,3,4,5]]", + "explanation": "The figure above describes the graph.\nThe following figure shows all the possible MSTs:\n\"\"\nNotice that the two edges 0 and 1 appear in all MSTs, therefore they are critical edges, so we return them in the first list of the output.\nThe edges 2, 3, 4, and 5 are only part of some MSTs, therefore they are considered pseudo-critical edges. We add them to the second list of the output." + }, + { + "example_num": 2, + "expected_input": "n = 4, edges = [[0,1,1],[1,2,1],[2,3,1],[0,3,1]]", + "expected_output": "[[],[0,1,2,3]]", + "explanation": "We can observe that since all 4 edges have equal weight, choosing any 3 edges from the given 4 will yield an MST. Therefore all 4 edges are pseudo-critical." + } + ], + "solution": "/**\n * @param {number} n\n * @param {number[][]} edges\n * @return {number[][]}\n */\nconst findCriticalAndPseudoCriticalEdges = function (n, edges) {\n const criticalEdges = [],\n psuedoCriticalEdges = [],\n map = new Map()\n edges.forEach((edge, i) => map.set(edge, i))\n edges.sort((a, b) => a[2] - b[2])\n const buildMST = (pick, skip) => {\n const uf = new UnionFind(n)\n let cost = 0\n if (pick !== null) {\n uf.union(pick[0], pick[1])\n cost += pick[2]\n }\n for (let edge of edges) {\n if (edge !== skip && uf.union(edge[0], edge[1])) cost += edge[2]\n }\n return uf.count === 1 ? cost : Number.MAX_SAFE_INTEGER\n }\n const minCost = buildMST(null, null)\n for (let edge of edges) {\n const index = map.get(edge)\n const costWithout = buildMST(null, edge)\n if (costWithout > minCost) {\n criticalEdges.push(index)\n } else {\n const costWith = buildMST(edge, null)\n if (costWith === minCost) psuedoCriticalEdges.push(index)\n }\n }\n return [criticalEdges, psuedoCriticalEdges]\n}\nclass UnionFind {\n constructor(n) {\n this.parents = Array(n)\n .fill(0)\n .map((e, i) => i)\n this.ranks = Array(n).fill(0)\n this.count = n\n }\n root(x) {\n while (x !== this.parents[x]) {\n this.parents[x] = this.parents[this.parents[x]]\n x = this.parents[x]\n }\n return x\n }\n find(x) {\n return this.root(x)\n }\n union(x, y) {\n const [rx, ry] = [this.find(x), this.find(y)]\n if (this.ranks[rx] >= this.ranks[ry]) {\n this.parents[ry] = rx\n this.ranks[rx] += this.ranks[ry]\n } else if (this.ranks[ry] > this.ranks[rx]) {\n this.parents[rx] = ry\n this.ranks[ry] += this.ranks[rx]\n }\n if (rx !== ry) {\n this.count--\n return true\n } else return false\n }\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720dd3", + "questionid": 776, + "title": "Stone Game IV", + "slug": "stone-game-iv", + "description": "Alice and Bob take turns playing a game, with Alice starting first. Initially, there are n stones in a pile. On each player's turn, that player makes a move consisting of removing any non-zero square number of stones in the pile. Also, if a player cannot make a move, he/she loses the game. Given a positive integer n, return true if and only if Alice wins the game otherwise return false, assuming both players play optimally. ", + "category": [ + "Math", + "Dynamic Programming", + "Game Theory" + ], + "complexity": "Hard", + "successrate": 60.8, + "totalsubmissions": 95502, + "totalaccepted": 58083, + "likes": 1247, + "dislikes": 53, + "hints": "Use dynamic programming to keep track of winning and losing states. Given some number of stones, Alice can win if she can force Bob onto a losing state.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 1", + "expected_output": "true\nExplanation: Alice can remove 1 stone winning the game because Bob doesn't have any moves.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "n = 2", + "expected_output": "false\nExplanation: Alice can only remove 1 stone, after that Bob removes the last one winning the game (2 -> 1 -> 0).", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "n = 4", + "expected_output": "true", + "explanation": "n is already a perfect square, Alice can win with one move, removing 4 stones (4 -> 0)." + } + ], + "solution": "/**\n * @param {number} n\n * @return {boolean}\n */\nconst winnerSquareGame = function(n) {\n const dp = new Array(n + 1).fill(0);\n for (let i = 1; i <= n; ++i) {\n for (let k = 1; k * k <= i; ++k) {\n if (!dp[i - k * k]) {\n dp[i] = true;\n break;\n }\n }\n }\n return dp[n];\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720dd4", + "questionid": 777, + "title": "Path Crossing", + "slug": "path-crossing", + "description": "Given a string path, where path[i] = 'N', 'S', 'E' or 'W', each representing moving one unit north, south, east, or west, respectively. You start at the origin (0, 0) on a 2D plane and walk on the path specified by path. Return true if the path crosses itself at any point, that is, if at any time you are on a location you have previously visited. Return false otherwise. ", + "category": [ + "Hash Table", + "String" + ], + "complexity": "Easy", + "successrate": 55.7, + "totalsubmissions": 62878, + "totalaccepted": 35053, + "likes": 473, + "dislikes": 8, + "hints": "Simulate the process while keeping track of visited points. Use a set to store previously visited points.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "path = "NES"", + "expected_output": "false", + "explanation": "Notice that the path doesn't cross any point more than once." + }, + { + "example_num": 2, + "expected_input": "path = "NESWW"", + "expected_output": "true", + "explanation": "Notice that the path visits the origin twice." + } + ], + "solution": null + }, + { + "_id": "66f925ddfdfb8e1665720dd5", + "questionid": 778, + "title": "Check If Array Pairs Are Divisible by k", + "slug": "check-if-array-pairs-are-divisible-by-k", + "description": "Given an array of integers arr of even length n and an integer k. We want to divide the array into exactly n / 2 pairs such that the sum of each pair is divisible by k. Return true If you can find a way to do that or false otherwise. ", + "category": [ + "Array", + "Hash Table", + "Counting" + ], + "complexity": "Medium", + "successrate": 40.5, + "totalsubmissions": 75098, + "totalaccepted": 30395, + "likes": 933, + "dislikes": 56, + "hints": "Keep an array of the frequencies of ((x % k) + k) % k for each x in arr. for each i in [0, k - 1] we need to check if freq[k] == freq[k - i] Take care of the case when i == k - i and when i == 0", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "arr = [1,2,3,4,5,10,6,7,8,9], k = 5", + "expected_output": "true", + "explanation": "Pairs are (1,9),(2,8),(3,7),(4,6) and (5,10)." + }, + { + "example_num": 2, + "expected_input": "arr = [1,2,3,4,5,6], k = 7", + "expected_output": "true", + "explanation": "Pairs are (1,6),(2,5) and(3,4)." + }, + { + "example_num": 3, + "expected_input": "arr = [1,2,3,4,5,6], k = 10", + "expected_output": "false", + "explanation": "You can try all possible pairs to see that there is no way to divide arr into 3 pairs each with sum divisible by 10." + } + ], + "solution": null + }, + { + "_id": "66f925ddfdfb8e1665720ddc", + "questionid": 785, + "title": "Count Odd Numbers in an Interval Range", + "slug": "count-odd-numbers-in-an-interval-range", + "description": "Given two non-negative integers low and high. Return the count of odd numbers between low and high\u00a0(inclusive). ", + "category": [ + "Math" + ], + "complexity": "Easy", + "successrate": 48.1, + "totalsubmissions": 146529, + "totalaccepted": 70473, + "likes": 616, + "dislikes": 48, + "hints": "If the range (high - low + 1) is even, the number of even and odd numbers in this range will be the same. If the range (high - low + 1) is odd, the solution will depend on the parity of high and low.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "low = 3, high = 7", + "expected_output": "3\r\nExplanation: The odd numbers between 3 and 7 are [3,5,7].", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "low = 8, high = 10", + "expected_output": "1\r\nExplanation: The odd numbers between 8 and 10 are [9].", + "explanation": "" + } + ], + "solution": "/**\n * @param {number} low\n * @param {number} high\n * @return {number}\n */\nconst countOdds = function(low, high) {\n let res = 0\n \n const odd = num => num % 2 === 1\n if(odd(low)) res++\n \n const num = Math.floor( (high - low) / 2 )\n res += num\n \n if(high > low + 2 * num && odd(high)) res++\n \n return res\n};\n\n\n// another\n\n/**\n * @param {number} low\n * @param {number} high\n * @return {number}\n */\nconst countOdds = function(low, high) {\n return ~~((high + 1) / 2) - (~~(low / 2))\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720dde", + "questionid": 787, + "title": "Number of Good Ways to Split a String", + "slug": "number-of-good-ways-to-split-a-string", + "description": "You are given a string s. A split is called good if you can split s into two non-empty strings sleft and sright where their concatenation is equal to s (i.e., sleft + sright = s) and the number of distinct letters in sleft and sright is the same. Return the number of good splits you can make in s. ", + "category": [ + "String", + "Dynamic Programming", + "Bit Manipulation" + ], + "complexity": "Medium", + "successrate": 70.2, + "totalsubmissions": 98161, + "totalaccepted": 68912, + "likes": 1315, + "dislikes": 30, + "hints": "Use two HashMap to store the counts of distinct letters in the left and right substring divided by the current index.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "aacaba"", + "expected_output": "2", + "explanation": "There are 5 ways to split "aacaba" and 2 of them are good. \n("a", "acaba") Left string and right string contains 1 and 3 different letters respectively.\n("aa", "caba") Left string and right string contains 1 and 3 different letters respectively.\n("aac", "aba") Left string and right string contains 2 and 2 different letters respectively (good split).\n("aaca", "ba") Left string and right string contains 2 and 2 different letters respectively (good split).\n("aacab", "a") Left string and right string contains 3 and 1 different letters respectively." + }, + { + "example_num": 2, + "expected_input": "s = "abcd"", + "expected_output": "1", + "explanation": "Split the string as follows ("ab", "cd")." + } + ], + "solution": "/**\n * @param {string} s\n * @return {number}\n */\nconst numSplits = function(s) {\n const n = s.length\n const freq = new Map()\n const prefix = Array(26).fill(0)\n for(let i = 0; i < n; i++) {\n if(freq.get(s[i]) == null) freq.set(s[i], 0)\n freq.set(s[i], freq.get(s[i]) + 1)\n prefix[i] = freq.size\n }\n freq.clear()\n const suffix = Array(26).fill(0)\n for(let i = n - 1; i >= 0 ;i--) {\n if(freq.get(s[i]) == null) freq.set(s[i], 0)\n freq.set(s[i], freq.get(s[i]) + 1)\n suffix[i] = freq.size\n }\n // console.log(prefix, suffix)\n let res = 0\n for(let i = 1; i < n; i++) {\n if(prefix[i - 1] === suffix[i]) res++\n }\n \n return res\n};\n\n\n// another\n\n\n/**\n * @param {string} s\n * @return {number}\n */\nconst numSplits = function(s) {\n const arr = Array(26).fill(0)\n const a = 'a'.charCodeAt(0)\n for(let i = 0, len = s.length; i < len; i++) {\n arr[s.charCodeAt(i) - a]++\n }\n const cur = Array(26).fill(0)\n let res = 0\n for(let i = 0, len = s.length; i < len - 1; i++) {\n cur[s.charCodeAt(i) - a]++\n let tmp = false, clone = arr.slice()\n for(let j = 0; j < 26; j++) {\n clone[j] -= cur[j]\n }\n const curNum = cur.reduce((ac, e) => ac + (e > 0 ? 1 : 0), 0)\n const cloneNum = clone.reduce((ac, e) => ac + (e > 0 ? 1 : 0), 0)\n if(curNum === cloneNum) res++\n }\n \n return res\n};\n\n" + }, + { + "_id": "66f925ddfdfb8e1665720de1", + "questionid": 790, + "title": "Number of Substrings With Only 1s", + "slug": "number-of-substrings-with-only-1s", + "description": "Given a binary string s, return the number of substrings with all characters 1's. Since the answer may be too large, return it modulo 109 + 7. ", + "category": [ + "Math", + "String" + ], + "complexity": "Medium", + "successrate": 44.2, + "totalsubmissions": 65615, + "totalaccepted": 28986, + "likes": 508, + "dislikes": 22, + "hints": "Count number of 1s in each consecutive-1 group. For a group with n consecutive 1s, the total contribution of it to the final answer is (n + 1) * n // 2.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "0110111"", + "expected_output": "9", + "explanation": "There are 9 substring in total with only 1's characters.\n"1" -> 5 times.\n"11" -> 3 times.\n"111" -> 1 time." + }, + { + "example_num": 2, + "expected_input": "s = "101"", + "expected_output": "2", + "explanation": "Substring "1" is shown 2 times in s." + }, + { + "example_num": 3, + "expected_input": "s = "111111"", + "expected_output": "21", + "explanation": "Each substring contains only 1's characters." + } + ], + "solution": null + }, + { + "_id": "66f925ddfdfb8e1665720de2", + "questionid": 791, + "title": "String Compression II", + "slug": "string-compression-ii", + "description": "Run-length encoding is a string compression method that works by\u00a0replacing consecutive identical characters (repeated 2 or more times) with the concatenation of the character and the number marking the count of the characters (length of the run). For example, to compress the string\u00a0\"aabccc\"\u00a0we replace \"aa\"\u00a0by\u00a0\"a2\"\u00a0and replace \"ccc\"\u00a0by\u00a0\"c3\". Thus the compressed string becomes \"a2bc3\". Notice that in this problem, we are not adding\u00a0'1'\u00a0after single characters. Given a\u00a0string s\u00a0and an integer k. You need to delete at most\u00a0k characters from\u00a0s\u00a0such that the run-length encoded version of s\u00a0has minimum length. Find the minimum length of the run-length encoded\u00a0version of s after deleting at most k characters. ", + "category": [ + "String", + "Dynamic Programming" + ], + "complexity": "Hard", + "successrate": 38, + "totalsubmissions": 29095, + "totalaccepted": 11048, + "likes": 459, + "dislikes": 48, + "hints": "Use dynamic programming. The state of the DP can be the current index and the remaining characters to delete. Having a prefix sum for each character can help you determine for a certain character c in some specific range, how many characters you need to delete to merge all occurrences of c in that range.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "aaabcccd", k = 2", + "expected_output": "4\nExplanation: Compressing s without deleting anything will give us "a3bc3d" of length 6. Deleting any of the characters 'a' or 'c' would at most decrease the length of the compressed string to 5, for instance delete 2 'a' then we will have s = "abcccd" which compressed is abc3d. Therefore, the optimal way is to delete 'b' and 'd', then the compressed version of s will be "a3c3" of length 4.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "s = "aabbaa", k = 2", + "expected_output": "2\nExplanation: If we delete both 'b' characters, the resulting compressed string would be "a4" of length 2.", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "s = "aaaaaaaaaaa", k = 0", + "expected_output": "3\nExplanation: Since k is zero, we cannot delete anything. The compressed string is "a11" of length 3.", + "explanation": "" + } + ], + "solution": "/**\n * @param {string} s\n * @param {number} k\n * @return {number}\n */\nconst getLengthOfOptimalCompression = function(s, k) {\n const m = new Map()\n function counter(start, last, lastCount, left) {\n if(left < 0) return Infinity\n if(start >= s.length) return 0\n let res\n const k = `${start}-${last}-${lastCount}-${left}`\n if(m.has(k)) return m.get(k)\n if(s[start] === last) {\n const incr = (lastCount === 1 || lastCount === 9 || lastCount === 99) ? 1 : 0\n res = incr + counter(start + 1, last, lastCount + 1, left)\n } else {\n const keepCounter = 1 + counter(start + 1, s[start], 1, left)\n const delCounter = counter(start + 1, last, lastCount, left - 1)\n res = Math.min(keepCounter, delCounter)\n }\n m.set(k, res)\n return res\n }\n return counter(0, '', 0, k)\n};\n\n// another\n\nconst getLengthOfOptimalCompression = function (s, k) {\n const n = s.length\n const dp = new Array(n + 1).fill(n).map((row) => new Array(k + 1).fill(n))\n dp[0][0] = 0\n\n for (let i = 1; i <= n; i++) {\n for (let j = 0; j <= k; j++) {\n let letterCount = 0\n let deletion = 0\n // keep s[i], compress same letters, remove different letters\n for (let l = i; l >= 1; l--) {\n if (s.charAt(l - 1) === s.charAt(i - 1)) letterCount++\n else deletion++\n // places = length needed to rep compressed letters.\n // 0 places for count = 1,0, 1 place = <10, 10-99 requires 2 places, 100+ requires 3\n let places = 0\n if (letterCount >= 100) places = 3\n else if (letterCount >= 10) places = 2\n else if (letterCount >= 2) places = 1\n if (j - deletion >= 0) {\n dp[i][j] = Math.min(dp[i][j], dp[l - 1][j - deletion] + 1 + places)\n }\n }\n // delete\n if (j > 0) {\n dp[i][j] = Math.min(dp[i][j], dp[i - 1][j - 1])\n }\n }\n }\n return dp[n][k]\n}\n\n" + }, + { + "_id": "66f925ddfdfb8e1665720de7", + "questionid": 796, + "title": "Maximum Number of Non-Overlapping Subarrays With Sum Equals Target", + "slug": "maximum-number-of-non-overlapping-subarrays-with-sum-equals-target", + "description": "Given an array nums and an integer target, return the maximum number of non-empty non-overlapping subarrays such that the sum of values in each subarray is equal to target. ", + "category": [ + "Array", + "Hash Table", + "Greedy", + "Prefix Sum" + ], + "complexity": "Medium", + "successrate": 46.4, + "totalsubmissions": 41089, + "totalaccepted": 19048, + "likes": 729, + "dislikes": 15, + "hints": "Keep track of prefix sums to quickly look up what subarray that sums \"target\" can be formed at each step of scanning the input array. It can be proved that greedily forming valid subarrays as soon as one is found is optimal.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,1,1,1,1], target = 2", + "expected_output": "2", + "explanation": "There are 2 non-overlapping subarrays [1,1,1,1,1] with sum equals to target(2)." + }, + { + "example_num": 2, + "expected_input": "nums = [-1,3,5,1,4,2,-9], target = 6", + "expected_output": "2", + "explanation": "There are 3 subarrays with sum equal to 6.\n([5,1], [4,2], [3,5,1,4,2,-9]) but only the first 2 are non-overlapping." + } + ], + "solution": "/**\n * @param {number[]} nums\n * @param {number} target\n * @return {number}\n */\nconst maxNonOverlapping = function(nums, target) {\n if(nums == null || nums.length === 0) return 0\n let sum = 0, res = 0\n const n = nums.length\n const m = {0: 0}\n \n for(let i = 0; i < n; i++) {\n sum += nums[i]\n if(m[sum - target] != null) {\n res = Math.max(res, m[sum - target] + 1)\n }\n m[sum] = res\n }\n return res\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720de9", + "questionid": 798, + "title": "Minimum Suffix Flips", + "slug": "minimum-suffix-flips", + "description": "You are given a 0-indexed binary string target of length n. You have another binary string s of length n that is initially set to all zeros. You want to make s equal to target. In one operation, you can pick an index i where 0 <= i < n and flip all bits in the inclusive range [i, n - 1]. Flip means changing '0' to '1' and '1' to '0'. Return the minimum number of operations needed to make s equal to target. ", + "category": [ + "String", + "Greedy" + ], + "complexity": "Medium", + "successrate": 72.4, + "totalsubmissions": 44336, + "totalaccepted": 32118, + "likes": 636, + "dislikes": 32, + "hints": "Consider a strategy where the choice of bulb with number i is increasing. In such a strategy, you no longer need to worry about bulbs that have been set to the left.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "target = "10111"", + "expected_output": "3", + "explanation": "Initially, s = "00000".\nChoose index i = 2: "00000" -> "00111"\nChoose index i = 0: "00111" -> "11000"\nChoose index i = 1: "11000" -> "10111"\nWe need at least 3 flip operations to form target." + }, + { + "example_num": 2, + "expected_input": "target = "101"", + "expected_output": "3", + "explanation": "Initially, s = "000".\nChoose index i = 0: "000" -> "111"\nChoose index i = 1: "111" -> "100"\nChoose index i = 2: "100" -> "101"\nWe need at least 3 flip operations to form target." + }, + { + "example_num": 3, + "expected_input": "target = "00000"", + "expected_output": "0", + "explanation": "We do not need any operations since the initial s already equals target." + } + ], + "solution": "/**\n * @param {string} target\n * @return {number}\n */\nconst minFlips = function (target) {\n const n = target.length\n let res = 0, flip = 0\n\n for(let i = 0; i < n; i++) {\n if(target[i] === '0' && flip % 2 === 0) continue\n if(target[i] === '1' && flip % 2 === 1) continue\n flip++\n res++\n }\n\n return res\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720ded", + "questionid": 802, + "title": "Thousand Separator", + "slug": "thousand-separator", + "description": "Given an integer n, add a dot (\".\") as the thousands separator and return it in string format. ", + "category": [ + "String" + ], + "complexity": "Easy", + "successrate": 55.9, + "totalsubmissions": 58728, + "totalaccepted": 32849, + "likes": 328, + "dislikes": 15, + "hints": "Scan from the back of the integer and use dots to connect blocks with length 3 except the last block.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 987", + "expected_output": ""987"", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "n = 1234", + "expected_output": ""1.234"", + "explanation": "" + } + ], + "solution": null + }, + { + "_id": "66f925ddfdfb8e1665720dee", + "questionid": 803, + "title": "Minimum Number of Vertices to Reach All Nodes", + "slug": "minimum-number-of-vertices-to-reach-all-nodes", + "description": "Given a\u00a0directed acyclic graph,\u00a0with\u00a0n\u00a0vertices numbered from\u00a00\u00a0to\u00a0n-1,\u00a0and an array\u00a0edges\u00a0where\u00a0edges[i] = [fromi, toi]\u00a0represents a directed edge from node\u00a0fromi\u00a0to node\u00a0toi. Find the smallest set of vertices from which all nodes in the graph are reachable. It's guaranteed that a unique solution exists. Notice that you can return the vertices in any order. ", + "category": [ + "Graph" + ], + "complexity": "Medium", + "successrate": 78.6, + "totalsubmissions": 72692, + "totalaccepted": 57103, + "likes": 1369, + "dislikes": 60, + "hints": "A node that does not have any incoming edge can only be reached by itself. Any other node with incoming edges can be reached from some other node. We only have to count the number of nodes with zero incoming edges.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 6, edges = [[0,1],[0,2],[2,5],[3,4],[4,2]]", + "expected_output": "[0,3]\nExplanation: It's not possible to reach all the nodes from a single vertex. From 0 we can reach [0,1,2,5]. From 3 we can reach [3,4,2,5]. So we output [0,3].", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "n = 5, edges = [[0,1],[2,1],[3,1],[1,4],[2,4]]", + "expected_output": "[0,2,3]\nExplanation: Notice that vertices 0, 3 and 2 are not reachable from any other node, so we must include them. Also any of these vertices can reach nodes 1 and 4.", + "explanation": "" + } + ], + "solution": "/**\n * @param {number} n\n * @param {number[][]} edges\n * @return {number[]}\n */\nvar findSmallestSetOfVertices = function(n, edges) {\n const indegree = Array(n).fill(0)\n for(const [from, to] of edges) {\n indegree[to]++\n }\n let res = []\n for(let i = 0; i 1,2,3],\n  [4,5,6],\n  [7,8,9]]", + "expected_output": "25\nExplanation: Diagonals sum: 1 + 5 + 9 + 3 + 7 = 25\nNotice that element mat[1][1] = 5 is counted only once.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "mat = [[1,1,1,1],\n  [1,1,1,1],\n  [1,1,1,1],\n  [1,1,1,1]]", + "expected_output": "8", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "mat = [[5]]", + "expected_output": "5", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[][]} mat\n * @return {number}\n */\nconst diagonalSum = function(mat) {\n let res = 0, n = mat.length\n for(let i = 0; i < n; i++) {\n const j = i, ii = i, jj = n - 1 - i\n if(j == jj) res += mat[i][j]\n else {\n res += mat[i][j] + mat[ii][jj]\n }\n }\n \n return res\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720dfe", + "questionid": 819, + "title": "Sum of All Odd Length Subarrays", + "slug": "sum-of-all-odd-length-subarrays", + "description": "Given an array of positive integers\u00a0arr, calculate the sum of all possible odd-length subarrays. A subarray is a contiguous\u00a0subsequence of the array. Return\u00a0the sum of all odd-length subarrays of\u00a0arr. ", + "category": [ + "Array", + "Math", + "Prefix Sum" + ], + "complexity": "Easy", + "successrate": 83.4, + "totalsubmissions": 110599, + "totalaccepted": 92214, + "likes": 1901, + "dislikes": 155, + "hints": "You can brute force \u20ac\u201c try every (i,j) pair, and if the length is odd, go through and add the sum to the answer.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "arr = [1,4,2,5,3]", + "expected_output": "58\nExplanation: The odd-length subarrays of arr and their sums are:\n[1] = 1\n[4] = 4\n[2] = 2\n[5] = 5\n[3] = 3\n[1,4,2] = 7\n[4,2,5] = 11\n[2,5,3] = 10\n[1,4,2,5,3] = 15\nIf we add all these together we get 1 + 4 + 2 + 5 + 3 + 7 + 11 + 10 + 15 = 58", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "arr = [1,2]", + "expected_output": "3\nExplanation: There are only 2 subarrays of odd length, [1] and [2]. Their sum is 3.", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "arr = [10,11,12]", + "expected_output": "66", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} arr\n * @return {number}\n */\nconst sumOddLengthSubarrays = function(arr) {\n const n = arr.length, pre = Array(n + 1).fill(0)\n for(let i = 0; i < n; i++) pre[i + 1] = pre[i] + arr[i]\n \n let res = 0\n let len = 1\n while(len <= n) {\n for(let i = 0; i <= n - len; i++) {\n res += pre[i + len] - pre[i] // len === 1: 1 - 0, 2 - 1\n // len === 3: 3 - 0, 6 - 3\n }\n \n len += 2\n }\n \n return res\n \n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720dff", + "questionid": 820, + "title": "Make Sum Divisible by P", + "slug": "make-sum-divisible-by-p", + "description": "Given an array of positive integers nums, remove the smallest subarray (possibly empty) such that the sum of the remaining elements is divisible by p. It is not allowed to remove the whole array. Return the length of the smallest subarray that you need to remove, or -1 if it's impossible. A subarray is defined as a contiguous block of elements in the array. ", + "category": [ + "Array", + "Hash Table", + "Prefix Sum" + ], + "complexity": "Medium", + "successrate": 28.2, + "totalsubmissions": 55868, + "totalaccepted": 15733, + "likes": 878, + "dislikes": 38, + "hints": "Use prefix sums to calculate the subarray sums. Suppose you know the remainder for the sum of the entire array. How does removing a subarray affect that remainder? What remainder does the subarray need to have in order to make the rest of the array sum up to be divisible by k? Use a map to keep track of the rightmost index for every prefix sum % p.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [3,1,4,2], p = 6", + "expected_output": "1", + "explanation": "The sum of the elements in nums is 10, which is not divisible by 6. We can remove the subarray [4], and the sum of the remaining elements is 6, which is divisible by 6." + }, + { + "example_num": 2, + "expected_input": "nums = [6,3,5,2], p = 9", + "expected_output": "2", + "explanation": "We cannot remove a single element to get a sum divisible by 9. The best way is to remove the subarray [5,2], leaving us with [6,3] with sum 9." + }, + { + "example_num": 3, + "expected_input": "nums = [1,2,3], p = 3", + "expected_output": "0", + "explanation": "Here the sum is 6. which is already divisible by 3. Thus we do not need to remove anything." + } + ], + "solution": "/**\n * @param {number[]} nums\n * @param {number} p\n * @return {number}\n */\nconst minSubarray = function(nums, p) {\n const sum = nums.reduce((ac, e) => ac+ e,0)\n const target = sum % p, n = nums.length, {min} = Math\n if(target === 0) return 0\n const map = new Map()\n map.set(0, -1)\n let res = n\n for(let i = 0, s = 0; i < n; i++) {\n s += nums[i]\n const r = s % p\n\n if(r >= target) {\n if(map.has(r - target)) res = min(res, i - map.get(r-target))\n }else {\n if(map.has(p + r - target)) res = min(res, i - map.get(p + r - target))\n }\n map.set(r, i)\n }\n \n return res === n ? -1 : res\n};\n\n// another\n\n\n/**\n * @param {number[]} nums\n * @param {number} p\n * @return {number}\n */\nconst minSubarray = function(nums, p) {\n const remain = nums.reduce((ac, e) => ac + e, 0) % p\n const n = nums.length, hash = {0: -1}\n let res = n\n if(remain === 0) return 0\n for(let i = 0, sum = 0; i < n; i++) {\n const cur = nums[i]\n sum += cur\n const target = (sum % p - remain + p) % p\n if(hash[target] != null) {\n res = Math.min(res, i - hash[target])\n }\n\n hash[sum % p] = i\n }\n// console.log(hash)\n \n return res === n ? -1 : res\n};\n\n// another\n\n/**\n * @param {number[]} nums\n * @param {number} p\n * @return {number}\n */\nconst minSubarray = function(nums, p) {\n const diff = nums.reduce((a, b) => a + b, 0) % p;\n let res = diff === 0 ? 0 : nums.length;\n \n for (let i = 0, sum = 0, map = {0: -1}; i < nums.length; i++) {\n sum += nums[i];\n const target = (sum % p - diff + p) % p;\n if (map[target] !== undefined) {\n res = Math.min(res, i - map[target]);\n }\n map[sum % p] = i;\n }\n \n return res === nums.length ? -1 : res;\n};\n\n/**\n\nLet pre[] be the prefix sum array,\nthen pre[i] is running prefix sum or prefix sum of i elements,\npre[j] is the prefix sum such that pre[i]-pre[j] is the subarray we\nneed to remove to make pre[n] (sum of all elements) divisible by p\n\n(pre[n] - (pre[i]-pre[j])) % p = 0 ... (remove a subarray to make pre[n] divisible by p)\n=> pre[n] % p = (pre[i]-pre[j]) % p ... ((a-b)%m = a%m - b%m)\n=> pre[j]%p = pre[i]%p - pre[n]%p ... (same property used above)\nsince RHS can be negative we make it positive modulus by adding p and taking modulus\n=> pre[j]%p = (pre[i]%p - pre[n]%p + p) % p\n\n*/\n" + }, + { + "_id": "66f925ddfdfb8e1665720e00", + "questionid": 821, + "title": "Maximum Sum Obtained of Any Permutation", + "slug": "maximum-sum-obtained-of-any-permutation", + "description": "We have an array of integers, nums, and an array of requests where requests[i] = [starti, endi]. The ith request asks for the sum of nums[starti] + nums[starti + 1] + ... + nums[endi - 1] + nums[endi]. Both starti and endi are 0-indexed. Return the maximum total sum of all requests among all permutations of nums. Since the answer may be too large, return it modulo 109 + 7. ", + "category": [ + "Array", + "Greedy", + "Sorting", + "Prefix Sum" + ], + "complexity": "Medium", + "successrate": 36.2, + "totalsubmissions": 33296, + "totalaccepted": 12069, + "likes": 487, + "dislikes": 26, + "hints": "Indexes with higher frequencies should be bound with larger values", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,2,3,4,5], requests = [[1,3],[0,1]]", + "expected_output": "19", + "explanation": "One permutation of nums is [2,1,3,4,5] with the following result: \nrequests[0] -> nums[1] + nums[2] + nums[3] = 1 + 3 + 4 = 8\nrequests[1] -> nums[0] + nums[1] = 2 + 1 = 3\nTotal sum: 8 + 3 = 11.\nA permutation with a higher total sum is [3,5,4,2,1] with the following result:\nrequests[0] -> nums[1] + nums[2] + nums[3] = 5 + 4 + 2 = 11\nrequests[1] -> nums[0] + nums[1] = 3 + 5 = 8\nTotal sum: 11 + 8 = 19, which is the best that you can do." + }, + { + "example_num": 2, + "expected_input": "nums = [1,2,3,4,5,6], requests = [[0,1]]", + "expected_output": "11", + "explanation": "A permutation with the max total sum is [6,5,4,3,2,1] with request sums [11]." + }, + { + "example_num": 3, + "expected_input": "nums = [1,2,3,4,5,10], requests = [[0,2],[1,3],[1,1]]", + "expected_output": "47", + "explanation": "A permutation with the max total sum is [4,10,5,3,2,1] with request sums [19,18,10]." + } + ], + "solution": "/**\n * @param {number[]} nums\n * @param {number[][]} requests\n * @return {number}\n */\nconst maxSumRangeQuery = function(nums, requests) {\n nums.sort((a, b) => b - a)\n const n = nums.length\n const arr = Array(n).fill(0)\n for(const [s, e] of requests) {\n arr[s] += 1\n if(e + 1 < n) arr[e + 1] -= 1\n }\n for(let i = 1; i < n; i++) {\n arr[i] += arr[i - 1]\n }\n arr.sort((a, b) => b - a)\n \n let res = 0\n const mod = 1e9 + 7\n \n for(let i = 0; i < n; i++) {\n res = (res + nums[i] * arr[i]) % mod\n }\n \n return res\n};\n\n// another\n\n/**\n * @param {number[]} nums\n * @param {number[][]} requests\n * @return {number}\n */\nconst maxSumRangeQuery = function (nums, requests) {\n let res = 0\n const mod = 10 ** 9 + 7,\n n = nums.length\n const count = Array(n).fill(0)\n for (let r of requests) {\n count[r[0]] += 1\n if (r[1] + 1 < n) count[r[1] + 1] -= 1\n }\n for (let i = 1; i < n; i++) count[i] += count[i - 1]\n nums.sort((a, b) => a - b)\n count.sort((a, b) => a - b)\n for (let i = 0; i < n; ++i) res = (res + nums[i] * count[i]) % mod\n return res\n}\n\n// another\n\n/**\n * @param {number[]} nums\n * @param {number[][]} requests\n * @return {number}\n */\nconst maxSumRangeQuery = function (nums, requests) {\n const n = nums.length, arr = Array(n + 1).fill(0)\n for(let [s, e] of requests) {\n arr[s] += 1\n arr[e + 1] -= 1\n }\n for(let i = 0, cur = 0; i < n; i++) {\n cur += arr[i]\n arr[i] = cur\n }\n nums.sort((a, b) => b - a)\n arr.sort((a, b) => b - a)\n const mod = 1e9 + 7\n let res = 0\n for(let i = 0; i < n; i++) {\n if (arr[i] <= 0) break\n res = (res + nums[i] * arr[i]) % mod\n }\n return res\n}\n\n// another\n\n/**\n * @param {number[]} nums\n * @param {number[][]} requests\n * @return {number}\n */\nconst maxSumRangeQuery = function (nums, requests) {\n const n = nums.length\n\n const arr = Array(n + 1).fill(0) \n for(const [s, e] of requests) {\n arr[s] += 1\n arr[e + 1] -= 1\n }\n for(let i = 1; i <= n; i++) {\n arr[i] += arr[i - 1] \n }\n arr.sort((a, b) => b - a)\n nums.sort((a, b) => b - a)\n let res = 0\n const mod = 1e9 + 7\n \n for (let i = 0; i < n; i++) {\n if(arr[i] <= 0) break\n res = (res + nums[i] * arr[i]) % mod\n }\n \n return res\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720e08", + "questionid": 829, + "title": "Minimum Cost to Connect Two Groups of Points", + "slug": "minimum-cost-to-connect-two-groups-of-points", + "description": "You are given two groups of points where the first group has size1 points, the second group has size2 points, and size1 >= size2. The cost of the connection between any two points are given in an size1 x size2 matrix where cost[i][j] is the cost of connecting point i of the first group and point j of the second group. The groups are connected if each point in both groups is connected to one or more points in the opposite group. In other words, each point in the first group must be connected to at least one point in the second group, and each point in the second group must be connected to at least one point in the first group. Return the minimum cost it takes to connect the two groups. ", + "category": [ + "Array", + "Dynamic Programming", + "Bit Manipulation", + "Matrix", + "Bitmask" + ], + "complexity": "Hard", + "successrate": 45.9, + "totalsubmissions": 13535, + "totalaccepted": 6208, + "likes": 322, + "dislikes": 12, + "hints": "Each point on the left would either be connected to exactly point already connected to some left node, or a subset of the nodes on the right which are not connected to any node Use dynamic programming with bitmasking, where the state will be (number of points assigned in first group, bitmask of points assigned in second group).", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "cost = [[15, 96], [36, 2]]", + "expected_output": "17\nExplanation: The optimal way of connecting the groups is:\n1--A\n2--B\nThis results in a total cost of 17.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "cost = [[1, 3, 5], [4, 1, 1], [1, 5, 3]]", + "expected_output": "4\nExplanation: The optimal way of connecting the groups is:\n1--A\n2--B\n2--C\n3--A\nThis results in a total cost of 4.\nNote that there are multiple points connected to point 2 in the first group and point A in the second group. This does not matter as there is no limit to the number of points that can be connected. We only care about the minimum total cost.", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "cost = [[2, 5, 1], [3, 4, 7], [8, 1, 2], [6, 2, 4], [3, 8, 8]]", + "expected_output": "10", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[][]} cost\n * @return {number}\n */\nconst connectTwoGroups = function(cost) {\n const m = cost.length, n = cost[0].length, { min } = Math\n const limit = 1 << n\n const dp = Array.from({ length: m + 1 }, () => Array(limit).fill(Infinity))\n const subCost = Array.from({ length: m + 1 }, () => Array(limit).fill(Infinity))\n \n for(let i = 0; i < m; i++) {\n for(let mask = 0; mask < limit; mask++) {\n let sum = 0\n for(let j = 0; j < n; j++) {\n if((mask >> j) & 1) {\n sum += cost[i][j]\n }\n }\n \n subCost[i][mask] = sum\n }\n }\n \n dp[0][0] = 0\n for(let i = 1; i <= m; i++) {\n for(let mask = 0; mask < limit; mask++) {\n for(let sub = mask; sub; sub = (sub - 1) & mask) {\n dp[i][mask] = min(\n dp[i][mask],\n dp[i - 1][mask - sub] + subCost[i - 1][sub]\n )\n }\n let tmp = Infinity\n for(let j = 0; j < n; j++) {\n tmp = min(tmp, cost[i - 1][j])\n }\n \n dp[i][mask] = min(dp[i][mask], dp[i - 1][mask] + tmp)\n }\n }\n // console.log(dp)\n return dp[m][limit - 1]\n};\n\n// another\n\n\n/**\n * @param {number[][]} cost\n * @return {number}\n */\nconst connectTwoGroups = function (cost) {\n const min = Array(cost[0].length).fill(Infinity)\n for (let j = 0; j < min.length; j++) {\n for (let i = 0; i < cost.length; i++) {\n min[j] = Math.min(min[j], cost[i][j])\n }\n }\n const dp = Array.from({ length: 13 }, () => Array(4096).fill(-1))\n return dfs(cost, min, 0, 0, dp)\n}\n\nfunction dfs(cost, min, i, mask, dp) {\n if (dp[i][mask] !== -1) return dp[i][mask]\n let res = i >= cost.length ? 0 : Infinity\n if (i >= cost.length) {\n for (let j = 0; j < cost[0].length; j++) {\n if ((mask & (1 << j)) === 0) res += min[j]\n }\n } else {\n for (let j = 0; j < cost[0].length; j++) {\n res = Math.min(\n res,\n cost[i][j] + dfs(cost, min, i + 1, mask | (1 << j), dp)\n )\n }\n }\n dp[i][mask] = res\n return res\n}\n\n// another\n\n/**\n * @param {number[][]} cost\n * @return {number}\n */\nconst connectTwoGroups = function (cost) {\n const n = cost.length\n const m = cost[0].length\n const con = 1 << m\n const dp = Array(n + 1)\n .fill(null)\n .map(() => Array(con).fill(0))\n const min = Array(m).fill(Infinity)\n for (let i = 0; i < n; i++) {\n for (let j = 0; j < m; j++) {\n min[j] = Math.min(min[j], cost[i][j])\n }\n }\n function dfs(i, mask) {\n let res\n if (dp[i][mask]) {\n return dp[i][mask]\n } else if (i >= n) {\n res = 0\n for (let j = 0; j < m; j++) {\n const binaryJ = 1 << j\n if ((mask & binaryJ) === 0) res += min[j]\n }\n } else {\n res = Infinity\n for (let j = 0; j < m; j++) {\n const binaryJ = 1 << j\n res = Math.min(res, cost[i][j] + dfs(i + 1, mask | binaryJ))\n }\n }\n dp[i][mask] = res\n return res\n }\n return dfs(0, 0)\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720e09", + "questionid": 830, + "title": "Maximum Profit of Operating a Centennial Wheel", + "slug": "maximum-profit-of-operating-a-centennial-wheel", + "description": "You are the operator of a Centennial Wheel that has four gondolas, and each gondola has room for up to four people. You have the ability to rotate the gondolas counterclockwise, which costs you runningCost dollars. You are given an array customers of length n where customers[i] is the number of new customers arriving just before the ith rotation (0-indexed). This means you must rotate the wheel i times before the customers[i] customers arrive. You cannot make customers wait if there is room in the gondola. Each customer pays boardingCost dollars when they board on the gondola closest to the ground and will exit once that gondola reaches the ground again. You can stop the wheel at any time, including before serving all customers. If you decide to stop serving customers, all subsequent rotations are free in order to get all the customers down safely. Note that if there are currently more than four customers waiting at the wheel, only four will board the gondola, and the rest will wait for the next rotation. Return the minimum number of rotations you need to perform to maximize your profit. If there is no scenario where the profit is positive, return -1. ", + "category": [ + "Array", + "Simulation" + ], + "complexity": "Medium", + "successrate": 43.9, + "totalsubmissions": 21987, + "totalaccepted": 9658, + "likes": 67, + "dislikes": 207, + "hints": "Think simulation Note that the number of turns will never be more than 50 / 4 * n", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "customers = [8,3], boardingCost = 5, runningCost = 6", + "expected_output": "3", + "explanation": "The numbers written on the gondolas are the number of people currently there.\n1. 8 customers arrive, 4 board and 4 wait for the next gondola, the wheel rotates. Current profit is 4 * $5 - 1 * $6 = $14.\n2. 3 customers arrive, the 4 waiting board the wheel and the other 3 wait, the wheel rotates. Current profit is 8 * $5 - 2 * $6 = $28.\n3. The final 3 customers board the gondola, the wheel rotates. Current profit is 11 * $5 - 3 * $6 = $37.\nThe highest profit was $37 after rotating the wheel 3 times." + }, + { + "example_num": 2, + "expected_input": "customers = [10,9,6], boardingCost = 6, runningCost = 4", + "expected_output": "7", + "explanation": "1. 10 customers arrive, 4 board and 6 wait for the next gondola, the wheel rotates. Current profit is 4 * $6 - 1 * $4 = $20.\n2. 9 customers arrive, 4 board and 11 wait (2 originally waiting, 9 newly waiting), the wheel rotates. Current profit is 8 * $6 - 2 * $4 = $40.\n3. The final 6 customers arrive, 4 board and 13 wait, the wheel rotates. Current profit is 12 * $6 - 3 * $4 = $60.\n4. 4 board and 9 wait, the wheel rotates. Current profit is 16 * $6 - 4 * $4 = $80.\n5. 4 board and 5 wait, the wheel rotates. Current profit is 20 * $6 - 5 * $4 = $100.\n6. 4 board and 1 waits, the wheel rotates. Current profit is 24 * $6 - 6 * $4 = $120.\n7. 1 boards, the wheel rotates. Current profit is 25 * $6 - 7 * $4 = $122.\nThe highest profit was $122 after rotating the wheel 7 times." + }, + { + "example_num": 3, + "expected_input": "customers = [3,4,0,5,1], boardingCost = 1, runningCost = 92", + "expected_output": "-1", + "explanation": "1. 3 customers arrive, 3 board and 0 wait, the wheel rotates. Current profit is 3 * $1 - 1 * $92 = -$89.\n2. 4 customers arrive, 4 board and 0 wait, the wheel rotates. Current profit is 7 * $1 - 2 * $92 = -$177.\n3. 0 customers arrive, 0 board and 0 wait, the wheel rotates. Current profit is 7 * $1 - 3 * $92 = -$269.\n4. 5 customers arrive, 4 board and 1 waits, the wheel rotates. Current profit is 11 * $1 - 4 * $92 = -$357.\n5. 1 customer arrives, 2 board and 0 wait, the wheel rotates. Current profit is 13 * $1 - 5 * $92 = -$447.\nThe profit was never positive, so return -1." + } + ], + "solution": "/**\n * @param {number[]} customers\n * @param {number} boardingCost\n * @param {number} runningCost\n * @return {number}\n */\nconst minOperationsMaxProfit = function(customers, boardingCost, runningCost) {\n let remain = 0\n let profit = 0\n let cost = 0\n let max = -Infinity\n let maxNum = 0\n for(let i = 0, len = customers.length; i < len; i++) {\n const e = customers[i]\n remain += e\n const cur = (remain >= 4 ? 4 : remain)\n remain -= cur\n profit += cur * boardingCost - runningCost\n if(profit > max) maxNum++\n max = Math.max(max, profit)\n }\n if(remain) {\n const r = Math.floor(remain / 4)\n const single = 4 * boardingCost - runningCost\n remain = remain % 4\n // profit += (single * r + (remain > 0 ? (remain * boardingCost - runningCost) : 0))\n profit += single * r\n if(single > 0) maxNum += r\n max = Math.max(max, profit)\n if (remain < 4) {\n const tmp = remain * boardingCost - runningCost\n profit += tmp\n remain = 0\n if(profit > max) maxNum++\n max = Math.max(max, profit)\n }\n }\n if (max <=0 )return -1\n return maxNum\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720e0d", + "questionid": 834, + "title": "Maximum Number of Visible Points", + "slug": "maximum-number-of-visible-points", + "description": "You are given an array points, an integer angle, and your location, where location = [posx, posy] and points[i] = [xi, yi] both denote integral coordinates on the X-Y plane. Initially, you are facing directly east from your position. You cannot move from your position, but you can rotate. In other words, posx and posy cannot be changed. Your field of view in degrees is represented by angle, determining how wide you can see from any given view direction. Let d be the amount in degrees that you rotate counterclockwise. Then, your field of view is the inclusive range of angles [d - angle/2, d + angle/2]. Your browser does not support the video tag or this video format. You can see some set of points if, for each point, the angle formed by the point, your position, and the immediate east direction from your position is in your field of view. There can be multiple points at one coordinate. There may be points at your location, and you can always see these points regardless of your rotation. Points do not obstruct your vision to other points. Return the maximum number of points you can see. ", + "category": [ + "Array", + "Math", + "Geometry", + "Sliding Window", + "Sorting" + ], + "complexity": "Hard", + "successrate": 36.6, + "totalsubmissions": 69650, + "totalaccepted": 25473, + "likes": 373, + "dislikes": 506, + "hints": "Sort the points by polar angle with the original position. Now only a consecutive collection of points would be visible from any coordinate. We can use two pointers to keep track of visible points for each start point For handling the cyclic condition, it\u20ac\u2122d be helpful to append the point list to itself after sorting.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "points = [[2,1],[2,2],[3,3]], angle = 90, location = [1,1]", + "expected_output": "3", + "explanation": "The shaded region represents your field of view. All points can be made visible in your field of view, including [3,3] even though [2,2] is in front and in the same line of sight." + }, + { + "example_num": 2, + "expected_input": "points = [[2,1],[2,2],[3,4],[1,1]], angle = 90, location = [1,1]", + "expected_output": "4", + "explanation": "All points can be made visible in your field of view, including the one at your location." + }, + { + "example_num": 3, + "expected_input": "points = [[1,0],[2,1]], angle = 13, location = [1,1]", + "expected_output": "1", + "explanation": "You can only see one of the two points, as shown above." + } + ], + "solution": "/**\n * @param {number[][]} points\n * @param {number} angle\n * @param {number[]} location\n * @return {number}\n */\nconst visiblePoints = function (points, angle, location) {\n const angles = [];\n let count = 0;\n for (let p of points) {\n let dx = p[0] - location[0];\n let dy = p[1] - location[1];\n if (dx == 0 && dy == 0) {\n // edge case of same point\n count++;\n continue;\n }\n angles.push(Math.atan2(dy, dx) * (180 / Math.PI));\n }\n angles.sort();\n const tmp = angles.slice();\n for (let d of angles) tmp.push(d + 360); // concatenate to handle edge case\n let res = count;\n for (let i = 0, j = 0; i < tmp.length; i++) {\n while (tmp[i] - tmp[j] > angle) {\n j++;\n }\n res = Math.max(res, count + i - j + 1);\n }\n return res;\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720e0c", + "questionid": 833, + "title": "Special Array With X Elements Greater Than or Equal X", + "slug": "special-array-with-x-elements-greater-than-or-equal-x", + "description": "You are given an array nums of non-negative integers. nums is considered special if there exists a number x such that there are exactly x numbers in nums that are greater than or equal to x. Notice that x does not have to be an element in nums. Return x if the array is special, otherwise, return -1. It can be proven that if nums is special, the value for x is unique. ", + "category": [ + "Array", + "Binary Search", + "Sorting" + ], + "complexity": "Easy", + "successrate": 60.5, + "totalsubmissions": 59654, + "totalaccepted": 36114, + "likes": 732, + "dislikes": 117, + "hints": "Count the number of elements greater than or equal to x for each x in the range [0, nums.length]. If for any x, the condition satisfies, return that x. Otherwise, there is no answer.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [3,5]", + "expected_output": "2", + "explanation": "There are 2 values (3 and 5) that are greater than or equal to 2." + }, + { + "example_num": 2, + "expected_input": "nums = [0,0]", + "expected_output": "-1", + "explanation": "No numbers fit the criteria for x.\nIf x = 0, there should be 0 numbers >= x, but there are 2.\nIf x = 1, there should be 1 number >= x, but there are 0.\nIf x = 2, there should be 2 numbers >= x, but there are 0.\nx cannot be greater since there are only 2 numbers in nums." + }, + { + "example_num": 3, + "expected_input": "nums = [0,4,3,0,4]", + "expected_output": "3", + "explanation": "There are 3 values that are greater than or equal to 3." + } + ], + "solution": "/**\n * @param {number[]} nums\n * @return {number}\n */\nconst specialArray = function(nums) {\n let l = -1, r = 1001\n while(l <= r) {\n const mid = r - Math.floor((r - l) / 2)\n const tmp = valid(mid)\n if(tmp === mid) return mid\n else if(tmp > mid) l = mid + 1\n else r = mid - 1\n }\n return -1\n \n function valid(mid) {\n let res = 0\n for(let e of nums) {\n if(e >= mid) res++\n }\n return res\n }\n};\n\n// another \n\n/**\n * @param {number[]} nums\n * @return {number}\n */\nconst specialArray = function (nums) {\n nums.sort((a, b) => b - a)\n let i = 0\n while(i < nums.length && nums[i] >= i) {\n i++\n }\n if(nums[i - 1] < i) return -1\n return i\n};\n\n// another\n\n/**\n * @param {number[]} nums\n * @return {number}\n */\nconst specialArray = function(nums) {\n nums.sort((a, b) => b - a)\n let left = 0, right = nums.length\n while(left <= right) {\n const mid = left + ((right - left) >> 1)\n if(mid < nums[mid]) left = mid + 1\n else right = mid - 1\n }\n // if we found i == nums[i], there will be i + 1 items\n // larger or equal to i, which makes array not special.\n return left < nums.length && left === nums[left] ? -1 : left\n};\n\n// another\n\n/**\n * @param {number[]} nums\n * @return {number}\n */\nconst specialArray = function(nums) {\n const n = nums.length\n nums.sort((a, b) => b - a)\n let l = 0, r = n\n while(l < r) {\n const mid = l + ((r - l) >> 1)\n if(nums[mid] > mid) l = mid + 1\n else r = mid\n }\n return l < n && l === nums[l] ? -1 : l\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720e0f", + "questionid": 836, + "title": "Count Subtrees With Max Distance Between Cities", + "slug": "count-subtrees-with-max-distance-between-cities", + "description": "There are n cities numbered from 1 to n. You are given an array edges of size n-1, where edges[i] = [ui, vi] represents a bidirectional edge between cities ui and vi. There exists a unique path between each pair of cities. In other words, the cities form a tree. A subtree is a subset of cities where every city is reachable from every other city in the subset, where the path between each pair passes through only the cities from the subset. Two subtrees are different if there is a city in one subtree that is not present in the other. For each d from 1 to n-1, find the number of subtrees in which the maximum distance between any two cities in the subtree is equal to d. Return an array of size n-1 where the dth element (1-indexed) is the number of subtrees in which the maximum distance between any two cities is equal to d. Notice\u00a0that\u00a0the distance between the two cities is the number of edges in the path between them. ", + "category": [ + "Dynamic Programming", + "Bit Manipulation", + "Tree", + "Enumeration", + "Bitmask" + ], + "complexity": "Hard", + "successrate": 65.3, + "totalsubmissions": 9323, + "totalaccepted": 6088, + "likes": 295, + "dislikes": 28, + "hints": "Iterate through every possible subtree by doing a bitmask on which vertices to include. How can you determine if a subtree is valid (all vertices are connected)? To determine connectivity, count the number of reachable vertices starting from any included vertex and only traveling on edges connecting 2 vertices in the subtree. The count should be the same as the number of 1s in the bitmask. The diameter is basically the maximum distance between any two nodes. Root the tree at a vertex. The answer is the max of the heights of the two largest subtrees or the longest diameter in any of the subtrees.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 4, edges = [[1,2],[2,3],[2,4]]", + "expected_output": "[3,4,0]\r\nExplanation:\r\nThe subtrees with subsets {1,2}, {2,3} and {2,4} have a max distance of 1.\r\nThe subtrees with subsets {1,2,3}, {1,2,4}, {2,3,4} and {1,2,3,4} have a max distance of 2.\r\nNo subtree has two nodes where the max distance between them is 3.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "n = 2, edges = [[1,2]]", + "expected_output": "[1]", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "n = 3, edges = [[1,2],[2,3]]", + "expected_output": "[2,1]", + "explanation": "" + } + ], + "solution": "/**\n * @param {number} n\n * @param {number[][]} edges\n * @return {number[]}\n */\nconst countSubgraphsForEachDiameter = function (n, edges) {\n const graph = {};\n for (let [u, v] of edges) {\n if (!graph[u - 1]) graph[u - 1] = [];\n if (!graph[v - 1]) graph[v - 1] = [];\n graph[u - 1].push(v - 1);\n graph[v - 1].push(u - 1);\n }\n let ans = Array(n - 1).fill(0);\n for (let i = 1, len = 2 ** n; i < len; i++) {\n const d = maxDistance(i);\n if (d > 0) ans[d - 1] += 1;\n }\n return ans;\n function bfs(src, cities) {\n const visited = new Set();\n visited.add(src);\n const q = [[src, 0]]; // Pair of (vertex, distance)\n let farthestDist = 0; // Farthest distance from src to other nodes\n while (q.length > 0) {\n const [u, d] = q.shift();\n farthestDist = d;\n for (let v of graph[u]) {\n if (!visited.has(v) && cities.has(v)) {\n visited.add(v);\n q.push([v, d + 1]);\n }\n }\n }\n return [farthestDist, visited];\n }\n function maxDistance(state) {\n // return: maximum distance between any two cities in our subset. O(n^2)\n const cities = new Set();\n for (let i = 0; i < n; i++) {\n if ((state >> i) & (1 === 1)) cities.add(i);\n }\n let ans = 0;\n for (let i of cities) {\n const [farthestDist, visited] = bfs(i, cities);\n if (visited.size < cities.size) return 0; // Can't visit all nodes of the tree -> Invalid tree\n ans = Math.max(ans, farthestDist);\n }\n return ans;\n }\n};\n\n// another\n\n/**\n * @param {number} n\n * @param {number[][]} edges\n * @return {number[]}\n */\nconst countSubgraphsForEachDiameter = function(n, edges) {\n const graph = {}\n for(const [u, v] of edges) {\n if(graph[u - 1] == null) graph[u - 1] = []\n if(graph[v - 1] == null) graph[v - 1] = []\n graph[u - 1].push(v - 1)\n graph[v - 1].push(u - 1)\n }\n const res = Array(n - 1).fill(0)\n \n for(let i = 0, len = 2 ** n; i < len; i++) {\n const dis = maxDistance(i)\n if(dis > 0) res[dis - 1]++\n }\n \n return res\n \n function bfs(src, cities) {\n const visited = new Set([src])\n let q = [[src, 0]]\n let maxDist = 0\n while(q.length) {\n const tmp = []\n const size = q.length\n for(let i = 0; i < size; i++) {\n const [u, d] = q[i]\n maxDist = d\n for(const v of (graph[u] || [])) {\n if(cities.has(v) && !visited.has(v)) {\n visited.add(v)\n tmp.push([v, d + 1])\n }\n }\n }\n \n q = tmp\n }\n \n return [maxDist, visited]\n }\n \n function maxDistance(state) {\n const cities = new Set()\n for(let i = 0; i < n; i++) {\n if(state & (1 << i)) cities.add(i)\n }\n \n let res = 0\n for(const e of cities) {\n const [maxDist, visited] = bfs(e, cities)\n if(visited.size < cities.size) return 0\n res = Math.max(res, maxDist) \n }\n \n return res\n }\n}; \n\n\n" + }, + { + "_id": "66f925ddfdfb8e1665720e13", + "questionid": 840, + "title": "Largest Substring Between Two Equal Characters", + "slug": "largest-substring-between-two-equal-characters", + "description": "Given a string s, return the length of the longest substring between two equal characters, excluding the two characters. If there is no such substring return -1. A substring is a contiguous sequence of characters within a string. ", + "category": [ + "Hash Table", + "String" + ], + "complexity": "Easy", + "successrate": 59.2, + "totalsubmissions": 53135, + "totalaccepted": 31464, + "likes": 377, + "dislikes": 24, + "hints": "Try saving the first and last position of each character Try finding every pair of indexes with equal characters", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "aa"", + "expected_output": "0", + "explanation": "The optimal substring here is an empty substring between the two 'a's." + }, + { + "example_num": 2, + "expected_input": "s = "abca"", + "expected_output": "2", + "explanation": "The optimal substring here is "bc"." + }, + { + "example_num": 3, + "expected_input": "s = "cbzxy"", + "expected_output": "-1", + "explanation": "There are no characters that appear twice in s." + } + ], + "solution": "/**\n * @param {string} s\n * @return {number}\n */\nconst maxLengthBetweenEqualCharacters = function(s) {\n const m = {}\n if(s ==null || s.length <= 1) return -1\n let res = -1\n for(let i = 0, len = s.length; i< len;i++) {\n if(m[s[i]] != null) {\n res = Math.max(res, i - m[s[i]] - 1)\n } else {\n m[s[i]] = i\n }\n \n }\n return res\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720e16", + "questionid": 843, + "title": "Path With Minimum Effort", + "slug": "path-with-minimum-effort", + "description": "You are a hiker preparing for an upcoming hike. You are given heights, a 2D array of size rows x columns, where heights[row][col] represents the height of cell (row, col). You are situated in the top-left cell, (0, 0), and you hope to travel to the bottom-right cell, (rows-1, columns-1) (i.e.,\u00a00-indexed). You can move up, down, left, or right, and you wish to find a route that requires the minimum effort. A route's effort is the maximum absolute difference in heights between two consecutive cells of the route. Return the minimum effort required to travel from the top-left cell to the bottom-right cell. ", + "category": [ + "Array", + "Binary Search", + "Depth-First Search", + "Breadth-First Search", + "Union Find", + "Heap (Priority Queue)", + "Matrix" + ], + "complexity": "Medium", + "successrate": 52, + "totalsubmissions": 142763, + "totalaccepted": 74173, + "likes": 2084, + "dislikes": 98, + "hints": "Consider the grid as a graph, where adjacent cells have an edge with cost of the difference between the cells. If you are given threshold k, check if it is possible to go from (0, 0) to (n-1, m-1) using only edges of \u2030\u00a4 k cost. Binary search the k value.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "heights = [[1,2,2],[3,8,2],[5,3,5]]", + "expected_output": "2", + "explanation": "The route of [1,3,5,3,5] has a maximum absolute difference of 2 in consecutive cells.\nThis is better than the route of [1,2,2,2,5], where the maximum absolute difference is 3." + }, + { + "example_num": 2, + "expected_input": "heights = [[1,2,3],[3,8,4],[5,3,5]]", + "expected_output": "1", + "explanation": "The route of [1,2,3,4,5] has a maximum absolute difference of 1 in consecutive cells, which is better than route [1,3,5,3,5]." + }, + { + "example_num": 3, + "expected_input": "heights = [[1,2,1,1,1],[1,2,1,2,1],[1,2,1,2,1],[1,2,1,2,1],[1,1,1,2,1]]", + "expected_output": "0", + "explanation": "This route does not require any effort." + } + ], + "solution": "/**\n * @param {number[][]} heights\n * @return {number}\n */\nconst minimumEffortPath = function(heights) {\n const m = heights.length, n = heights[0].length\n const { abs, floor } = Math\n let l = 0, r= 1e6\n \n while(l < r) {\n const mid = l + floor((r- l) /2)\n if(valid(mid)) {\n r = mid\n } else {\n l = mid + 1\n }\n }\n \n return l\n \n function valid(effort) {\n const visited = Array.from({length:m}, () => Array(n).fill(0))\n const dirs = [[1,0],[-1,0],[0,1],[0,-1]]\n let q = []\n q.push([0, 0])\n visited[0][0] = 1\n while(q.length) {\n const [x, y] = q.shift()\n for(const [dx, dy] of dirs) {\n const nx = x + dx, ny = y + dy\n if(nx<0 || nx>=m || ny < 0 || ny >= n) continue\n if(visited[nx][ny]) continue\n if(abs(heights[nx][ny] - heights[x][y]) > effort) continue\n q.push([nx,ny])\n visited[nx][ny] = 1\n }\n }\n \n return visited[m - 1][n - 1] === 1\n }\n};\n\n// another\n\n/**\n * @param {number[][]} heights\n * @return {number}\n */\nconst minimumEffortPath = function(heights) {\n const m = heights.length, n = heights[0].length\n const dirs = [[1, 0], [-1, 0], [0, 1], [0, -1]]\n let l = 0, r = 1e6 - 1\n \n while(l < r) {\n const mid = ~~((l + r) / 2)\n // console.log(l, r, mid)\n if(valid(mid)) {\n r = mid\n } else {\n l = mid + 1\n }\n }\n \n return l\n \n function valid(limit) {\n const visited = Array.from({ length: m }, () => Array(n).fill(false))\n return dfs(0, 0, limit, visited)\n }\n \n function dfs(i, j, limit, visited) {\n if(i === m - 1 && j === n - 1) return true\n visited[i][j] = true\n for(const [dx, dy] of dirs) {\n const nx = i + dx, ny = j + dy\n if(nx < 0 || nx >= m || ny < 0 || ny >= n) continue\n if(visited[nx][ny]) continue\n if(Math.abs(heights[i][j] - heights[nx][ny]) > limit) continue\n if(dfs(nx, ny, limit, visited)) return true\n }\n // return false\n }\n\n};\n\n// another\n\n\n\n/**\n * @param {number[][]} heights\n * @return {number}\n */\nconst minimumEffortPath = function(heights) {\n const m = heights.length, n = heights[0].length\n const pq = new PriorityQueue()\n const dist = Array.from({ length: m }, () => Array(n).fill(Infinity))\n pq.push([0, 0, 0])\n dist[0][0] = 0\n const dirs = [[-1, 0], [1, 0], [0, 1], [0, -1]]\n while(!pq.isEmpty()) {\n const [v, i, j] = pq.pop()\n if(i === m - 1 && j === n - 1) return v\n for(const [dx, dy] of dirs) {\n const nx = i + dx, ny = j + dy\n if(nx < 0 || nx >= m || ny < 0 || ny >= n) continue\n const diff = Math.max(v, Math.abs(heights[nx][ny] - heights[i][j]))\n if(dist[nx][ny] > diff) {\n dist[nx][ny] = diff\n pq.push([diff, nx, ny])\n }\n }\n }\n return -1\n};\n\nclass PriorityQueue {\n constructor(comparator = (a, b) => a[0] < b[0]) {\n this.heap = []\n this.top = 0\n this.comparator = comparator\n }\n size() {\n return this.heap.length\n }\n isEmpty() {\n return this.size() === 0\n }\n peek() {\n return this.heap[this.top]\n }\n push(...values) {\n values.forEach((value) => {\n this.heap.push(value)\n this.siftUp()\n })\n return this.size()\n }\n pop() {\n const poppedValue = this.peek()\n const bottom = this.size() - 1\n if (bottom > this.top) {\n this.swap(this.top, bottom)\n }\n this.heap.pop()\n this.siftDown()\n return poppedValue\n }\n replace(value) {\n const replacedValue = this.peek()\n this.heap[this.top] = value\n this.siftDown()\n return replacedValue\n }\n\n parent = (i) => ((i + 1) >>> 1) - 1\n left = (i) => (i << 1) + 1\n right = (i) => (i + 1) << 1\n greater = (i, j) => this.comparator(this.heap[i], this.heap[j])\n swap = (i, j) => ([this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]])\n siftUp = () => {\n let node = this.size() - 1\n while (node > this.top && this.greater(node, this.parent(node))) {\n this.swap(node, this.parent(node))\n node = this.parent(node)\n }\n }\n siftDown = () => {\n let node = this.top\n while (\n (this.left(node) < this.size() && this.greater(this.left(node), node)) ||\n (this.right(node) < this.size() && this.greater(this.right(node), node))\n ) {\n let maxChild =\n this.right(node) < this.size() &&\n this.greater(this.right(node), this.left(node))\n ? this.right(node)\n : this.left(node)\n this.swap(node, maxChild)\n node = maxChild\n }\n }\n}\n\n// another\n\n/**\n * @param {number[][]} heights\n * @return {number}\n */\nconst minimumEffortPath = function (heights) {\n const d = [0, 1, 0, -1, 0]\n let lo = 0,\n hi = 10 ** 6 + 1\n while (lo < hi) {\n let effort = lo + ((hi - lo) >> 1)\n if (isPath(heights, effort)) {\n hi = effort\n } else {\n lo = effort + 1\n }\n }\n return lo\n function isPath(h, effort) {\n const m = h.length,\n n = h[0].length\n const q = []\n q.push([0, 0])\n const seen = new Set()\n seen.add(0)\n while (q.length) {\n const cur = q.shift()\n const x = cur[0],\n y = cur[1]\n if (x === m - 1 && y === n - 1) {\n return true\n }\n for (let k = 0; k < 4; k++) {\n const r = x + d[k],\n c = y + d[k + 1]\n if(seen.has(r * n + c)) continue\n if (\n 0 <= r &&\n r < m &&\n 0 <= c &&\n c < n &&\n effort >= Math.abs(h[r][c] - h[x][y])\n ) {\n seen.add(r * n + c)\n q.push([r, c])\n }\n }\n }\n return false\n }\n}\n\n// another\n\n/**\n * @param {number[][]} heights\n * @return {number}\n */\nconst minimumEffortPath = function(heights) {\n const rows = heights.length\n const cols = heights[0].length\n const dirs = [[-1, 0], [1, 0], [0, 1], [0, -1]]\n const dist = Array.from({ length: rows }, () => Array(cols).fill(Infinity))\n const pq = new PriorityQueue()\n pq.push([0, 0, 0])\n dist[0][0] = 0\n while(pq.size) {\n const cur = pq.pop()\n if(cur[1] === rows - 1 && cur[2] === cols - 1) return cur[0]\n for(let dir of dirs) {\n const nr = cur[1] + dir[0]\n const nc = cur[2] + dir[1]\n if(nr < 0 || nr >= rows || nc < 0 || nc >= cols) continue\n const diff = Math.max(cur[0], Math.abs(heights[nr][nc] - heights[cur[1]][cur[2]]))\n if(dist[nr][nc] > diff) {\n dist[nr][nc] = diff\n pq.push([diff, nr, nc])\n }\n }\n }\n return 0\n};\n\nclass PriorityQueue {\n constructor(comparator = (a, b) => a[0] < b[0]) {\n this.heap = []\n this.top = 0\n this.comparator = comparator\n }\n size() {\n return this.heap.length\n }\n isEmpty() {\n return this.size() === 0\n }\n peek() {\n return this.heap[this.top]\n }\n push(...values) {\n values.forEach((value) => {\n this.heap.push(value)\n this.siftUp()\n })\n return this.size()\n }\n pop() {\n const poppedValue = this.peek()\n const bottom = this.size() - 1\n if (bottom > this.top) {\n this.swap(this.top, bottom)\n }\n this.heap.pop()\n this.siftDown()\n return poppedValue\n }\n replace(value) {\n const replacedValue = this.peek()\n this.heap[this.top] = value\n this.siftDown()\n return replacedValue\n }\n\n parent = (i) => ((i + 1) >>> 1) - 1\n left = (i) => (i << 1) + 1\n right = (i) => (i + 1) << 1\n greater = (i, j) => this.comparator(this.heap[i], this.heap[j])\n swap = (i, j) => ([this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]])\n siftUp = () => {\n let node = this.size() - 1\n while (node > this.top && this.greater(node, this.parent(node))) {\n this.swap(node, this.parent(node))\n node = this.parent(node)\n }\n }\n siftDown = () => {\n let node = this.top\n while (\n (this.left(node) < this.size() && this.greater(this.left(node), node)) ||\n (this.right(node) < this.size() && this.greater(this.right(node), node))\n ) {\n let maxChild =\n this.right(node) < this.size() &&\n this.greater(this.right(node), this.left(node))\n ? this.right(node)\n : this.left(node)\n this.swap(node, maxChild)\n node = maxChild\n }\n }\n}\n\n" + }, + { + "_id": "66f925ddfdfb8e1665720e1a", + "questionid": 847, + "title": "Count Sorted Vowel Strings", + "slug": "count-sorted-vowel-strings", + "description": "Given an integer n, return the number of strings of length n that consist only of vowels (a, e, i, o, u) and are lexicographically sorted. A string s is lexicographically sorted if for all valid i, s[i] is the same as or comes before s[i+1] in the alphabet. ", + "category": [ + "Dynamic Programming" + ], + "complexity": "Medium", + "successrate": 74.9, + "totalsubmissions": 110393, + "totalaccepted": 82665, + "likes": 1763, + "dislikes": 38, + "hints": "For each character, its possible values will depend on the value of its previous character, because it needs to be not smaller than it. Think backtracking. Build a recursive function count(n, last_character) that counts the number of valid strings of length n and whose first characters are not less than last_character. In this recursive function, iterate on the possible characters for the first character, which will be all the vowels not less than last_character, and for each possible value c, increase the answer by count(n-1, c).", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 1", + "expected_output": "5", + "explanation": "The 5 sorted strings that consist of vowels only are ["a","e","i","o","u"]." + }, + { + "example_num": 2, + "expected_input": "n = 2", + "expected_output": "15", + "explanation": "The 15 sorted strings that consist of vowels only are\n["aa","ae","ai","ao","au","ee","ei","eo","eu","ii","io","iu","oo","ou","uu"].\nNote that "ea" is not a valid string since 'e' comes after 'a' in the alphabet." + }, + { + "example_num": 3, + "expected_input": "n = 33", + "expected_output": "66045", + "explanation": "" + } + ], + "solution": "/**\n * @param {number} n\n * @return {number}\n */\nconst countVowelStrings = function (n) {\n return (n + 4) * (n + 3) * (n + 2) * (n + 1) / 24\n};\n\n// another\n\n/**\n * @param {number} n\n * @return {number}\n */\nconst countVowelStrings = function (n) {\n let mem = [1, 1, 1, 1, 1];\n for (let i = 1; i < n; ++i) {\n const next = [0, 0, 0, 0, 0];\n let tmp = 0;\n for (let j = 4; j >= 0; --j) {\n tmp += mem[j];\n next[j] = tmp;\n }\n mem = next;\n }\n let sum = 0;\n for (let i of mem) {\n sum += i;\n }\n return sum;\n};\n\n// another\n\n/**\n * @param {number} n\n * @return {number}\n */\nconst countVowelStrings = function (n) {\n const dp = Array.from({ length: n + 1 }, () => Array(5))\n recur(n, 0)\n return dp[n][0]\n function recur(r, i) {\n if(r === 0) return 1\n if(i === 5) return 0\n if(dp[r][i] != null) return dp[r][i]\n let res = recur(r, i + 1)\n res += recur(r - 1, i)\n return dp[r][i] = res\n }\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720e1e", + "questionid": 851, + "title": "Sell Diminishing-Valued Colored Balls", + "slug": "sell-diminishing-valued-colored-balls", + "description": "You have an inventory of different colored balls, and there is a customer that wants orders balls of any color. The customer weirdly values the colored balls. Each colored ball's value is the number of balls of that color\u00a0you currently have in your inventory. For example, if you own 6 yellow balls, the customer would pay 6 for the first yellow ball. After the transaction, there are only 5 yellow balls left, so the next yellow ball is then valued at 5 (i.e., the value of the balls decreases as you sell more to the customer). You are given an integer array, inventory, where inventory[i] represents the number of balls of the ith color that you initially own. You are also given an integer orders, which represents the total number of balls that the customer wants. You can sell the balls in any order. Return the maximum total value that you can attain after selling orders colored balls. As the answer may be too large, return it modulo 109 + 7. ", + "category": [ + "Array", + "Math", + "Binary Search", + "Greedy", + "Sorting", + "Heap (Priority Queue)" + ], + "complexity": "Medium", + "successrate": 30.6, + "totalsubmissions": 90962, + "totalaccepted": 27814, + "likes": 718, + "dislikes": 273, + "hints": "Greedily sell the most expensive ball. There is some value k where all balls of value > k are sold, and some, (maybe 0) of balls of value k are sold. Use binary search to find this value k, and use maths to find the total sum.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "inventory = [2,5], orders = 4", + "expected_output": "14", + "explanation": "Sell the 1st color 1 time (2) and the 2nd color 3 times (5 + 4 + 3).\nThe maximum total value is 2 + 5 + 4 + 3 = 14." + }, + { + "example_num": 2, + "expected_input": "inventory = [3,5], orders = 6", + "expected_output": "19\nExplanation: Sell the 1st color 2 times (3 + 2) and the 2nd color 4 times (5 + 4 + 3 + 2).\nThe maximum total value is 3 + 2 + 5 + 4 + 3 + 2 = 19.", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} inventory\n * @param {number} orders\n * @return {number}\n */\nconst maxProfit = function(inventory, orders) {\n const bigIntMax = (...args) => args.reduce((m, e) => e > m ? e : m);\n inventory = inventory.map(e => BigInt(e))\n orders = BigInt(orders)\n let l = 0n, r = bigIntMax(...inventory)\n while(l < r) {\n const mid = l + (r - l) / 2n\n if(valid(mid)) l = mid + 1n\n else r = mid\n }\n \n // console.log(l)\n const mod = BigInt(1e9 + 7)\n let t = l, res = 0n, cnt = 0n\n for(const e of inventory) {\n if(e <= t) continue\n cnt += e - t\n res = (res + (t + 1n + e) * (e - t) / 2n) % mod\n }\n \n res = (res + (orders - cnt) * t) % mod\n \n return res\n \n function valid(mid) {\n let res = 0n\n for(const e of inventory) {\n if(e > mid) res += e - mid\n }\n return res > orders\n }\n};\n\n// another\n\n/**\n * @param {number[]} inventory\n * @param {number} orders\n * @return {number}\n */\nfunction maxProfit(inventory, orders) {\n inventory.sort((a, b) => a - b)\n inventory = inventory.map(e => BigInt(e))\n let ans = 0n, n = inventory.length - 1, count = 1n\n const mod = BigInt(10 ** 9 + 7)\n orders = BigInt(orders)\n while(orders > 0n) {\n if(n > 0 && inventory[n] > inventory[n - 1] && orders >= count * (inventory[n] - inventory[n - 1])) {\n ans += count * sum(inventory[n - 1], inventory[n])\n orders -= count * (inventory[n] - inventory[n - 1])\n } else if(n === 0 || inventory[n] > inventory[n - 1]) {\n const num = orders / count\n ans += count * sum(inventory[n] - num, inventory[n])\n const remain = orders % count\n ans += remain * (inventory[n] - num)\n orders = 0n\n }\n ans %= mod\n n--\n count++\n }\n return ans\n}\n\nfunction sum(lo, hi) {\n return (hi - lo) * (lo + hi + 1n) / 2n\n}\n\n// another\n\n/**\n * @param {number[]} inventory\n * @param {number} orders\n * @return {number}\n */\nconst maxProfit = function (inventory, orders) {\n let Max = 1e9 + 7,\n Min = 0\n let mod = BigInt(1e9 + 7)\n while (Max > Min + 1) {\n let tot = 0\n let mid = ((Max + Min) >> 1)\n for (let it of inventory) {\n if (it > mid) tot += it - mid\n }\n if (tot > orders) Min = mid\n else Max = mid\n }\n let sum = BigInt(0)\n Max = BigInt(Max)\n orders = BigInt(orders)\n for (let it of inventory) {\n it = BigInt(it)\n if (it > Max) {\n sum += ((it + Max + BigInt(1)) * (it - Max)) / BigInt(2)\n orders -= it - Max\n }\n }\n sum += orders * Max\n \n return sum % mod\n}\n\n// another\n\n/**\n * @param {number[]} inventory\n * @param {number} orders\n * @return {number}\n */\nvar maxProfit = function(inventory, orders) {\n inventory.sort((a, b) => b - a)\n const mod = BigInt(1e9 + 7), n = BigInt(inventory.length)\n inventory = inventory.map(e => BigInt(e))\n orders = BigInt(orders)\n let cur = BigInt(inventory[0]), res = 0n, i = 0n\n const min = (a, b) => a > b ? b : a\n while(orders) {\n while(i < n && inventory[i] === cur) i++\n let next = i === n ? 0n : inventory[i]\n let h = cur - next, r = 0n, cnt = min(orders, i * h)\n if (orders < i * h) {\n h = orders / i\n r = orders % i\n }\n let val = cur - h\n res = (res + (cur + val + 1n) * h / 2n * i + val * r) % mod\n orders -= cnt\n cur = next\n }\n\n return res\n};\n\n// another\n\n/**\n * @param {number[]} inventory\n * @param {number} orders\n * @return {number}\n */\nconst maxProfit = function (inventory, orders) {\n inventory.sort((a, b) => b - a)\n const mod = BigInt(1e9 + 7),\n n = BigInt(inventory.length)\n inventory = inventory.map((e) => BigInt(e))\n orders = BigInt(orders)\n let cur = BigInt(inventory[0]),\n res = 0n,\n i = 0n\n const min = (a, b) => (a > b ? b : a)\n while (orders) {\n while (i < n && inventory[i] === cur) i++\n let next = i === n ? 0n : inventory[i]\n let h = cur - next,\n r = 0n,\n cnt = min(orders, i * h)\n if (orders < i * h) {\n h = orders / i\n r = orders % i\n }\n let val = cur - h\n res = (res + (((cur + val + 1n) * h) / 2n) * i + val * r) % mod\n orders -= cnt\n cur = next\n }\n\n return res\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720e24", + "questionid": 857, + "title": "Richest Customer Wealth", + "slug": "richest-customer-wealth", + "description": "You are given an m x n integer grid accounts where accounts[i][j] is the amount of money the i\u200b\u200b\u200b\u200b\u200b\u200b\u200b\u200b\u200b\u200b\u200bth\u200b\u200b\u200b\u200b customer has in the j\u200b\u200b\u200b\u200b\u200b\u200b\u200b\u200b\u200b\u200b\u200bth bank. Return the wealth that the richest customer has. A customer's wealth is the amount of money they have in all their bank accounts. The richest customer is the customer that has the maximum wealth. ", + "category": [ + "Array", + "Matrix" + ], + "complexity": "Easy", + "successrate": 89.3, + "totalsubmissions": 310405, + "totalaccepted": 277200, + "likes": 1770, + "dislikes": 256, + "hints": "Calculate the wealth of each customer Find the maximum element in array.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "accounts = [[1,2,3],[3,2,1]]", + "expected_output": "6\nExplanation:\n1st customer has wealth = 1 + 2 + 3 = 6\n2nd customer has wealth = 3 + 2 + 1 = 6\nBoth customers are considered the richest with a wealth of 6 each, so return 6.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "accounts = [[1,5],[7,3],[3,5]]", + "expected_output": "10\nExplanation: \n1st customer has wealth = 6\n2nd customer has wealth = 10 \n3rd customer has wealth = 8\nThe 2nd customer is the richest with a wealth of 10.", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "accounts = [[2,8,7],[7,1,3],[1,9,5]]", + "expected_output": "17", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[][]} accounts\n * @return {number}\n */\nconst maximumWealth = function(accounts) {\n let max = -Infinity\n const m = accounts.length, n = accounts[0].length\n for(let i = 0; i < m; i++) {\n let tmp = 0\n for(let j = 0; j < n; j++) {\n tmp += accounts[i][j]\n }\n max = Math.max(max, tmp)\n }\n return max\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720e2c", + "questionid": 865, + "title": "Partitioning Into Minimum Number Of Deci-Binary Numbers", + "slug": "partitioning-into-minimum-number-of-deci-binary-numbers", + "description": "A decimal number is called deci-binary if each of its digits is either 0 or 1 without any leading zeros. For example, 101 and 1100 are deci-binary, while 112 and 3001 are not. Given a string n that represents a positive decimal integer, return the minimum number of positive deci-binary numbers needed so that they sum up to n. ", + "category": [ + "String", + "Greedy" + ], + "complexity": "Medium", + "successrate": 87.8, + "totalsubmissions": 86815, + "totalaccepted": 76222, + "likes": 789, + "dislikes": 559, + "hints": "Think about if the input was only one digit. Then you need to add up as many ones as the value of this digit. If the input has multiple digits, then you can solve for each digit independently, and merge the answers to form numbers that add up to that input. Thus the answer is equal to the max digit.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = "32"", + "expected_output": "3", + "explanation": "10 + 11 + 11 = 32" + }, + { + "example_num": 2, + "expected_input": "n = "82734"", + "expected_output": "8", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "n = "27346209830709182346"", + "expected_output": "9", + "explanation": "" + } + ], + "solution": "/**\n * @param {string} n\n * @return {number}\n */\nvar minPartitions = function(n) {\n let res = 0\n const arr = n.split('').map(e => parseInt(e))\n for(let i = 0, len = arr.length; i < len; i++) {\n res = Math.max(arr[i], res)\n }\n return res\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720e34", + "questionid": 873, + "title": "Maximum Number of Eaten Apples", + "slug": "maximum-number-of-eaten-apples", + "description": "There is a special kind of apple tree that grows apples every day for n days. On the ith day, the tree grows apples[i] apples that will rot after days[i] days, that is on day i + days[i] the apples will be rotten and cannot be eaten. On some days, the apple tree does not grow any apples, which are denoted by apples[i] == 0 and days[i] == 0. You decided to eat at most one apple a day (to keep the doctors away). Note that you can keep eating after the first n days. Given two integer arrays days and apples of length n, return the maximum number of apples you can eat. ", + "category": [ + "Array", + "Greedy", + "Heap (Priority Queue)" + ], + "complexity": "Medium", + "successrate": 36.4, + "totalsubmissions": 38800, + "totalaccepted": 14118, + "likes": 489, + "dislikes": 145, + "hints": "It's optimal to finish the apples that will rot first before those that will rot last You need a structure to keep the apples sorted by their finish time", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "apples = [1,2,3,5,2], days = [3,2,1,4,2]", + "expected_output": "7", + "explanation": "You can eat 7 apples:\n- On the first day, you eat an apple that grew on the first day.\n- On the second day, you eat an apple that grew on the second day.\n- On the third day, you eat an apple that grew on the second day. After this day, the apples that grew on the third day rot.\n- On the fourth to the seventh days, you eat apples that grew on the fourth day." + }, + { + "example_num": 2, + "expected_input": "apples = [3,0,0,0,0,2], days = [3,0,0,0,0,2]", + "expected_output": "5", + "explanation": "You can eat 5 apples:\n- On the first to the third day you eat apples that grew on the first day.\n- Do nothing on the fouth and fifth days.\n- On the sixth and seventh days you eat apples that grew on the sixth day." + } + ], + "solution": "/**\n * @param {number[]} apples\n * @param {number[]} days\n * @return {number}\n */\nconst eatenApples = function (apples, days) {\n const n = apples.length\n let fin = 0,\n i = 0\n const q = new PriorityQueue()\n while (i < n || !q.isEmpty()) {\n if (i < n && apples[i] > 0) q.push([i + days[i], apples[i]])\n while (!q.isEmpty() && (q.peek()[0] <= i || q.peek()[1] === 0)) q.pop()\n if (!q.isEmpty()) {\n q.peek()[1] -= 1\n if(q.peek()[1] <= 0) q.pop()\n fin += 1\n }\n i += 1\n }\n return fin\n}\n\nclass PriorityQueue {\n constructor(comparator = (a, b) => a[0] < b[0]) {\n this.heap = []\n this.top = 0\n this.comparator = comparator\n }\n size() {\n return this.heap.length\n }\n isEmpty() {\n return this.size() === 0\n }\n peek() {\n return this.heap[this.top]\n }\n push(...values) {\n values.forEach((value) => {\n this.heap.push(value)\n this.siftUp()\n })\n return this.size()\n }\n pop() {\n const poppedValue = this.peek()\n const bottom = this.size() - 1\n if (bottom > this.top) {\n this.swap(this.top, bottom)\n }\n this.heap.pop()\n this.siftDown()\n return poppedValue\n }\n replace(value) {\n const replacedValue = this.peek()\n this.heap[this.top] = value\n this.siftDown()\n return replacedValue\n }\n\n parent = (i) => ((i + 1) >>> 1) - 1\n left = (i) => (i << 1) + 1\n right = (i) => (i + 1) << 1\n greater = (i, j) => this.comparator(this.heap[i], this.heap[j])\n swap = (i, j) => ([this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]])\n siftUp = () => {\n let node = this.size() - 1\n while (node > this.top && this.greater(node, this.parent(node))) {\n this.swap(node, this.parent(node))\n node = this.parent(node)\n }\n }\n siftDown = () => {\n let node = this.top\n while (\n (this.left(node) < this.size() && this.greater(this.left(node), node)) ||\n (this.right(node) < this.size() && this.greater(this.right(node), node))\n ) {\n let maxChild =\n this.right(node) < this.size() &&\n this.greater(this.right(node), this.left(node))\n ? this.right(node)\n : this.left(node)\n this.swap(node, maxChild)\n node = maxChild\n }\n }\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720e3d", + "questionid": 882, + "title": "Minimize Hamming Distance After Swap Operations", + "slug": "minimize-hamming-distance-after-swap-operations", + "description": "You are given two integer arrays, source and target, both of length n. You are also given an array allowedSwaps where each allowedSwaps[i] = [ai, bi] indicates that you are allowed to swap the elements at index ai and index bi (0-indexed) of array source. Note that you can swap elements at a specific pair of indices multiple times and in any order. The Hamming distance of two arrays of the same length, source and target, is the number of positions where the elements are different. Formally, it is the number of indices i for 0 <= i <= n-1 where source[i] != target[i] (0-indexed). Return the minimum Hamming distance of source and target after performing any amount of swap operations on array source. ", + "category": [ + "Array", + "Depth-First Search", + "Union Find" + ], + "complexity": "Medium", + "successrate": 47.9, + "totalsubmissions": 25012, + "totalaccepted": 11985, + "likes": 567, + "dislikes": 17, + "hints": "The source array can be imagined as a graph where each index is a node and each allowedSwaps[i] is an edge. Nodes within the same component can be freely swapped with each other. For each component, find the number of common elements. The elements that are not in common will contribute to the total Hamming distance.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "source = [1,2,3,4], target = [2,1,4,5], allowedSwaps = [[0,1],[2,3]]", + "expected_output": "1", + "explanation": "source can be transformed the following way:\n- Swap indices 0 and 1: source = [2,1,3,4]\n- Swap indices 2 and 3: source = [2,1,4,3]\nThe Hamming distance of source and target is 1 as they differ in 1 position: index 3." + }, + { + "example_num": 2, + "expected_input": "source = [1,2,3,4], target = [1,3,2,4], allowedSwaps = []", + "expected_output": "2", + "explanation": "There are no allowed swaps.\nThe Hamming distance of source and target is 2 as they differ in 2 positions: index 1 and index 2." + }, + { + "example_num": 3, + "expected_input": "source = [5,1,2,4,3], target = [1,5,4,2,3], allowedSwaps = [[0,4],[4,2],[1,3],[1,4]]", + "expected_output": "0", + "explanation": "" + } + ], + "solution": "class UnionFind {\n constructor(n) {\n this.parents = Array(n)\n .fill(0)\n .map((e, i) => i)\n this.ranks = Array(n).fill(0)\n }\n root(x) {\n while (x !== this.parents[x]) {\n this.parents[x] = this.parents[this.parents[x]]\n x = this.parents[x]\n }\n return x\n }\n find(x) {\n return this.root(x)\n }\n check(x, y) {\n return this.root(x) === this.root(y)\n }\n union(x, y) {\n const [rx, ry] = [this.find(x), this.find(y)]\n if (this.ranks[rx] >= this.ranks[ry]) {\n this.parents[ry] = rx\n this.ranks[rx] += this.ranks[ry]\n } else if (this.ranks[ry] > this.ranks[rx]) {\n this.parents[rx] = ry\n this.ranks[ry] += this.ranks[rx]\n }\n }\n}\n/**\n * @param {number[]} source\n * @param {number[]} target\n * @param {number[][]} allowedSwaps\n * @return {number}\n */\nconst minimumHammingDistance = function (source, target, allowedSwaps) {\n const n = target.length\n const uf = new UnionFind(n)\n for (let A of allowedSwaps) {\n const i = A[0],\n j = A[1]\n uf.union(i, j)\n }\n const M = {}\n for (let i = 0; i < n; i++) {\n const j = uf.find(i)\n if (M[j] == null) M[j] = {}\n if (M[j][source[i]] == null) M[j][source[i]] = 0\n M[j][source[i]]++\n }\n let res = 0\n for (let i = 0; i < n; i++) {\n const j = uf.find(i)\n if (M[j][target[i]]) {\n if (!--M[j][target[i]]) {\n delete M[j][target[i]]\n }\n } else res++\n }\n return res\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720e3e", + "questionid": 883, + "title": "Number Of Rectangles That Can Form The Largest Square", + "slug": "number-of-rectangles-that-can-form-the-largest-square", + "description": "You are given an array rectangles where rectangles[i] = [li, wi] represents the ith rectangle of length li and width wi. You can cut the ith rectangle to form a square with a side length of k if both k <= li and k <= wi. For example, if you have a rectangle [4,6], you can cut it to get a square with a side length of at most 4. Let maxLen be the side length of the largest square you can obtain from any of the given rectangles. Return the number of rectangles that can make a square with a side length of maxLen. ", + "category": [ + "Array" + ], + "complexity": "Easy", + "successrate": 78.8, + "totalsubmissions": 51652, + "totalaccepted": 40686, + "likes": 333, + "dislikes": 40, + "hints": "What is the length of the largest square the can be cut out of some rectangle? It'll be equal to min(rectangle.length, rectangle.width). Replace each rectangle with this value. Calculate maxSize by iterating over the given rectangles and maximizing the answer with their values denoted in the first hint. Then iterate again on the rectangles and calculate the number whose values = maxSize.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "rectangles = [[5,8],[3,9],[5,12],[16,5]]", + "expected_output": "3", + "explanation": "The largest squares you can get from each rectangle are of lengths [5,3,5,5].\r\nThe largest possible square is of length 5, and you can get it out of 3 rectangles." + }, + { + "example_num": 2, + "expected_input": "rectangles = [[2,3],[3,7],[4,3],[3,7]]", + "expected_output": "3", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[][]} rectangles\n * @return {number}\n */\nconst countGoodRectangles = function(A) {\n const arr = []\n let max = 0\n A.forEach(e => {\n const tmp = Math.min(...e)\n if(tmp > max) max=tmp\n arr.push(tmp)\n })\n let res = 0\n for(let e of arr) {\n if(e >= max) res++\n }\n return res\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720e46", + "questionid": 891, + "title": "Form Array by Concatenating Subarrays of Another Array", + "slug": "form-array-by-concatenating-subarrays-of-another-array", + "description": "You are given a 2D integer array groups of length n. You are also given an integer array nums. You are asked if you can choose n disjoint subarrays from the array nums such that the ith subarray is equal to groups[i] (0-indexed), and if i > 0, the (i-1)th subarray appears before the ith subarray in nums (i.e. the subarrays must be in the same order as groups). Return true if you can do this task, and false otherwise. Note that the subarrays are disjoint if and only if there is no index k such that nums[k] belongs to more than one subarray. A subarray is a contiguous sequence of elements within an array. ", + "category": [ + "Array", + "Greedy", + "String Matching" + ], + "complexity": "Medium", + "successrate": 53, + "totalsubmissions": 19359, + "totalaccepted": 10259, + "likes": 202, + "dislikes": 21, + "hints": "When we use a subarray, the room for the next subarrays will be the suffix after the used subarray. If we can match a group with multiple subarrays, we should choose the first one, as this will just leave the largest room for the next subarrays.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "groups = [[1,-1,-1],[3,-2,0]], nums = [1,-1,0,1,-1,-1,3,-2,0]", + "expected_output": "true", + "explanation": "You can choose the 0th subarray as [1,-1,0,1,-1,-1,3,-2,0] and the 1st one as [1,-1,0,1,-1,-1,3,-2,0].\nThese subarrays are disjoint as they share no common nums[k] element." + }, + { + "example_num": 2, + "expected_input": "groups = [[10,-2],[1,2,3,4]], nums = [1,2,3,4,10,-2]", + "expected_output": "false\nExplanation: Note that choosing the subarrays [1,2,3,4,10,-2] and [1,2,3,4,10,-2] is incorrect because they are not in the same order as in groups.\n[10,-2] must come before [1,2,3,4].", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "groups = [[1,2,3],[3,4]], nums = [7,7,1,2,3,4,7,7]", + "expected_output": "false\nExplanation: Note that choosing the subarrays [7,7,1,2,3,4,7,7] and [7,7,1,2,3,4,7,7] is invalid because they are not disjoint.\nThey share a common elements nums[4] (0-indexed).", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[][]} groups\n * @param {number[]} nums\n * @return {boolean}\n */\nconst canChoose = function (groups, nums) {\n const dp = new Array(1000).fill(0)\n const lsps = preprocess(groups)\n let cur = 0\n for (let i = 0; i < groups.length; i++) {\n if (cur >= nums.length) return false\n cur = find(nums, cur, groups[i], lsps[i])\n if (cur === -1) return false\n cur += groups[i].length\n }\n return true\n function find(nums, cur, p, lsp) {\n const n = nums.length\n dp[cur] = p[0] === nums[cur] ? 1 : 0\n if (lsp.length === 1 && dp[cur] === 1) {\n return cur\n }\n for (let i = cur + 1; i < n; i++) {\n let j = dp[i - 1]\n while (j > 0 && p[j] !== nums[i]) {\n j = lsp[j - 1]\n }\n dp[i] = j + (p[j] === nums[i])\n if (dp[i] === p.length) {\n return i - p.length + 1\n }\n }\n return -1\n }\n\n function preprocess(groups) {\n const rets = []\n for (let g of groups) {\n const n = g.length\n const dp = new Array(n)\n dp[0] = 0\n for (let i = 1; i < n; i++) {\n let j = dp[i - 1]\n while (j > 0 && g[j] !== g[i]) {\n j = dp[j - 1]\n }\n dp[i] = j + (g[j] === g[i] ? 1 : 0)\n }\n rets.push(dp)\n }\n return rets\n }\n}\n\n// another\n\n/**\n * @param {number[][]} groups\n * @param {number[]} nums\n * @return {boolean}\n */\nconst canChoose = function (groups, nums) {\n const m = nums.length\n let index = 0\n for (let group of groups) {\n const n = group.length\n // Step-1 Generate LPS\n const lps = Array(n).fill(0)\n for (let i = 1; i < n; i++) {\n let j = lps[i - 1]\n while (j > 0 && group[i] !== group[j]) {\n j = lps[j - 1]\n }\n if (group[i] === group[j]) {\n j++\n }\n lps[i] = j\n }\n\n // Step-2 - Matching\n let j = 0\n while (index < m) {\n if (nums[index] === group[j]) {\n j++\n index++\n }\n if (j === n) break\n else if (index < m && nums[index] != group[j]) {\n if (j > 0) {\n j = lps[j - 1]\n } else {\n index++\n }\n }\n }\n if (j !== n) return false\n }\n return true\n}\n\n\n// another\n\n\n/**\n * @param {number[][]} groups\n * @param {number[]} nums\n * @return {boolean}\n */\nconst canChoose = function(groups, nums) {\n let gi = 0, ni = 0\n const n = groups.length, m = nums.length\n while(gi < n && ni < m) {\n const len = groups[gi].length\n let pass = true\n if(nums[ni] !== groups[gi][0]) {\n ni++\n continue\n }\n for(let i = 1; i < len; i++) {\n if(nums[ni + i] !== groups[gi][i]) {\n pass = false\n break\n }\n }\n if(pass) {\n gi++\n ni += len\n } else {\n ni++\n }\n }\n if(gi >= n) return true\n\n return false\n\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720e48", + "questionid": 893, + "title": "Maximum Score From Removing Stones", + "slug": "maximum-score-from-removing-stones", + "description": "You are playing a solitaire game with three piles of stones of sizes a, b, and c respectively. Each turn you choose two different non-empty piles, take one stone from each, and add 1 point to your score. The game stops when there are fewer than two non-empty piles (meaning there are no more available moves). Given three integers a, b, and c, return the maximum score you can get. ", + "category": [ + "Math", + "Greedy", + "Heap (Priority Queue)" + ], + "complexity": "Medium", + "successrate": 65.2, + "totalsubmissions": 32426, + "totalaccepted": 21143, + "likes": 485, + "dislikes": 34, + "hints": "It's optimal to always remove one stone from the biggest 2 piles Note that the limits are small enough for simulation", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "a = 2, b = 4, c = 6", + "expected_output": "6", + "explanation": "The starting state is (2, 4, 6). One optimal set of moves is:\n- Take from 1st and 3rd piles, state is now (1, 4, 5)\n- Take from 1st and 3rd piles, state is now (0, 4, 4)\n- Take from 2nd and 3rd piles, state is now (0, 3, 3)\n- Take from 2nd and 3rd piles, state is now (0, 2, 2)\n- Take from 2nd and 3rd piles, state is now (0, 1, 1)\n- Take from 2nd and 3rd piles, state is now (0, 0, 0)\nThere are fewer than two non-empty piles, so the game ends. Total: 6 points." + }, + { + "example_num": 2, + "expected_input": "a = 4, b = 4, c = 6", + "expected_output": "7", + "explanation": "The starting state is (4, 4, 6). One optimal set of moves is:\n- Take from 1st and 2nd piles, state is now (3, 3, 6)\n- Take from 1st and 3rd piles, state is now (2, 3, 5)\n- Take from 1st and 3rd piles, state is now (1, 3, 4)\n- Take from 1st and 3rd piles, state is now (0, 3, 3)\n- Take from 2nd and 3rd piles, state is now (0, 2, 2)\n- Take from 2nd and 3rd piles, state is now (0, 1, 1)\n- Take from 2nd and 3rd piles, state is now (0, 0, 0)\nThere are fewer than two non-empty piles, so the game ends. Total: 7 points." + }, + { + "example_num": 3, + "expected_input": "a = 1, b = 8, c = 8", + "expected_output": "8", + "explanation": "One optimal set of moves is to take from the 2nd and 3rd piles for 8 turns until they are empty.\nAfter that, there are fewer than two non-empty piles, so the game ends." + } + ], + "solution": "/**\n * @param {number} a\n * @param {number} b\n * @param {number} c\n * @return {number}\n */\nconst maximumScore = function(a, b, c) {\n const arr = [a, b, c]\n arr.sort((a, b) => a - b)\n \n\n if (arr[0] + arr[1] <= arr[2]) {\n return arr[0] + arr[1];\n } else {\n const min = Math.min(arr[0], Math.floor((arr[1] + arr[0] - arr[2]) / 2));\n return arr[2] + min;\n }\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720e11", + "questionid": 838, + "title": "Widest Vertical Area Between Two Points Containing No Points", + "slug": "widest-vertical-area-between-two-points-containing-no-points", + "description": "Given n points on a 2D plane where points[i] = [xi, yi], Return\u00a0the widest vertical area between two points such that no points are inside the area. A vertical area is an area of fixed-width extending infinitely along the y-axis (i.e., infinite height). The widest vertical area is the one with the maximum width. Note that points on the edge of a vertical area are not considered included in the area. ", + "category": [ + "Array", + "Sorting" + ], + "complexity": "Medium", + "successrate": 84, + "totalsubmissions": 33632, + "totalaccepted": 28243, + "likes": 170, + "dislikes": 494, + "hints": "Try sorting the points Think is the y-axis of a point relevant", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "points = [[8,7],[9,9],[7,4],[9,7]]", + "expected_output": "1", + "explanation": "Both the red and the blue area are optimal." + }, + { + "example_num": 2, + "expected_input": "points = [[3,1],[9,0],[1,0],[1,4],[5,3],[8,8]]", + "expected_output": "3", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[][]} points\n * @return {number}\n */\nconst maxWidthOfVerticalArea = function(points) {\n const arr = points.map(e => e[0])\n arr.sort((a, b) => a - b)\n let res = -Infinity\n for(let i = 1, len = arr.length; i < len; i++) {\n if(arr[i] - arr[i - 1] > res) res = arr[i] - arr[i - 1]\n }\n return res\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720e18", + "questionid": 845, + "title": "Minimum Deletions to Make String Balanced", + "slug": "minimum-deletions-to-make-string-balanced", + "description": "You are given a string s consisting only of characters 'a' and 'b'. You can delete any number of characters in s to make s balanced. s is balanced if there is no pair of indices (i,j) such that i < j and s[i] = 'b' and s[j]= 'a'. Return the minimum number of deletions needed to make s balanced. ", + "category": [ + "String", + "Dynamic Programming", + "Stack" + ], + "complexity": "Medium", + "successrate": 56, + "totalsubmissions": 33672, + "totalaccepted": 18869, + "likes": 682, + "dislikes": 19, + "hints": "You need to find for every index the number of Bs before it and the number of A's after it You can speed up the finding of A's and B's in suffix and prefix using preprocessing", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "aababbab"", + "expected_output": "2", + "explanation": "You can either:\nDelete the characters at 0-indexed positions 2 and 6 ("aababbab" -> "aaabbb"), or\nDelete the characters at 0-indexed positions 3 and 6 ("aababbab" -> "aabbbb")." + }, + { + "example_num": 2, + "expected_input": "s = "bbaaaaabb"", + "expected_output": "2", + "explanation": "The only solution is to delete the first two characters." + } + ], + "solution": "/**\n * @param {string} s\n * @return {number}\n */\nconst minimumDeletions = function(s) {\n let res = 0, b = 0\n for(const e of s) {\n if(e === 'b') b++\n else if(b > 0) {\n res++\n b--\n }\n }\n \n return res\n};\n\n// another\n\n\n/**\n * @param {string} s\n * @return {number}\n */\nconst minimumDeletions = function(s) {\n let res = 0\n let cnt = 0\n for(let c of s) {\n if(c === 'a' && cnt > 0) {\n res++\n cnt--\n } else if(c === 'b') {\n cnt++\n }\n }\n \n return res\n};\n\n// another\n\n/**\n * @param {string} s\n * @return {number}\n */\nconst minimumDeletions = function(s) {\n const len = s.length\n const dp = Array(len + 1).fill(0)\n let bcount = 0\n for(let i = 1; i <= len; i++) {\n if(s[i - 1] === 'a') {\n dp[i] = Math.min(dp[i - 1] + 1, bcount)\n } else {\n dp[i] = dp[i - 1]\n bcount++\n }\n }\n \n return dp[len]\n};\n\n// another\n\n/**\n * @param {string} s\n * @return {number}\n */\nconst minimumDeletions = function(s) {\n const len = s.length\n const stack = []\n let res = 0\n for(let i = 0; i < len; i++) {\n if(stack.length && stack[stack.length - 1] > s[i]) {\n res++\n stack.pop()\n } else {\n stack.push(s[i])\n }\n }\n return res\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720e19", + "questionid": 846, + "title": "Check Array Formation Through Concatenation", + "slug": "check-array-formation-through-concatenation", + "description": "You are given an array of distinct integers arr and an array of integer arrays pieces, where the integers in pieces are distinct. Your goal is to form arr by concatenating the arrays in pieces in any order. However, you are not allowed to reorder the integers in each array pieces[i]. Return true if it is possible to form the array arr from pieces. Otherwise, return false. ", + "category": [ + "Array", + "Hash Table" + ], + "complexity": "Easy", + "successrate": 55.8, + "totalsubmissions": 119597, + "totalaccepted": 66766, + "likes": 671, + "dislikes": 112, + "hints": "Note that the distinct part means that every position in the array belongs to only one piece Note that you can get the piece every position belongs to naively", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "arr = [15,88], pieces = [[88],[15]]", + "expected_output": "true", + "explanation": "Concatenate [15] then [88]" + }, + { + "example_num": 2, + "expected_input": "arr = [49,18,16], pieces = [[16,18,49]]", + "expected_output": "false", + "explanation": "Even though the numbers match, we cannot reorder pieces[0]." + }, + { + "example_num": 3, + "expected_input": "arr = [91,4,64,78], pieces = [[78],[4,64],[91]]", + "expected_output": "true", + "explanation": "Concatenate [91] then [4,64] then [78]" + } + ], + "solution": "/**\n * @param {number[]} arr\n * @param {number[][]} pieces\n * @return {boolean}\n */\nconst canFormArray = function(arr, pieces) {\n const m = new Map()\n for(let i = 0, len = arr.length; i < len; i++) {\n m.set(arr[i], i)\n }\n for(let p of pieces) {\n let idx = m.get(p[0])\n if(idx == null) return false\n for(let i = 1, len = p.length; i < len; i++) {\n console.log(m.has(p[i]))\n if(!m.has(p[i]) || arr[++idx] !== p[i]) return false\n }\n }\n return true\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720e1d", + "questionid": 850, + "title": "Minimum Deletions to Make Character Frequencies Unique", + "slug": "minimum-deletions-to-make-character-frequencies-unique", + "description": "A string s is called good if there are no two different characters in s that have the same frequency. Given a string s, return the minimum number of characters you need to delete to make s good. The frequency of a character in a string is the number of times it appears in the string. For example, in the string \"aab\", the frequency of 'a' is 2, while the frequency of 'b' is 1. ", + "category": [ + "String", + "Greedy", + "Sorting" + ], + "complexity": "Medium", + "successrate": 56.4, + "totalsubmissions": 143838, + "totalaccepted": 81115, + "likes": 1266, + "dislikes": 27, + "hints": "As we can only delete characters, if we have multiple characters having the same frequency, we must decrease all the frequencies of them, except one. Sort the alphabet characters by their frequencies non-increasingly. Iterate on the alphabet characters, keep decreasing the frequency of the current character until it reaches a value that has not appeared before.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "aab"", + "expected_output": "0", + "explanation": "s is already good." + }, + { + "example_num": 2, + "expected_input": "s = "aaabbbcc"", + "expected_output": "2", + "explanation": "You can delete two 'b's resulting in the good string "aaabcc".\nAnother way it to delete one 'b' and one 'c' resulting in the good string "aaabbc"." + }, + { + "example_num": 3, + "expected_input": "s = "ceabaacb"", + "expected_output": "2", + "explanation": "You can delete both 'c's resulting in the good string "eabaab".\nNote that we only care about characters that are still in the string at the end (i.e. frequency of 0 is ignored)." + } + ], + "solution": "/**\n * @param {string} s\n * @return {number}\n */\nconst minDeletions = function(s) {\n if (s == null || s.length <= 1) {\n return 0;\n }\n\n const map = new Map();\n for (let ch of s) {\n map.set(ch, (map.get(ch) || 0) + 1);\n }\n\n\n const frequencies = new Set();\n let minDeletions = 0;\n \n const vals = map.values()\n for (let frequency of vals) {\n if (!frequencies.has(frequency)) {\n frequencies.add(frequency);\n continue;\n }\n\n let curr = frequency;\n while (curr > 0 && frequencies.has(curr)) {\n curr--;\n minDeletions++;\n }\n\n if (curr > 0) {\n frequencies.add(curr);\n }\n }\n\n return minDeletions;\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720e21", + "questionid": 854, + "title": "Smallest String With A Given Numeric Value", + "slug": "smallest-string-with-a-given-numeric-value", + "description": "The numeric value of a lowercase character is defined as its position (1-indexed) in the alphabet, so the numeric value of a is 1, the numeric value of b is 2, the numeric value of c is 3, and so on. The numeric value of a string consisting of lowercase characters is defined as the sum of its characters' numeric values. For example, the numeric value of the string \"abe\" is equal to 1 + 2 + 5 = 8. You are given two integers n and k. Return the lexicographically smallest string with length equal to n and numeric value equal to k. Note that a string x is lexicographically smaller than string y if x comes before y in dictionary order, that is, either x is a prefix of y, or if i is the first position such that x[i] != y[i], then x[i] comes before y[i] in alphabetic order. ", + "category": [ + "String", + "Greedy" + ], + "complexity": "Medium", + "successrate": 67, + "totalsubmissions": 118160, + "totalaccepted": 79194, + "likes": 1523, + "dislikes": 50, + "hints": "Think greedily. If you build the string from the end to the beginning, it will always be optimal to put the highest possible character at the current index.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 3, k = 27", + "expected_output": ""aay"", + "explanation": "The numeric value of the string is 1 + 1 + 25 = 27, and it is the smallest string with such a value and length equal to 3." + }, + { + "example_num": 2, + "expected_input": "n = 5, k = 73", + "expected_output": ""aaszz"", + "explanation": "" + } + ], + "solution": "/**\n * @param {number} n\n * @param {number} k\n * @return {string}\n */\nconst getSmallestString = function(n, k) {\n let arr = Array(n).fill(1)\n k -= n \n for(let i = n - 1; i >= 0; i--) {\n if(k > 0) {\n const delta = 26 - arr[i]\n if(k >= delta) {\n k -= delta\n arr[i] = arr[i] + delta\n } else {\n arr[i] = arr[i] + k\n k = 0\n }\n } else break\n }\n const str = 'abcdefghijklmnopqrstuvwxyz'\n const m = {}\n for(let i = 0; i < 26; i++) {\n m[i + 1] = str[i]\n }\n const res = []\n for(let i = 0; i < n; i++) {\n res[i] = m[arr[i]]\n }\n return res.join('')\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720e22", + "questionid": 855, + "title": "Count the Number of Consistent Strings", + "slug": "count-the-number-of-consistent-strings", + "description": "You are given a string allowed consisting of distinct characters and an array of strings words. A string is consistent if all characters in the string appear in the string allowed. Return the number of consistent strings in the array words. ", + "category": [ + "Array", + "Hash Table", + "String", + "Bit Manipulation" + ], + "complexity": "Easy", + "successrate": 81.9, + "totalsubmissions": 102721, + "totalaccepted": 84109, + "likes": 818, + "dislikes": 39, + "hints": "A string is incorrect if it contains a character that is not allowed Constraints are small enough for brute force", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "allowed = "ab", words = ["ad","bd","aaab","baa","badab"]", + "expected_output": "2", + "explanation": "Strings "aaab" and "baa" are consistent since they only contain characters 'a' and 'b'." + }, + { + "example_num": 2, + "expected_input": "allowed = "abc", words = ["a","b","c","ab","ac","bc","abc"]", + "expected_output": "7", + "explanation": "All strings are consistent." + }, + { + "example_num": 3, + "expected_input": "allowed = "cad", words = ["cc","acd","b","ba","bac","bad","ac","d"]", + "expected_output": "4", + "explanation": "Strings "cc", "acd", "ac", and "d" are consistent." + } + ], + "solution": "/**\n * @param {string} allowed\n * @param {string[]} words\n * @return {number}\n */\nvar countConsistentStrings = function(allowed, words) {\n const set = new Set()\n for(let c of allowed) set.add(c)\n let res = 0\n for(let i = 0, len = words.length; i < len; i++) {\n const cur = words[i]\n let b = true\n for(let c of cur) {\n if(!set.has(c)) {\n b = false\n break\n }\n }\n if(b) res++\n }\n \n return res\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720e26", + "questionid": 859, + "title": "Minimum Moves to Make Array Complementary", + "slug": "minimum-moves-to-make-array-complementary", + "description": "You are given an integer array nums of even length n and an integer limit. In one move, you can replace any integer from nums with another integer between 1 and limit, inclusive. The array nums is complementary if for all indices i (0-indexed), nums[i] + nums[n - 1 - i] equals the same number. For example, the array [1,2,3,4] is complementary because for all indices i, nums[i] + nums[n - 1 - i] = 5. Return the minimum number of moves required to make nums complementary. ", + "category": [ + "Array", + "Hash Table", + "Prefix Sum" + ], + "complexity": "Medium", + "successrate": 37.3, + "totalsubmissions": 15487, + "totalaccepted": 5772, + "likes": 437, + "dislikes": 54, + "hints": "Given a target sum x, each pair of nums[i] and nums[n-1-i] would either need 0, 1, or 2 modifications. Can you find the optimal target sum x value such that the sum of modifications is minimized? Create a difference array to efficiently sum all the modifications.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,2,4,3], limit = 4", + "expected_output": "1", + "explanation": "In 1 move, you can change nums to [1,2,2,3] (underlined elements are changed).\nnums[0] + nums[3] = 1 + 3 = 4.\nnums[1] + nums[2] = 2 + 2 = 4.\nnums[2] + nums[1] = 2 + 2 = 4.\nnums[3] + nums[0] = 3 + 1 = 4.\nTherefore, nums[i] + nums[n-1-i] = 4 for every i, so nums is complementary." + }, + { + "example_num": 2, + "expected_input": "nums = [1,2,2,1], limit = 2", + "expected_output": "2", + "explanation": "In 2 moves, you can change nums to [2,2,2,2]. You cannot change any number to 3 since 3 > limit." + }, + { + "example_num": 3, + "expected_input": "nums = [1,2,1,2], limit = 2", + "expected_output": "0", + "explanation": "nums is already complementary." + } + ], + "solution": "/**\n * @param {number[]} nums\n * @param {number} limit\n * @return {number}\n */\nconst minMoves = function (nums, limit) {\n const { min, max } = Math\n const n = nums.length\n const delta = Array(limit * 2 + 2).fill(0)\n for (let i = 0; i < n / 2; i++) {\n const lo = 1 + min(nums[i], nums[n - i - 1])\n const hi = limit + max(nums[i], nums[n - i - 1])\n const sum = nums[i] + nums[n - i - 1]\n delta[lo]--\n delta[sum]--\n delta[sum + 1]++\n delta[hi + 1]++\n }\n let now = n\n let ans = n\n for (let i = 2; i <= limit * 2; i++) {\n now += delta[i]\n ans = min(ans, now)\n }\n return ans\n}\n\n// another\n\n/**\n * @param {number[]} nums\n * @param {number} limit\n * @return {number}\n */\nconst minMoves = function (nums, limit) {\n const n = nums.length, { max, min } = Math\n const delta = Array(2 * limit + 2).fill(0)\n for(let i = 0; i < n / 2; i++) {\n const a = nums[i], b = nums[n - 1 - i]\n // [2, min(a, b) + 1)\n delta[2] += 2\n // [min(a, b) + 1, a + b)\n delta[min(a, b) + 1] -= 1\n delta[a + b]--\n // [a + b + 1, max(a, b) + limit]\n delta[a + b + 1] += 1\n // (max(a, b) + limit, 2 * limit]\n delta[max(a, b) + limit + 1] +=1\n }\n \n let res = n, cur = 0\n for(let i = 2; i <= limit * 2; i++) {\n cur += delta[i]\n res = min(cur, res)\n }\n \n return res\n}\n\n// another\n\n/**\n * @param {number[]} nums\n * @param {number} limit\n * @return {number}\n */\nconst minMoves = function (nums, limit) {\n const n = nums.length, { min, max } = Math\n const arr = Array(2 * limit + 2).fill(0)\n for(let i = 0, r = n / 2; i < r; i++) {\n const a = nums[i], b = nums[n - 1 - i]\n arr[2] += 2\n arr[min(a, b) + 1]--\n arr[a + b]--\n arr[a + b + 1]++\n arr[max(a, b) + limit + 1]++\n }\n let res = Infinity, cur = 0\n for(let i = 2, r = 2 * limit; i <= r; i++) {\n cur += arr[i]\n res = min(res, cur)\n }\n \n return res\n}\n\n// another\n\n/**\n * @param {number[]} nums\n * @param {number} limit\n * @return {number}\n */\nconst minMoves = function (nums, limit) {\n const n = nums.length, { min, max } = Math\n const arr = Array(2 * limit + 2).fill(0)\n for(let i = 0, r = n / 2; i < r; i++) {\n const a = nums[i], b = nums[n - 1 - i]\n // [2, 2 * limit]\n arr[2] += 2\n arr[2 * limit + 1] -= 2\n // [min(a, b) + 1, max(a, b) + limit]\n arr[min(a, b) + 1]--\n arr[max(a, b) + limit + 1]++\n // a + b\n arr[a + b]--\n arr[a + b + 1]++\n\n }\n let res = Infinity, cur = 0\n for(let i = 2, r = 2 * limit; i <= r; i++) {\n cur += arr[i]\n res = min(res, cur)\n }\n \n return res\n}\n\n// another\n\n/**\n * @param {number[]} nums\n * @param {number} limit\n * @return {number}\n */\nconst minMoves = function(nums, limit) {\n const n = nums.length\n const arr = Array(2 * limit + 2).fill(0)\n for(let i = 0; i < n / 2; i++) {\n const a = nums[i], b = nums[n - 1 - i]\n const l = Math.min(a, b), r = Math.max(a, b)\n arr[l + 1]--\n arr[l + r]--\n arr[l + r + 1]++\n arr[r + limit + 1]++\n }\n let res = n, cur = n\n for(let e of arr) {\n cur += e\n res = Math.min(res, cur)\n }\n \n return res\n};\n\n\n" + }, + { + "_id": "66f925ddfdfb8e1665720e2e", + "questionid": 867, + "title": "Maximum Erasure Value", + "slug": "maximum-erasure-value", + "description": "You are given an array of positive integers nums and want to erase a subarray containing\u00a0unique elements. The score you get by erasing the subarray is equal to the sum of its elements. Return the maximum score you can get by erasing exactly one subarray. An array b is called to be a subarray of a if it forms a contiguous subsequence of a, that is, if it is equal to a[l],a[l+1],...,a[r] for some (l,r). ", + "category": [ + "Array", + "Hash Table", + "Sliding Window" + ], + "complexity": "Medium", + "successrate": 52.4, + "totalsubmissions": 78337, + "totalaccepted": 41076, + "likes": 823, + "dislikes": 14, + "hints": "The main point here is for the subarray to contain unique elements for each index. Only the first subarrays starting from that index have unique elements. This can be solved using the two pointers technique", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [4,2,4,5,6]", + "expected_output": "17", + "explanation": "The optimal subarray here is [2,4,5,6]." + }, + { + "example_num": 2, + "expected_input": "nums = [5,2,1,2,5,2,1,2,5]", + "expected_output": "8", + "explanation": "The optimal subarray here is [5,2,1] or [1,2,5]." + } + ], + "solution": "/**\n * @param {number[]} nums\n * @return {number}\n */\nconst maximumUniqueSubarray = function(nums) {\n return maxSumSubarray(nums, nums.length)\n};\n\nfunction maxSumSubarray(arr, n) {\n\n let i = 0, j = 1;\n const set = new Set();\n set.add(arr[0]);\n\n let sum = arr[0];\n let maxsum = sum;\n let end = arr[0]\n \n while (i < n - 1 && j < n) {\n const is_in = set.has(arr[j])\n if (!is_in) {\n sum = sum + arr[j];\n maxsum = Math.max(sum, maxsum);\n \n set.add(arr[j++]);\n } else {\n sum -= arr[i];\n set.delete(arr[i++]);\n }\n }\n return maxsum;\n}\n\nfunction end(s) {\n return Array.from(s).pop();\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720e2f", + "questionid": 868, + "title": "Jump Game VI", + "slug": "jump-game-vi", + "description": "You are given a 0-indexed integer array nums and an integer k. You are initially standing at index 0. In one move, you can jump at most k steps forward without going outside the boundaries of the array. That is, you can jump from index i to any index in the range [i + 1, min(n - 1, i + k)] inclusive. You want to reach the last index of the array (index n - 1). Your score is the sum of all nums[j] for each index j you visited in the array. Return the maximum score you can get. ", + "category": [ + "Array", + "Dynamic Programming", + "Queue", + "Sliding Window", + "Heap (Priority Queue)", + "Monotonic Queue" + ], + "complexity": "Medium", + "successrate": 42.7, + "totalsubmissions": 99365, + "totalaccepted": 42467, + "likes": 1287, + "dislikes": 51, + "hints": "Let dp[i] be \"the maximum score to reach the end starting at index i\". The answer for dp[i] is nums[i] + max{dp[i+j]} for 1 <= j <= k. That gives an O(n*k) solution. Instead of checking every j for every i, keep track of the largest dp[i] values in a heap and calculate dp[i] from right to left. When the largest value in the heap is out of bounds of the current index, remove it and keep checking.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,-1,-2,4,-7,3], k = 2", + "expected_output": "7", + "explanation": "You can choose your jumps forming the subsequence [1,-1,4,3] (underlined above). The sum is 7." + }, + { + "example_num": 2, + "expected_input": "nums = [10,-5,-2,4,0,3], k = 3", + "expected_output": "17", + "explanation": "You can choose your jumps forming the subsequence [10,4,3] (underlined above). The sum is 17." + }, + { + "example_num": 3, + "expected_input": "nums = [1,-5,-20,4,-1,3,-6,-3], k = 2", + "expected_output": "0", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} nums\n * @param {number} k\n * @return {number}\n */\nconst maxResult = function (nums, k) {\n const n = nums.length\n const f = Array(n).fill(0)\n f[0] = nums[0]\n const q = [0]\n for (let i = 1; i < n; ++i) {\n while (i - q[0] > k) {\n q.shift()\n }\n f[i] = f[q[0]] + nums[i]\n while (q.length && f[i] >= f[q[q.length - 1]]) {\n q.pop()\n }\n q.push(i)\n }\n return f[n - 1]\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720e31", + "questionid": 870, + "title": "Calculate Money in Leetcode Bank", + "slug": "calculate-money-in-leetcode-bank", + "description": "Hercy wants to save money for his first car. He puts money in the Leetcode\u00a0bank every day. He starts by putting in $1 on Monday, the first day. Every day from Tuesday to Sunday, he will put in $1 more than the day before. On every subsequent Monday, he will put in $1 more than the previous Monday. Given n, return the total amount of money he will have in the Leetcode bank at the end of the nth day. ", + "category": [ + "Math" + ], + "complexity": "Easy", + "successrate": 64.9, + "totalsubmissions": 44970, + "totalaccepted": 29166, + "likes": 433, + "dislikes": 14, + "hints": "Simulate the process by keeping track of how much money John is putting in and which day of the week it is, and use this information to deduce how much money John will put in the next day.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 4", + "expected_output": "10", + "explanation": " After the 4th day, the total is 1 + 2 + 3 + 4 = 10." + }, + { + "example_num": 2, + "expected_input": "n = 10", + "expected_output": "37", + "explanation": " After the 10th day, the total is (1 + 2 + 3 + 4 + 5 + 6 + 7) + (2 + 3 + 4) = 37. Notice that on the 2nd Monday, Hercy only puts in $2." + }, + { + "example_num": 3, + "expected_input": "n = 20", + "expected_output": "96", + "explanation": " After the 20th day, the total is (1 + 2 + 3 + 4 + 5 + 6 + 7) + (2 + 3 + 4 + 5 + 6 + 7 + 8) + (3 + 4 + 5 + 6 + 7 + 8) = 96." + } + ], + "solution": "/**\n * @param {number} n\n * @return {number}\n */\nconst totalMoney = function(n) {\n let total = 0\n for(let i = 0 ; i < n; i++) {\n const base = (i / 7) >> 0\n const remain = i % 7 + 1\n total += base + remain\n }\n\n return total\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720e36", + "questionid": 875, + "title": "Maximum XOR With an Element From Array", + "slug": "maximum-xor-with-an-element-from-array", + "description": "You are given an array nums consisting of non-negative integers. You are also given a queries array, where queries[i] = [xi, mi]. The answer to the ith query is the maximum bitwise XOR value of xi and any element of nums that does not exceed mi. In other words, the answer is max(nums[j] XOR xi) for all j such that nums[j] <= mi. If all elements in nums are larger than mi, then the answer is -1. Return an integer array answer where answer.length == queries.length and answer[i] is the answer to the ith query. ", + "category": [ + "Array", + "Bit Manipulation", + "Trie" + ], + "complexity": "Hard", + "successrate": 43.2, + "totalsubmissions": 19885, + "totalaccepted": 8589, + "likes": 489, + "dislikes": 15, + "hints": "In problems involving bitwise operations, we often think on the bits level. In this problem, we can think that to maximize the result of an xor operation, we need to maximize the most significant bit, then the next one, and so on. If there's some number in the array that is less than m and whose the most significant bit is different than that of x, then xoring with this number maximizes the most significant bit, so I know this bit in the answer is 1. To check the existence of such numbers and narrow your scope for further bits based on your choice, you can use trie. You can sort the array and the queries, and maintain the trie such that in each query the trie consists exactly of the valid elements.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [0,1,2,3,4], queries = [[3,1],[1,3],[5,6]]", + "expected_output": "[3,3,7]", + "explanation": "1) 0 and 1 are the only two integers not greater than 1. 0 XOR 3 = 3 and 1 XOR 3 = 2. The larger of the two is 3.\n2) 1 XOR 2 = 3.\n3) 5 XOR 2 = 7." + }, + { + "example_num": 2, + "expected_input": "nums = [5,2,4,6,6,3], queries = [[12,4],[8,1],[6,3]]", + "expected_output": "[15,-1,5]", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} nums\n * @param {number[][]} queries\n * @return {number[]}\n */\nvar maximizeXor = function(nums, queries) {\n nums.sort((a, b) => a - b)\n const n = nums.length\n queries.forEach((query, index) => {\n query.push(index)\n })\n queries.sort((a, b) => a[1] - b[1])\n const trie = new Trie()\n let i = 0\n const res = []\n queries.forEach(([x, m, index]) => {\n while (i < n && nums[i] <= m) {\n trie.insert(nums[i])\n i++\n }\n\n res[index] = trie.query(x)\n \n })\n return res\n};\n\nclass Trie {\n constructor() {\n this.root = {}\n }\n insert(num) {\n let node = this.root\n for (let i = 31; i >= 0; i--) {\n const bit = (num >> i) & 1\n if (!node[bit]) {\n node[bit] = {}\n }\n node = node[bit]\n }\n }\n query(num) {\n let node = this.root\n if (Object.keys(node).length === 0) return -1\n let res = 0\n for (let i = 31; i >= 0; i--) {\n const bit = (num >> i) & 1\n if(node == null) break\n if (node[1 - bit]) {\n res |= 1 << i\n node = node[1 - bit]\n } else {\n node = node[bit]\n }\n }\n return res\n }\n}\n\n// another\n\n\n/**\n * @param {number[]} nums\n * @param {number[][]} queries\n * @return {number[]}\n */\nconst maximizeXor = function(nums, queries) {\n nums.sort((a, b) => a - b)\n queries.forEach((e, i) => e.push(i))\n queries.sort((a, b) => a[1] - b[1])\n const n = nums.length\n let idx = 0\n const res = []\n const root = [null, null]\n for(const [x, m, qi] of queries) {\n while(idx < n && nums[idx] <= m) {\n let cur = root, val = nums[idx]\n for(let i = 29; i >= 0; i--) {\n const tmp = (val >> i) & 1\n if(cur[tmp] == null) cur[tmp] = [null, null]\n cur = cur[tmp]\n }\n idx++\n }\n if(idx === 0) {\n res[qi] = -1\n continue\n }\n \n let tmp = 0, cur = root\n for(let i = 29; i >= 0; i--) {\n const val = 1 - ((x >> i) & 1)\n if(cur[val] != null) {\n tmp = tmp * 2 + 1\n cur = cur[val]\n } else {\n tmp = tmp * 2\n cur = cur[1 - val]\n }\n }\n res[qi] = tmp\n }\n\n return res\n};\n\n// another\n\n/**\n * @param {number[]} nums\n * @param {number[][]} queries\n * @return {number[]}\n */\nconst maximizeXor = function (nums, queries) {\n nums.sort((a, b) => a - b)\n const numOfBits = 1 + Math.floor(Math.log2(nums[nums.length - 1]))\n const maxMask = (1 << numOfBits) - 1\n return queries.map(([x, m]) => query(x, m))\n function query(x, m) {\n if (m < nums[0]) return -1\n let l = 0,\n r = nums.length\n while (l < r) {\n let mid = l + ((r - l) >> 1)\n if (m < nums[mid])r = mid\n else l = mid + 1\n }\n r--\n l = 0\n let ans = x & ~maxMask\n for (let bit = numOfBits - 1; bit >= 0; bit--) {\n const mask = 1 << bit\n if (x & mask) {\n if ((nums[l] & mask) === 0) {\n ans |= 1 << bit\n r = search(l, r, mask) - 1\n }\n } else {\n if (nums[r] & mask) {\n ans |= 1 << bit\n l = search(l, r, mask)\n }\n }\n }\n return ans\n }\n function search(l, r, mask) {\n while (l <= r) {\n const m = l + ((r - l) >> 1)\n if ((nums[m] & mask) === 0) l = m + 1 \n else r = m - 1\n }\n return l\n }\n}\n\n\n// another\n\n/**\n * @param {number[]} nums\n * @param {number[][]} queries\n * @return {number[]}\n */\nconst maximizeXor = function (nums, queries) {\n const n = queries.length\n const result = new Array(n)\n const trie = [null, null]\n for (let num of nums) {\n let node = trie\n for (let i = 30; i >= 0; i--) {\n const b = 1 << i\n if (b & num) {\n if (!node[1]) node[1] = [null, null]\n node = node[1]\n } else {\n if (!node[0]) node[0] = [null, null]\n node = node[0]\n }\n }\n }\n const min = Math.min(...nums)\n const dfs = (node, num, i, val, max) => {\n if (!node || val > max) return -1\n if (i === -1) return val\n const bit = 1 << i\n i--\n if (bit > max) return dfs(node[0], num, i, val, max)\n if (num & bit) {\n let x = dfs(node[0], num, i, val, max)\n if (x > -1) return x\n return dfs(node[1], num, i, val | bit, max)\n } else {\n let y = dfs(node[1], num, i, val | bit, max)\n if (y > -1) return y\n return dfs(node[0], num, i, val, max)\n }\n }\n\n for (let i = 0; i < n; i++) {\n const [num, max] = queries[i]\n if (max < min) {\n result[i] = -1\n continue\n }\n result[i] = dfs(trie, num, 30, 0, max) ^ num\n }\n return result\n}\n\n// another\n// though not enough memory, this method still provides a method to solve this kind of problem\n\nclass Trie {\n constructor() {\n this.next = Array(2).fill(null)\n }\n}\n/**\n * @param {number[]} nums\n * @param {number[][]} queries\n * @return {number[]}\n */\nconst maximizeXor = function(nums, queries) {\n nums.sort((a, b) => a - b)\n queries.forEach((e, i) => e.push(i))\n queries.sort((a, b) => a[1] - b[1])\n const n = nums.length\n let idx = 0\n const res = []\n const root = new Trie()\n for(const [x, m, qi] of queries) {\n \n while(idx < n && nums[idx] <= m) {\n let cur = root, val = nums[idx]\n for(let i = 29; i >= 0; i--) {\n const tmp = (val >> i) & 1\n if(cur.next[tmp] == null) cur.next[tmp] = new Trie()\n cur = cur.next[tmp]\n }\n idx++\n }\n if(idx === 0) {\n res[qi] = -1\n continue\n }\n \n let tmp = 0, cur = root\n for(let i = 29; i >= 0; i--) {\n const val = 1 - ((x >> i) & 1)\n if(cur.next[val] != null) {\n tmp = tmp * 2 + 1\n cur = cur.next[val]\n } else {\n tmp = tmp * 2\n cur = cur.next[1 - val]\n }\n\n }\n \n res[qi] = tmp\n }\n return res\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720e37", + "questionid": 876, + "title": "Count Good Meals", + "slug": "count-good-meals", + "description": "A good meal is a meal that contains exactly two different food items with a sum of deliciousness equal to a power of two. You can pick any two different foods to make a good meal. Given an array of integers deliciousness where deliciousness[i] is the deliciousness of the ith item of food, return the number of different good meals you can make from this list modulo 109 + 7. Note that items with different indices are considered different even if they have the same deliciousness value. ", + "category": [ + "Array", + "Hash Table" + ], + "complexity": "Medium", + "successrate": 28.2, + "totalsubmissions": 82974, + "totalaccepted": 23396, + "likes": 519, + "dislikes": 188, + "hints": "Note that the number of powers of 2 is at most 21 so this turns the problem to a classic find the number of pairs that sum to a certain value but for 21 values You need to use something fasters than the NlogN approach since there is already the log of iterating over the powers so one idea is two pointers", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "deliciousness = [1,3,5,7,9]", + "expected_output": "4\nExplanation: The good meals are (1,3), (1,7), (3,5) and, (7,9).\nTheir respective sums are 4, 8, 8, and 16, all of which are powers of 2.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "deliciousness = [1,1,1,3,3,3,7]", + "expected_output": "15\nExplanation: The good meals are (1,1) with 3 ways, (1,3) with 9 ways, and (1,7) with 3 ways.", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} deliciousness\n * @return {number}\n */\nconst countPairs = function (deliciousness) {\n const N = deliciousness.length\n deliciousness.sort((a, b) => a - b)\n const mp = {},\n mod = 10 ** 9 + 7\n let ret = 0\n for (let i = 0; i < N; i++) {\n if (deliciousness[i] !== 0) {\n let sum = 1 << (32 - __builtin_clz(deliciousness[i]) - 1)\n ret += mp[sum - deliciousness[i]] || 0\n ret += mp[(sum << 1) - deliciousness[i]] || 0\n if (ret >= mod) ret -= mod\n }\n if (mp[deliciousness[i]] == null) mp[deliciousness[i]] = 0\n mp[deliciousness[i]]++\n }\n return ret\n}\n\nfunction __builtin_clz(num) {\n if (num === 0) return 32\n return 32 - dec2bin(num).length\n}\n\nfunction dec2bin(num) {\n return (num >>> 0).toString(2)\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720e38", + "questionid": 877, + "title": "Minimum Operations to Make a Subsequence", + "slug": "minimum-operations-to-make-a-subsequence", + "description": "You are given an array target that consists of distinct integers and another integer array arr that can have duplicates. In one operation, you can insert any integer at any position in arr. For example, if arr = [1,4,1,2], you can add 3 in the middle and make it [1,4,3,1,2]. Note that you can insert the integer at the very beginning or end of the array. Return the minimum number of operations needed to make target a subsequence of arr. A subsequence of an array is a new array generated from the original array by deleting some elements (possibly none) without changing the remaining elements' relative order. For example, [2,7,4] is a subsequence of [4,2,3,7,2,1,4] (the underlined elements), while [2,4,2] is not. ", + "category": [ + "Array", + "Hash Table", + "Binary Search", + "Greedy" + ], + "complexity": "Hard", + "successrate": 48.8, + "totalsubmissions": 14511, + "totalaccepted": 7085, + "likes": 410, + "dislikes": 8, + "hints": "The problem can be reduced to computing Longest Common Subsequence between both arrays. Since one of the arrays has distinct elements, we can consider that these elements describe an arrangement of numbers, and we can replace each element in the other array with the index it appeared at in the first array. Then the problem is converted to finding Longest Increasing Subsequence in the second array, which can be done in O(n log n).", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "target = [5,1,3], arr = [9,4,2,3,4]", + "expected_output": "2", + "explanation": "You can add 5 and 1 in such a way that makes arr = [5,9,4,1,2,3,4], then target will be a subsequence of arr." + }, + { + "example_num": 2, + "expected_input": "target = [6,4,8,1,3,2], arr = [4,7,6,2,3,8,6,1]", + "expected_output": "3", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} target\n * @param {number[]} arr\n * @return {number}\n */\nconst minOperations = function(target, arr) {\n const hash = {}\n for (let i = 0, n = target.length; i < n; i++) {\n hash[target[i]] = i\n }\n const stk = []\n for(let e of arr) {\n if(hash[e] == null) continue\n let l = 0, r = stk.length\n while(l < r) {\n const mid = l + (~~((r - l) / 2))\n if(stk[mid] < hash[e]) l = mid + 1\n else r = mid\n }\n stk[l] = hash[e]\n }\n return target.length - stk.length\n};\n\n// another\n\n/**\n * @param {number[]} target\n * @param {number[]} arr\n * @return {number}\n */\nconst minOperations = function (target, arr) {\n let length1 = target.length,\n length2 = arr.length\n const targetMap = new Map()\n for (let i = 0; i < length1; i++) targetMap.set(target[i], i)\n const list = new Array()\n for (let i = 0; i < length2; i++) {\n let num = arr[i]\n if (targetMap.has(num)) list.push(targetMap.get(num))\n }\n let longestIncreasing = lengthOfLIS(list)\n return target.length - longestIncreasing\n\n function lengthOfLIS(list) {\n let length = 1,\n size = list.length\n if (size == 0) return 0\n const d = new Array(size + 1).fill(0)\n d[length] = list[0]\n for (let i = 1; i < size; ++i) {\n if (list[i] > d[length]) {\n d[++length] = list[i]\n } else {\n let left = 1,\n right = length,\n pos = 0\n while (left <= right) {\n let mid = (left + right) >> 1\n if (d[mid] < list[i]) {\n pos = mid\n left = mid + 1\n } else {\n right = mid - 1\n }\n }\n d[pos + 1] = list[i]\n }\n }\n return length\n }\n}\n\n// another\n\n/**\n * @param {number[]} target\n * @param {number[]} arr\n * @return {number}\n */\nconst minOperations = function(target, arr) {\n const map = new Map()\n for(let i = 0, len = target.length; i < len; i++) {\n map.set(target[i], i)\n }\n const stack = []\n for(let a of arr) {\n if(!map.has(a)) continue\n if(stack.length === 0 || map.get(a) > stack[stack.length - 1]) {\n stack.push(map.get(a))\n continue\n }\n let left = 0, right = stack.length - 1, mid\n while(left < right) {\n mid = left + ((right - left) >> 1)\n if(stack[mid] < map.get(a)) left = mid + 1\n else right = mid\n }\n stack[left] = map.get(a)\n }\n\n return target.length - stack.length\n};\n\n// another\n\n/**\n * @param {number[]} target\n * @param {number[]} arr\n * @return {number}\n */\nconst minOperations = function(target, arr) {\n const hash = {}\n for(let i = 0, n = target.length; i < n; i++) {\n hash[target[i]] = i\n }\n const stack = []\n \n for(let e of arr) {\n if(hash[e] == null) continue\n const cur = hash[e]\n if(stack.length && cur > stack[stack.length - 1]) {\n stack.push(cur)\n continue\n }\n \n let l = 0, r = stack.length - 1\n \n while(l < r) {\n const mid = ~~((l + r) / 2)\n if(stack[mid] < cur) {\n l = mid + 1\n } else r = mid\n }\n \n stack[l] = cur\n \n }\n \n return target.length - stack.length\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720e3a", + "questionid": 879, + "title": "Decode XORed Permutation", + "slug": "decode-xored-permutation", + "description": "There is an integer array perm that is a permutation of the first n positive integers, where n is always odd. It was encoded into another integer array encoded of length n - 1, such that encoded[i] = perm[i] XOR perm[i + 1]. For example, if perm = [1,3,2], then encoded = [2,1]. Given the encoded array, return the original array perm. It is guaranteed that the answer exists and is unique. ", + "category": [ + "Array", + "Bit Manipulation" + ], + "complexity": "Medium", + "successrate": 60.7, + "totalsubmissions": 14967, + "totalaccepted": 9090, + "likes": 485, + "dislikes": 18, + "hints": "Compute the XOR of the numbers between 1 and n, and think about how it can be used. Let it be x. Think why n is odd. perm[0] = x XOR encoded[1] XOR encoded[3] XOR encoded[5] ... perm[i] = perm[i-1] XOR encoded[i-1]", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "encoded = [3,1]", + "expected_output": "[1,2,3]", + "explanation": "If perm = [1,2,3], then encoded = [1 XOR 2,2 XOR 3] = [3,1]" + }, + { + "example_num": 2, + "expected_input": "encoded = [6,5,4,6]", + "expected_output": "[2,4,1,5,3]", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} encoded\n * @return {number[]}\n */\nconst decode = function(encoded) {\n const n = encoded.length + 1\n let xor = 0\n for(let i = 1; i <= n; i++) xor ^= i\n for(let i = 1; i < n - 1; i += 2) xor ^= encoded[i]\n const res = [xor]\n let pre = xor\n for(let i = 0; i < n - 1; i++) {\n res.push(encoded[i] ^ pre)\n pre = res[res.length - 1]\n }\n \n return res\n};\n\n// another\n\n/**\n * @param {number[]} encoded\n * @return {number[]}\n */\nconst decode = function(encoded) {\n let a = 0\n const n = encoded.length + 1\n for(let i = 0; i <= n; i++) {\n a ^= i\n if(i < n && i % 2 === 1) a ^= encoded[i]\n }\n const res = [a]\n for(let i = 0; i < n - 1; i++) {\n res[i + 1] = res[i] ^ encoded[i]\n }\n \n return res\n};\n\n// another\n\n/**\n * @param {number[]} encoded\n * @return {number[]}\n */\nconst decode = function(A) {\n let xor = 0\n const len = A.length\n const permLen = len + 1\n for(let i = 1; i <= permLen; i++) {\n xor ^= i\n }\n // except first\n for(let i = 1; i < len; i += 2) xor ^= A[i]\n const first = xor\n const res = [xor]\n let pre = xor\n for(let i = 1; i < permLen; i++) {\n res[i] = A[i - 1] ^ pre\n pre = res[i]\n }\n return res; \n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720e3b", + "questionid": 880, + "title": "Count Ways to Make Array With Product", + "slug": "count-ways-to-make-array-with-product", + "description": "You are given a 2D integer array, queries. For each queries[i], where queries[i] = [ni, ki], find the number of different ways you can place positive integers into an array of size ni such that the product of the integers is ki. As the number of ways may be too large, the answer to the ith query is the number of ways modulo 109 + 7. Return an integer array answer where answer.length == queries.length, and answer[i] is the answer to the ith query. ", + "category": [ + "Array", + "Math", + "Dynamic Programming" + ], + "complexity": "Hard", + "successrate": 49.5, + "totalsubmissions": 6382, + "totalaccepted": 3160, + "likes": 154, + "dislikes": 25, + "hints": "Prime-factorize ki and count how many ways you can distribute the primes among the ni positions. After prime factorizing ki, suppose there are x amount of prime factor. There are (x + n - 1) choose (n - 1) ways to distribute the x prime factors into k positions, allowing repetitions.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "queries = [[2,6],[5,1],[73,660]]", + "expected_output": "[4,1,50734910]", + "explanation": " Each query is independent.\n[2,6]: There are 4 ways to fill an array of size 2 that multiply to 6: [1,6], [2,3], [3,2], [6,1].\n[5,1]: There is 1 way to fill an array of size 5 that multiply to 1: [1,1,1,1,1].\n[73,660]: There are 1050734917 ways to fill an array of size 73 that multiply to 660. 1050734917 modulo 109 + 7 = 50734910." + }, + { + "example_num": 2, + "expected_input": "queries = [[1,1],[2,2],[3,3],[4,4],[5,5]]", + "expected_output": "[1,2,3,10,5]", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[][]} queries\n * @return {number[]}\n */\nvar waysToFillArray = function (queries) {\n const nax = 10123\n const C = Array.from({ length: nax }, () => Array(15).fill(0n))\n const mod = BigInt(10 ** 9 + 7)\n if (C[1][1] == 0n) {\n for (let i = 0; i < nax; ++i) {\n C[i][0] = 1n\n if (i < 15) {\n C[i][i] = 1n\n }\n for (let j = 1; j < i && j < 15; ++j) {\n C[i][j] = (C[i - 1][j - 1] + C[i - 1][j]) % mod\n }\n }\n }\n const answer = []\n for (let query of queries) {\n let n = query[0]\n let k = query[1]\n let total = 1n\n const consider = (cnt) => {\n total = (total * C[n + cnt - 1][cnt]) % mod\n }\n for (let i = 2; i * i <= k; ++i) {\n if (k % i == 0) {\n let cnt = 0\n while (k % i == 0) {\n k = (k / i) >> 0\n cnt++\n }\n consider(cnt)\n }\n }\n if (k != 1) {\n consider(1)\n }\n answer.push(total)\n }\n return answer\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720e3f", + "questionid": 884, + "title": "Maximum Number of Balls in a Box", + "slug": "maximum-number-of-balls-in-a-box", + "description": "You are working in a ball factory where you have n balls numbered from lowLimit up to highLimit inclusive (i.e., n == highLimit - lowLimit + 1), and an infinite number of boxes numbered from 1 to infinity. Your job at this factory is to put each ball in the box with a number equal to the sum of digits of the ball's number. For example, the ball number 321 will be put in the box number 3 + 2 + 1 = 6 and the ball number 10 will be put in the box number 1 + 0 = 1. Given two integers lowLimit and highLimit, return the number of balls in the box with the most balls. ", + "category": [ + "Hash Table", + "Math", + "Counting" + ], + "complexity": "Easy", + "successrate": 73.7, + "totalsubmissions": 51413, + "totalaccepted": 37887, + "likes": 362, + "dislikes": 85, + "hints": "Note that both lowLimit and highLimit are of small constraints so you can iterate on all nubmer between them You can simulate the boxes by counting for each box the number of balls with digit sum equal to that box number", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "lowLimit = 1, highLimit = 10", + "expected_output": "2", + "explanation": "Box Number: 1 2 3 4 5 6 7 8 9 10 11 ...\nBall Count: 2 1 1 1 1 1 1 1 1 0 0 ...\nBox 1 has the most number of balls with 2 balls." + }, + { + "example_num": 2, + "expected_input": "lowLimit = 5, highLimit = 15", + "expected_output": "2", + "explanation": "Box Number: 1 2 3 4 5 6 7 8 9 10 11 ...\nBall Count: 1 1 1 1 2 2 1 1 1 0 0 ...\nBoxes 5 and 6 have the most number of balls with 2 balls in each." + }, + { + "example_num": 3, + "expected_input": "lowLimit = 19, highLimit = 28", + "expected_output": "2", + "explanation": "Box Number: 1 2 3 4 5 6 7 8 9 10 11 12 ...\nBall Count: 0 1 1 1 1 1 1 1 1 2 0 0 ...\nBox 10 has the most number of balls with 2 balls." + } + ], + "solution": "/**\n * @param {number} lowLimit\n * @param {number} highLimit\n * @return {number}\n */\nconst countBalls = function(lowLimit, highLimit) {\n const m = {}\n for(let i = lowLimit; i <= highLimit; i++) {\n const tmp = (i + '').split('').map(e => +e).reduce((ac, e) => ac + e, 0)\n if(m[tmp] == null) m[tmp] = 0\n m[tmp]++\n }\n const arr = Object.values(m)\n arr.sort((a, b) => b - a)\n return arr[0]\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720e44", + "questionid": 889, + "title": "Palindrome Partitioning IV", + "slug": "palindrome-partitioning-iv", + "description": "Given a string s, return true if it is possible to split the string s into three non-empty palindromic substrings. Otherwise, return false. A string is said to be palindrome if it the same string when reversed. ", + "category": [ + "String", + "Dynamic Programming" + ], + "complexity": "Hard", + "successrate": 49, + "totalsubmissions": 29581, + "totalaccepted": 14483, + "likes": 485, + "dislikes": 14, + "hints": "Preprocess checking palindromes in O(1) Note that one string is a prefix and another one is a suffix you can try brute forcing the rest", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "abcbdd"", + "expected_output": "true\nExplanation: "abcbdd" = "a" + "bcb" + "dd", and all three substrings are palindromes.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "s = "bcbddxy"", + "expected_output": "false\nExplanation: s cannot be split into 3 palindromes.", + "explanation": "" + } + ], + "solution": "/**\n * @param {string} s\n * @return {boolean}\n */\nconst checkPartitioning = function(s) {\n const map = manacher(s);\n return checkPartitioningDfs(map, s, 0);\n};\n\nfunction checkPartitioningDfs(map, word, i, path = []) {\n if (path.length > 3) return false;\n if (path.length == 3 && path.join('') == word) return true;\n let found = false;\n const length = map.get(i);\n path.push(word.substr(i, length));\n found = found || checkPartitioningDfs(map, word, i + length, path);\n path.pop();\n\n path.push(word.substr(i, 1));\n found = found || checkPartitioningDfs(map, word, i + 1, path);\n path.pop();\n \n return found;\n}\n\nfunction manacher(s) {\n const t = '^#' + s.split('').join('#') + '#$';\n let r = 0;\n let c = 0;\n let maxC = 0;\n const rad = new Array(t.length).fill(0);\n for (let i = 1; i < t.length - 1; ++i) {\n if (r > i) rad[i] = Math.min(rad[2 * c - i], r - i);\n while (t[i - rad[i] - 1] == t[i + rad[i] + 1]) rad[i]++;\n if (i + rad[i] > r) {\n c = i;\n r = i + rad[i];\n }\n if (rad[c] > rad[maxC]) maxC = c;\n }\n const ans = new Map();\n for (let i = 0; i < rad.length; ++i) {\n if (rad[i] > 0) {\n ans.set((i - rad[i] - 1) >>> 1, rad[i]);\n }\n }\n return ans;\n}\n\n// another\n\n/**\n * @param {string} s\n * @return {boolean}\n */\nconst checkPartitioning = function (s) {\n const n = s.length\n const dp = Array.from({ length: n }, () => Array(n).fill(false))\n for(let i = n - 1; i >= 0; i--) {\n for(let j = i; j < n; j++) {\n if(s[i] === s[j]) {\n dp[i][j] = i + 1 <= j - 1 ? dp[i + 1][j - 1] : true\n } else dp[i][j] = false\n }\n }\n for(let i = 1; i < n - 1; i++) {\n for(let j = i; j < n - 1; j++) {\n if(dp[0][i - 1] && dp[i][j] && dp[j + 1][n - 1]) return true\n }\n }\n return false\n}\n\n\n// another\n\n/**\n * @param {string} s\n * @return {boolean}\n */\nconst checkPartitioning = function(s) {\n for(let i = 1, len = s.length; i < len - 1; i++) {\n for(let j = i + 1; j < len; j++) {\n const s1 = s.slice(0, i), s2 = s.slice(i, j), s3 = s.slice(j)\n if(chk(s1) && chk(s2) && chk(s3)) return true\n }\n }\n return false\n};\n\nfunction chk(s) {\n let l = 0, r = s.length - 1\n for(;l <= r;) {\n if(s[l] === s[r]) {\n l++\n r--\n } else return false\n }\n return true\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720e4a", + "questionid": 895, + "title": "Minimum Changes To Make Alternating Binary String", + "slug": "minimum-changes-to-make-alternating-binary-string", + "description": "You are given a string s consisting only of the characters '0' and '1'. In one operation, you can change any '0' to '1' or vice versa. The string is called alternating if no two adjacent characters are equal. For example, the string \"010\" is alternating, while the string \"0100\" is not. Return the minimum number of operations needed to make s alternating. ", + "category": [ + "String" + ], + "complexity": "Easy", + "successrate": 59.1, + "totalsubmissions": 45138, + "totalaccepted": 26699, + "likes": 397, + "dislikes": 14, + "hints": "Think about how the final string will look like. It will either start with a '0' and be like '010101010..' or with a '1' and be like '10101010..' Try both ways, and check for each way, the number of changes needed to reach it from the given string. The answer is the minimum of both ways.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "0100"", + "expected_output": "1", + "explanation": "If you change the last character to '1', s will be "0101", which is alternating." + }, + { + "example_num": 2, + "expected_input": "s = "10"", + "expected_output": "0", + "explanation": "s is already alternating." + }, + { + "example_num": 3, + "expected_input": "s = "1111"", + "expected_output": "2", + "explanation": "You need two operations to reach "0101" or "1010"." + } + ], + "solution": "/**\n * @param {string} s\n * @return {number}\n */\nconst minOperations = function(s) {\n const arr = s.split('')\n return Math.min(helper(arr, 0, '0'), helper(arr, 0, '1'))\n \n function helper(arr, idx, ch) {\n if(idx === arr.length) return 0\n if(arr[idx] !== ch) return 1 + helper(arr, idx + 1, ch === '0' ? '1' : '0')\n else return helper(arr, idx + 1, ch === '0' ? '1' : '0')\n }\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720e10", + "questionid": 837, + "title": "Sort Array by Increasing Frequency", + "slug": "sort-array-by-increasing-frequency", + "description": "Given an array of integers nums, sort the array in increasing order based on the frequency of the values. If multiple values have the same frequency, sort them in decreasing order. Return the sorted array. ", + "category": [ + "Array", + "Hash Table", + "Sorting" + ], + "complexity": "Easy", + "successrate": 68.4, + "totalsubmissions": 84701, + "totalaccepted": 57909, + "likes": 1308, + "dislikes": 50, + "hints": "Count the frequency of each value. Use a custom comparator to compare values by their frequency. If two values have the same frequency, compare their values.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,1,2,2,2,3]", + "expected_output": "[3,1,1,2,2,2]", + "explanation": "'3' has a frequency of 1, '1' has a frequency of 2, and '2' has a frequency of 3." + }, + { + "example_num": 2, + "expected_input": "nums = [2,3,1,3,2]", + "expected_output": "[1,3,3,2,2]", + "explanation": "'2' and '3' both have a frequency of 2, so they are sorted in decreasing order." + }, + { + "example_num": 3, + "expected_input": "nums = [-1,1,-6,4,5,-6,1,4,1]", + "expected_output": "[5,-1,4,4,-6,-6,1,1,1]", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} nums\n * @return {number[]}\n */\nconst frequencySort = function(nums) {\n const hash = {}\n for(let e of nums) {\n if(hash[e] == null) hash[e] = 0\n hash[e]++\n }\n nums.sort((a, b) => hash[a] === hash[b] ? b - a : hash[a] - hash[b])\n return nums\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720e12", + "questionid": 839, + "title": "Count Substrings That Differ by One Character", + "slug": "count-substrings-that-differ-by-one-character", + "description": "Given two strings s and t, find the number of ways you can choose a non-empty substring of s and replace a single character by a different character such that the resulting substring is a substring of t. In other words, find the number of substrings in s that differ from some substring in t by exactly one character. For example, the underlined substrings in \"computer\" and \"computation\" only differ by the 'e'/'a', so this is a valid way. Return the number of substrings that satisfy the condition above. A substring is a contiguous sequence of characters within a string. ", + "category": [ + "Hash Table", + "String", + "Dynamic Programming" + ], + "complexity": "Medium", + "successrate": 71.9, + "totalsubmissions": 23756, + "totalaccepted": 17088, + "likes": 653, + "dislikes": 244, + "hints": "Take every substring of s, change a character, and see how many substrings of t match that substring. Use a Trie to store all substrings of t as a dictionary.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "aba", t = "baba"", + "expected_output": "6", + "explanation": "The following are the pairs of substrings from s and t that differ by exactly 1 character:\n("aba", "baba")\n("aba", "baba")\n("aba", "baba")\n("aba", "baba")\n("aba", "baba")\n("aba", "baba")\nThe underlined portions are the substrings that are chosen from s and t." + }, + { + "example_num": 2, + "expected_input": "s = "ab", t = "bb"", + "expected_output": "3", + "explanation": "The following are the pairs of substrings from s and t that differ by 1 character:\n("ab", "bb")\n("ab", "bb")\n("ab", "bb")\n\u200b\u200b\u200b\u200bThe underlined portions are the substrings that are chosen from s and t." + } + ], + "solution": "/**\n * @param {string} s\n * @param {string} t\n * @return {number}\n */\nconst countSubstrings = function (s, t) {\n const m = s.length\n const n = t.length\n const matrix = (m, n, v) => Array.from({ length: m }, () => Array(n).fill(v))\n // number of exact same substrings ending at s[i] and t[j].\n const same = matrix(m + 1, n + 1, 0)\n // number of substrings having 1 different character ending at s[i] and t[j].\n const one = matrix(m + 1, n + 1, 0)\n let result = 0\n for (let i = 1; i <= m; ++i) {\n for (let j = 1; j <= n; ++j) {\n if (s[i - 1] == t[j - 1]) {\n same[i][j] = same[i - 1][j - 1] + 1\n one[i][j] = one[i - 1][j - 1]\n } else {\n one[i][j] = same[i - 1][j - 1] + 1\n }\n result += one[i][j]\n }\n }\n return result\n}\n\n// another\n\n/**\n * @param {string} s\n * @param {string} t\n * @return {number}\n */\nconst countSubstrings = function(s, t) {\n let res = 0 ;\n for (let i = 0; i < s.length; ++i) res += helper(s, t, i, 0);\n for (let j = 1; j < t.length; ++j) res += helper(s, t, 0, j);\n return res;\n};\n\nfunction helper(s, t, i, j) {\n let res = 0, pre = 0, cur = 0;\n for (let n = s.length, m = t.length; i < n && j < m; ++i, ++j) {\n cur++;\n if (s.charAt(i) !== t.charAt(j)) {\n pre = cur;\n cur = 0;\n }\n res += pre;\n }\n return res;\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720e14", + "questionid": 841, + "title": "Best Team With No Conflicts", + "slug": "best-team-with-no-conflicts", + "description": "You are the manager of a basketball team. For the upcoming tournament, you want to choose the team with the highest overall score. The score of the team is the sum of scores of all the players in the team. However, the basketball team is not allowed to have conflicts. A conflict exists if a younger player has a strictly higher score than an older player. A conflict does not occur between players of the same age. Given two lists, scores and ages, where each scores[i] and ages[i] represents the score and age of the ith player, respectively, return the highest overall score of all possible basketball teams. ", + "category": [ + "Array", + "Dynamic Programming", + "Sorting" + ], + "complexity": "Medium", + "successrate": 40.7, + "totalsubmissions": 44467, + "totalaccepted": 18099, + "likes": 791, + "dislikes": 28, + "hints": "First, sort players by age and break ties by their score. You can now consider the players from left to right. If you choose to include a player, you must only choose players with at least that score later on.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "scores = [1,3,5,10,15], ages = [1,2,3,4,5]", + "expected_output": "34", + "explanation": " You can choose all the players." + }, + { + "example_num": 2, + "expected_input": "scores = [4,5,6,5], ages = [2,1,2,1]", + "expected_output": "16", + "explanation": " It is best to choose the last 3 players. Notice that you are allowed to choose multiple people of the same age." + }, + { + "example_num": 3, + "expected_input": "scores = [1,2,3,5], ages = [8,9,10,1]", + "expected_output": "6", + "explanation": " It is best to choose the first 3 players." + } + ], + "solution": "/**\n * @param {number[]} scores\n * @param {number[]} ages\n * @return {number}\n */\nconst bestTeamScore = function(scores, ages) {\n const len = ages.length\n const arr = Array(len)\n for(let i = 0; i < len; i++) {\n arr[i] = [scores[i], ages[i]] \n }\n arr.sort((a, b) => {\n if(a[1] > b[1]) return 1\n else if(a[1] === b[1]) return a[0] - b[0]\n else return -1\n })\n const dp = Array(len)\n let res = 0\n for(let i = 0; i < len; i++) {\n dp[i] = arr[i][0]\n for(let j = i - 1; j >= 0; j--) {\n if(arr[j][0] > arr[i][0] && arr[j][1] < arr[i][1]) {\n continue\n }\n dp[i] = Math.max(dp[i], dp[j] + arr[i][0])\n }\n res = Math.max(res, dp[i])\n }\n return res\n};\n\n" + }, + { + "_id": "66f925ddfdfb8e1665720e15", + "questionid": 842, + "title": "Slowest Key", + "slug": "slowest-key", + "description": "A newly designed keypad was tested, where a tester pressed a sequence of n keys, one at a time. You are given a string keysPressed of length n, where keysPressed[i] was the ith key pressed in the testing sequence, and a sorted list releaseTimes, where releaseTimes[i] was the time the ith key was released. Both arrays are 0-indexed. The 0th key was pressed at the time 0,\u00a0and every subsequent key was pressed at the exact time the previous key was released. The tester wants to know the key of the keypress that had the longest duration. The ith keypress had a duration of releaseTimes[i] - releaseTimes[i - 1], and the 0th keypress had a duration of releaseTimes[0]. Note that the same key could have been pressed multiple times during the test, and these multiple presses of the same key may not have had the same duration. Return the key of the keypress that had the longest duration. If there are multiple such keypresses, return the lexicographically largest key of the keypresses. ", + "category": [ + "Array", + "String" + ], + "complexity": "Easy", + "successrate": 59.6, + "totalsubmissions": 126419, + "totalaccepted": 75374, + "likes": 521, + "dislikes": 85, + "hints": "Get for each press its key and amount of time taken. Iterate on the presses, maintaining the answer so far. The current press will change the answer if and only if its amount of time taken is longer than that of the previous answer, or they are equal but the key is larger than that of the previous answer.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "releaseTimes = [9,29,49,50], keysPressed = "cbcd"", + "expected_output": ""c"", + "explanation": "The keypresses were as follows:\nKeypress for 'c' had a duration of 9 (pressed at time 0 and released at time 9).\nKeypress for 'b' had a duration of 29 - 9 = 20 (pressed at time 9 right after the release of the previous character and released at time 29).\nKeypress for 'c' had a duration of 49 - 29 = 20 (pressed at time 29 right after the release of the previous character and released at time 49).\nKeypress for 'd' had a duration of 50 - 49 = 1 (pressed at time 49 right after the release of the previous character and released at time 50).\nThe longest of these was the keypress for 'b' and the second keypress for 'c', both with duration 20.\n'c' is lexicographically larger than 'b', so the answer is 'c'." + }, + { + "example_num": 2, + "expected_input": "releaseTimes = [12,23,36,46,62], keysPressed = "spuda"", + "expected_output": ""a"", + "explanation": "The keypresses were as follows:\nKeypress for 's' had a duration of 12.\nKeypress for 'p' had a duration of 23 - 12 = 11.\nKeypress for 'u' had a duration of 36 - 23 = 13.\nKeypress for 'd' had a duration of 46 - 36 = 10.\nKeypress for 'a' had a duration of 62 - 46 = 16.\nThe longest of these was the keypress for 'a' with duration 16." + } + ], + "solution": "/**\n * @param {number[]} releaseTimes\n * @param {string} keysPressed\n * @return {character}\n */\nconst slowestKey = function(releaseTimes, keysPressed) {\n const m = {}\n const n = keysPressed.length\n const set = new Set()\n set.add(keysPressed[0])\n m[releaseTimes[0]] = set\n for(let i = 1; i < n; i++) {\n const k = releaseTimes[i] - releaseTimes[i - 1]\n if(m[k] == null) m[k] = new Set()\n m[k].add(keysPressed[i])\n }\n const keys = Object.keys(m).sort((a, b) => a - b)\n const last = keys[keys.length - 1]\n const arr = Array.from(m[last])\n arr.sort()\n return arr[arr.length - 1]\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720e17", + "questionid": 844, + "title": "Defuse the Bomb", + "slug": "defuse-the-bomb", + "description": "You have a bomb to defuse, and your time is running out! Your informer will provide you with a circular array code\u00a0of length of n\u00a0and a key k. To decrypt the code, you must replace every number. All the numbers are replaced simultaneously. As code is circular, the next element of code[n-1] is code[0], and the previous element of code[0] is code[n-1]. Given the circular array code and an integer key k, return the decrypted code to defuse the bomb! ", + "category": [ + "Array" + ], + "complexity": "Easy", + "successrate": 60.8, + "totalsubmissions": 37170, + "totalaccepted": 22582, + "likes": 414, + "dislikes": 45, + "hints": "As the array is circular, use modulo to find the correct index. The constraints are low enough for a brute-force solution.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "code = [5,7,1,4], k = 3", + "expected_output": "[12,10,16,13]", + "explanation": "Each number is replaced by the sum of the next 3 numbers. The decrypted code is [7+1+4, 1+4+5, 4+5+7, 5+7+1]. Notice that the numbers wrap around." + }, + { + "example_num": 2, + "expected_input": "code = [1,2,3,4], k = 0", + "expected_output": "[0,0,0,0]", + "explanation": "When k is zero, the numbers are replaced by 0." + }, + { + "example_num": 3, + "expected_input": "code = [2,4,9,3], k = -2", + "expected_output": "[12,5,6,13]", + "explanation": "The decrypted code is [3+9, 2+3, 4+2, 9+4]. Notice that the numbers wrap around again. If k is negative, the sum is of the previous numbers." + } + ], + "solution": "/**\n * @param {number[]} code\n * @param {number} k\n * @return {number[]}\n */\nconst decrypt = function(code, k) {\n const res = new Array(code.length).fill(0);\n if (k === 0) return res;\n let start = 1, end = k, sum = 0;\n if (k < 0) {\n k = -k;\n start = code.length - k;\n end = code.length - 1;\n }\n for (let i = start; i <= end; i++) sum += code[i];\n for (let i = 0; i < code.length; i++) {\n res[i] = sum;\n sum -= code[(start++) % code.length];\n sum += code[(++end) % code.length];\n }\n return res;\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720e1f", + "questionid": 852, + "title": "Minimum Operations to Reduce X to Zero", + "slug": "minimum-operations-to-reduce-x-to-zero", + "description": "You are given an integer array nums and an integer x. In one operation, you can either remove the leftmost or the rightmost element from the array nums and subtract its value from x. Note that this modifies the array for future operations. Return the minimum number of operations to reduce x to exactly 0 if it is possible, otherwise, return -1. ", + "category": [ + "Array", + "Hash Table", + "Binary Search", + "Sliding Window", + "Prefix Sum" + ], + "complexity": "Medium", + "successrate": 33.5, + "totalsubmissions": 136320, + "totalaccepted": 45728, + "likes": 1552, + "dislikes": 28, + "hints": "Think in reverse; instead of finding the minimum prefix + suffix, find the maximum subarray. Finding the maximum subarray is standard and can be done greedily.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,1,4,2,3], x = 5", + "expected_output": "2", + "explanation": "The optimal solution is to remove the last two elements to reduce x to zero." + }, + { + "example_num": 2, + "expected_input": "nums = [5,6,7,8,9], x = 4", + "expected_output": "-1", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "nums = [3,2,20,1,1,3], x = 10", + "expected_output": "5", + "explanation": "The optimal solution is to remove the last three elements and the first two elements (5 operations in total) to reduce x to zero." + } + ], + "solution": "/**\n * @param {number[]} nums\n * @param {number} x\n * @return {number}\n */\nconst minOperations = function(nums, x) {\n const n = nums.length\n const sum = nums.reduce((ac, e) => ac + e, 0)\n const target = sum - x\n if(target < 0) return -1\n if(target === 0) return n\n const map = new Map()\n map.set(0, -1)\n let res = 0\n for(let i = 0, cur = 0; i < n; i++) {\n cur += nums[i]\n if(map.has(cur - target)) {\n res = Math.max(res, i - map.get(cur - target))\n }\n \n if(!map.has(cur)) map.set(cur, i)\n }\n \n return res === 0 ? -1 : n - res\n};\n\n// another\n\n/**\n * @param {number[]} nums\n * @param {number} x\n * @return {number}\n */\nconst minOperations = function(nums, x) {\n const sum = nums.reduce((ac, e) => ac + e, 0)\n const subArrSum = sum - x\n if(subArrSum === 0) return nums.length\n const n = nums.length, hash = {0: -1}\n let ac = 0, res = -1\n for(let i = 0; i < n; i++) {\n const cur = nums[i]\n ac += cur\n if(hash[ac - subArrSum] != null) {\n res = Math.max(res, i - hash[ac - subArrSum])\n }\n hash[ac] = i\n }\n \n return res === -1 ? -1 : n - res\n};\n\n// another\n\n/**\n * @param {number[]} nums\n * @param {number} x\n * @return {number}\n */\nconst minOperations = function (nums, x) {\n let l = 0,\n r = nums.length - 1;\n while (x >= 0 && r >= l) {\n x -= nums[r];\n r -= 1;\n }\n if (r < 0 && x > 0) {\n return -1;\n } else if (r < 0 && x == 0) {\n return nums.length;\n }\n\n let ans = Number.MAX_VALUE;\n while (r < nums.length) {\n while (x <= 0 && r + 1 < nums.length) {\n if (x == 0) ans = Math.min(ans, nums.length - (r - l + 1));\n x += nums[r + 1];\n r += 1;\n }\n if (r + 1 >= nums.length) {\n if (x == 0) ans = Math.min(ans, nums.length - (r - l + 1));\n break;\n }\n while (x >= 0) {\n if (x == 0) ans = Math.min(ans, nums.length - (r - l + 1));\n x -= nums[l];\n l += 1;\n }\n }\n return ans != Number.MAX_VALUE ? ans : -1;\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720e20", + "questionid": 853, + "title": "Check If Two String Arrays are Equivalent", + "slug": "check-if-two-string-arrays-are-equivalent", + "description": "Given two string arrays word1 and word2, return true if the two arrays represent the same string, and false otherwise. A string is represented by an array if the array elements concatenated in order forms the string. ", + "category": [ + "Array", + "String" + ], + "complexity": "Easy", + "successrate": 82, + "totalsubmissions": 169765, + "totalaccepted": 139123, + "likes": 764, + "dislikes": 109, + "hints": "Concatenate all strings in the first array into a single string in the given order, the same for the second array. Both arrays represent the same string if and only if the generated strings are the same.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "word1 = ["ab", "c"], word2 = ["a", "bc"]", + "expected_output": "true", + "explanation": "word1 represents string "ab" + "c" -> "abc"\nword2 represents string "a" + "bc" -> "abc"\nThe strings are the same, so return true." + }, + { + "example_num": 2, + "expected_input": "word1 = ["a", "cb"], word2 = ["ab", "c"]", + "expected_output": "false", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "word1 = ["abc", "d", "defg"], word2 = ["abcddefg"]", + "expected_output": "true", + "explanation": "" + } + ], + "solution": "/**\n * @param {string[]} word1\n * @param {string[]} word2\n * @return {boolean}\n */\nconst arrayStringsAreEqual = function(word1, word2) {\n return word1.join('') === word2.join('')\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720e28", + "questionid": 861, + "title": "Max Number of K-Sum Pairs", + "slug": "max-number-of-k-sum-pairs", + "description": "You are given an integer array nums and an integer k. In one operation, you can pick two numbers from the array whose sum equals k and remove them from the array. Return the maximum number of operations you can perform on the array. ", + "category": [ + "Array", + "Hash Table", + "Two Pointers", + "Sorting" + ], + "complexity": "Medium", + "successrate": 53.6, + "totalsubmissions": 95121, + "totalaccepted": 50972, + "likes": 689, + "dislikes": 25, + "hints": "The abstract problem asks to count the number of disjoint pairs with a given sum k. For each possible value x, it can be paired up with k - x. The number of such pairs equals to min(count(x), count(k-x)), unless that x = k / 2, where the number of such pairs will be floor(count(x) / 2).", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,2,3,4], k = 5", + "expected_output": "2", + "explanation": "Starting with nums = [1,2,3,4]:\n- Remove numbers 1 and 4, then nums = [2,3]\n- Remove numbers 2 and 3, then nums = []\nThere are no more pairs that sum up to 5, hence a total of 2 operations." + }, + { + "example_num": 2, + "expected_input": "nums = [3,1,3,4,3], k = 6", + "expected_output": "1", + "explanation": "Starting with nums = [3,1,3,4,3]:\n- Remove the first two 3's, then nums = [1,4,3]\nThere are no more pairs that sum up to 6, hence a total of 1 operation." + } + ], + "solution": "/**\n * @param {number[]} nums\n * @param {number} k\n * @return {number}\n */\nconst maxOperations = function(nums, k) {\n const m = new Map()\n let res = 0\n for(let e of nums) {\n if(!m.has(e)) m.set(e, 0)\n if(m.has(k - e) && m.get(k - e)) {\n res++\n m.set(k - e, m.get(k - e) - 1)\n } else {\n m.set(e, m.get(e) + 1)\n }\n }\n return res;\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720e29", + "questionid": 862, + "title": "Minimum Incompatibility", + "slug": "minimum-incompatibility", + "description": "You are given an integer array nums and an integer k. You are asked to distribute this array into k subsets of equal size such that there are no two equal elements in the same subset. A subset's incompatibility is the difference between the maximum and minimum elements in that array. Return the minimum possible sum of incompatibilities of the k subsets after distributing the array optimally, or return -1 if it is not possible. A subset is a group integers that appear in the array with no particular order. ", + "category": [ + "Array", + "Dynamic Programming", + "Bit Manipulation", + "Bitmask" + ], + "complexity": "Hard", + "successrate": 37, + "totalsubmissions": 15608, + "totalaccepted": 5769, + "likes": 177, + "dislikes": 81, + "hints": "The constraints are small enough for a backtrack solution but not any backtrack solution If we use a naive n^k don't you think it can be optimized", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,2,1,4], k = 2", + "expected_output": "4", + "explanation": "The optimal distribution of subsets is [1,2] and [1,4].\nThe incompatibility is (2-1) + (4-1) = 4.\nNote that [1,1] and [2,4] would result in a smaller sum, but the first subset contains 2 equal elements." + }, + { + "example_num": 2, + "expected_input": "nums = [6,3,8,1,3,1,2,2], k = 4", + "expected_output": "6", + "explanation": "The optimal distribution of subsets is [1,2], [2,3], [6,8], and [1,3].\nThe incompatibility is (2-1) + (3-2) + (8-6) + (3-1) = 6." + }, + { + "example_num": 3, + "expected_input": "nums = [5,3,3,6,3,3], k = 3", + "expected_output": "-1", + "explanation": "It is impossible to distribute nums into 3 subsets where no two elements are equal in the same subset." + } + ], + "solution": "/**\n * @param {number[]} nums\n * @param {number} k\n * @return {number}\n */\nconst minimumIncompatibility = function(nums, k) {\n const n = nums.length\n const size = n / k\n const mod = 1e9 + 7\n if(size === 1) return 0\n const limit = 1 << n\n const dp = Array.from({ length: limit }, () => Array(16).fill(Infinity))\n for(let i = 0; i < n; i++) dp[1 << i][i] = 0\n \n for(let mask = 0; mask < limit; mask++) {\n for(let i = 0; i < n; i++) {\n if((mask & (1 << i)) === 0) continue\n for(let j = 0; j < n; j++) {\n if((mask & (1 << j))) continue\n const newMask = mask | (1 << j)\n if(bitCnt(mask) % size === 0) {\n dp[newMask][j] = Math.min(dp[newMask][j], dp[mask][i])\n } else if(nums[j] > nums[i]) {\n dp[newMask][j] = Math.min(dp[newMask][j], dp[mask][i] + nums[j] - nums[i])\n }\n }\n }\n }\n\n const candidate = Math.min(...dp.at(-1))\n \n return candidate === Infinity ? -1 : candidate\n \n function bitCnt(num) {\n let res = 0\n while(num) {\n if(num & 1) res++\n num = num >> 1\n }\n \n return res\n }\n};\n\n// another\n\n/**\n * @param {number[]} nums\n * @param {number} k\n * @return {number}\n */\nvar minimumIncompatibility = function (nums, k) {\n if (k === nums.length) {\n return 0\n }\n const counts = Array(nums.length + 1).fill(0)\n for (let num of nums) {\n counts[num]++\n if (counts[num] > k) {\n return -1\n }\n }\n const size = nums.length / k\n let ans = Number.MAX_VALUE\n const backtracking = (groupIdx, index, sum, lowIndex, curIndex) => {\n if (index === size) {\n sum += curIndex - lowIndex\n if (sum > ans) {\n return\n }\n if (groupIdx === k - 1) {\n ans = sum\n return\n } else {\n groupIdx++\n index = 0\n }\n }\n if (index === 0) {\n for (let i = 0; i < counts.length; i++) {\n if (counts[i]) {\n counts[i]--\n backtracking(groupIdx, index + 1, sum, i, i)\n counts[i]++\n }\n }\n } else {\n for (let i = curIndex + 1; i < counts.length; i++) {\n if (counts[i]) {\n counts[i]--\n backtracking(groupIdx, index + 1, sum, lowIndex, i)\n counts[i]++\n }\n }\n }\n }\n backtracking(0, 0, 0, 0, 0)\n return ans\n}\n\n// another\n\n/**\n * @param {number[]} nums\n * @param {number} k\n * @return {number}\n */\nconst minimumIncompatibility = function (nums, k) {\n if (nums.length === k) return 0\n const maxInBucket = nums.length / k\n const freqCount = {}\n for (const n of nums) {\n if (freqCount[n]) {\n if (freqCount[n] === k) {\n return -1\n } else {\n freqCount[n]++\n }\n } else {\n freqCount[n] = 1\n }\n }\n const cache = {}\n const allIndiciesUsedMask = 2 ** nums.length - 1\n const dfs = (usedIndicesBitMask) => {\n if (usedIndicesBitMask === allIndiciesUsedMask) {\n return 0\n }\n if (cache[usedIndicesBitMask]) {\n return cache[usedIndicesBitMask]\n }\n const valsToIndices = {}\n for (let i = 0; i < nums.length; i++) {\n const indexMask = 1 << i\n if (usedIndicesBitMask & indexMask) continue\n const value = nums[i]\n if (!valsToIndices.hasOwnProperty(value)) {\n valsToIndices[value] = i\n }\n }\n const indicesAvailable = Object.values(valsToIndices)\n let minIncompatibilityCost = Infinity\n const combinations = createCombinations(indicesAvailable, maxInBucket)\n for (const indices of combinations) {\n let nextMask = usedIndicesBitMask\n let minVal = Infinity\n let maxVal = -Infinity\n for (const index of indices) {\n minVal = Math.min(minVal, nums[index])\n maxVal = Math.max(maxVal, nums[index])\n nextMask = nextMask | (1 << index)\n }\n const incompatibilityCost = maxVal - minVal\n minIncompatibilityCost = Math.min(\n minIncompatibilityCost,\n dfs(nextMask) + incompatibilityCost\n )\n }\n return (cache[usedIndicesBitMask] = minIncompatibilityCost)\n }\n return dfs(0)\n}\n\nfunction createCombinations(indices, len) {\n const combinations = []\n if (indices.length < len) {\n return combinations\n }\n const stack = [[[], 0]]\n while (stack.length > 0) {\n let [combi, i] = stack.pop()\n for (; i < indices.length; i++) {\n const combination = [...combi, indices[i]]\n if (combination.length === len) {\n combinations.push(combination)\n } else {\n stack.push([combination, i + 1])\n }\n }\n }\n return combinations\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720e2b", + "questionid": 864, + "title": "Minimum Adjacent Swaps for K Consecutive Ones", + "slug": "minimum-adjacent-swaps-for-k-consecutive-ones", + "description": "You are given an integer array, nums, and an integer k. nums comprises of only 0's and 1's. In one move, you can choose two adjacent indices and swap their values. Return the minimum number of moves required so that nums has k consecutive 1's. ", + "category": [ + "Array", + "Greedy", + "Sliding Window", + "Prefix Sum" + ], + "complexity": "Hard", + "successrate": 40.7, + "totalsubmissions": 14315, + "totalaccepted": 5824, + "likes": 419, + "dislikes": 16, + "hints": "Choose k 1s and determine how many steps are required to move them into 1 group. Maintain a sliding window of k 1s, and maintain the steps required to group them. When you slide the window across, should you move the group to the right? Once you move the group to the right, it will never need to slide to the left again.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,0,0,1,0,1], k = 2", + "expected_output": "1", + "explanation": "In 1 move, nums could be [1,0,0,0,1,1] and have 2 consecutive 1's." + }, + { + "example_num": 2, + "expected_input": "nums = [1,0,0,0,0,0,1,1], k = 3", + "expected_output": "5", + "explanation": "In 5 moves, the leftmost 1 can be shifted right until nums = [0,0,0,0,0,1,1,1]." + }, + { + "example_num": 3, + "expected_input": "nums = [1,1,0,1], k = 2", + "expected_output": "0", + "explanation": "nums already has 2 consecutive 1's." + } + ], + "solution": "/**\n * @param {number[]} nums\n * @param {number} k\n * @return {number}\n */\nvar minMoves = function(nums, k) {\n if (k == 1) return 0;\n let n = 0;\n let pos = [];\n for (let i = 0; i < nums.length; ++i) {\n if (nums[i]) {\n pos.push(i - (n++));\n }\n }\n let sums = [];\n sums[0] = pos[0];\n for (let i = 1; i < n; ++i) {\n sums[i] = pos[i] + sums[i - 1];\n }\n let res = Number.MAX_VALUE;\n let l = (k / 2) >> 0, r = k - l - 1;\n for (let i = 0; i + k <= n; ++i) {\n let m = i + ((k / 2) >>> 0);\n let cur = pos[m] * l - (sums[m - 1] - sums[i] + pos[i]) - pos[m] * r + sums[i + k - 1] - sums[m];\n res = Math.min(cur, res);\n }\n return res;\n};\n\n" + }, + { + "_id": "66f925ddfdfb8e1665720e2d", + "questionid": 866, + "title": "Stone Game VII", + "slug": "stone-game-vii", + "description": "Alice and Bob take turns playing a game, with Alice starting first. There are n stones arranged in a row. On each player's turn, they can remove either the leftmost stone or the rightmost stone from the row and receive points equal to the sum of the remaining stones' values in the row. The winner is the one with the higher score when there are no stones left to remove. Bob found that he will always lose this game (poor Bob, he always loses), so he decided to minimize the score's difference. Alice's goal is to maximize the difference in the score. Given an array of integers stones where stones[i] represents the value of the ith stone from the left, return the difference in Alice and Bob's score if they both play optimally. ", + "category": [ + "Array", + "Math", + "Dynamic Programming", + "Game Theory" + ], + "complexity": "Medium", + "successrate": 58.7, + "totalsubmissions": 44395, + "totalaccepted": 26039, + "likes": 651, + "dislikes": 124, + "hints": "The constraints are small enough for an N^2 solution. Try using dynamic programming.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "stones = [5,3,1,4,2]", + "expected_output": "6", + "explanation": "- Alice removes 2 and gets 5 + 3 + 1 + 4 = 13 points. Alice = 13, Bob = 0, stones = [5,3,1,4].\n- Bob removes 5 and gets 3 + 1 + 4 = 8 points. Alice = 13, Bob = 8, stones = [3,1,4].\n- Alice removes 3 and gets 1 + 4 = 5 points. Alice = 18, Bob = 8, stones = [1,4].\n- Bob removes 1 and gets 4 points. Alice = 18, Bob = 12, stones = [4].\n- Alice removes 4 and gets 0 points. Alice = 18, Bob = 12, stones = [].\nThe score difference is 18 - 12 = 6." + }, + { + "example_num": 2, + "expected_input": "stones = [7,90,5,1,100,10,10,2]", + "expected_output": "122", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} stones\n * @return {number}\n */\nconst stoneGameVII = function (stones) {\n let len = stones.length\n const dp = Array.from({ length: len }, () => Array(len).fill(0))\n for (let i = len - 2; i >= 0; i--) {\n let sum = stones[i]\n for (let j = i + 1; j < len; j++) {\n sum += stones[j]\n dp[i][j] = Math.max(\n sum - stones[i] - dp[i + 1][j],\n sum - stones[j] - dp[i][j - 1]\n )\n }\n }\n return dp[0][len - 1]\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720e41", + "questionid": 886, + "title": "Sum of Unique Elements", + "slug": "sum-of-unique-elements", + "description": "You are given an integer array nums. The unique elements of an array are the elements that appear exactly once in the array. Return the sum of all the unique elements of nums. ", + "category": [ + "Array", + "Hash Table", + "Counting" + ], + "complexity": "Easy", + "successrate": 75.5, + "totalsubmissions": 96539, + "totalaccepted": 72919, + "likes": 721, + "dislikes": 17, + "hints": "Use a dictionary to count the frequency of each number.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,2,3,2]", + "expected_output": "4", + "explanation": "The unique elements are [1,3], and the sum is 4." + }, + { + "example_num": 2, + "expected_input": "nums = [1,1,1,1,1]", + "expected_output": "0", + "explanation": "There are no unique elements, and the sum is 0." + }, + { + "example_num": 3, + "expected_input": "nums = [1,2,3,4,5]", + "expected_output": "15", + "explanation": "The unique elements are [1,2,3,4,5], and the sum is 15." + } + ], + "solution": "/**\n * @param {number[]} nums\n * @return {number}\n */\nconst sumOfUnique = function(nums) {\n const m = {}\n for(let e of nums) {\n if(m[e] == null) m[e] = 0\n m[e]++\n }\n let res = 0\n // console.log(m)\n Object.entries(m).forEach(e => {\n const [k, v] = e\n if(v === 1) res += +k\n })\n return res\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720e45", + "questionid": 890, + "title": "Longest Nice Substring", + "slug": "longest-nice-substring", + "description": "A string s is nice if, for every letter of the alphabet that s contains, it appears both in uppercase and lowercase. For example, \"abABB\" is nice because 'A' and 'a' appear, and 'B' and 'b' appear. However, \"abA\" is not because 'b' appears, but 'B' does not. Given a string s, return the longest substring of s that is nice. If there are multiple, return the substring of the earliest occurrence. If there are none, return an empty string. ", + "category": [ + "Hash Table", + "String", + "Bit Manipulation", + "Sliding Window" + ], + "complexity": "Easy", + "successrate": 61.9, + "totalsubmissions": 36825, + "totalaccepted": 22808, + "likes": 561, + "dislikes": 432, + "hints": "Brute force and check each substring to see if it is nice.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "YazaAay"", + "expected_output": ""aAa"\nExplanation: "aAa" is a nice string because 'A/a' is the only letter of the alphabet in s, and both 'A' and 'a' appear.\n"aAa" is the longest nice substring.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "s = "Bb"", + "expected_output": ""Bb"", + "explanation": ""Bb" is a nice string because both 'B' and 'b' appear. The whole string is a substring." + }, + { + "example_num": 3, + "expected_input": "s = "c"", + "expected_output": """", + "explanation": "There are no nice substrings." + } + ], + "solution": "/**\n * @param {string} s\n * @return {string}\n */\nconst longestNiceSubstring = function(s) {\n let res = ''\n const n = s.length\n \n const arr = Array(26).fill(null)\n for(let i = 0; i < n - 1; i++) {\n for(let j = i + 1; j < n; j++) {\n const tmp = s.slice(i, j + 1)\n if(helper(tmp)) {\n if(tmp.length > res.length) res = tmp\n }\n }\n }\n \n \n return res\n};\n\nfunction helper(s) {\n const arr = Array(26).fill(null)\n const a = 'a'.charCodeAt(0), A = 'A'.charCodeAt(0)\n for(let e of s) {\n const ecode = e.charCodeAt(0)\n if(arr[ecode - a] === 0 || arr[ecode - A] === 0) continue\n if(ecode - a < 26 && ecode - a >= 0) arr[ecode - a] = arr[ecode - a] === 1 ? 0 : -1\n if(ecode - A < 26 && ecode - A >= 0) arr[ecode - A] = arr[ecode - A] === -1 ? 0 : 1\n }\n for(let e of arr) {\n if(e === -1 || e === 1) return false\n }\n \n return true\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720e49", + "questionid": 894, + "title": "Closest Subsequence Sum", + "slug": "closest-subsequence-sum", + "description": "You are given an integer array nums and an integer goal. You want to choose a subsequence of nums such that the sum of its elements is the closest possible to goal. That is, if the sum of the subsequence's elements is sum, then you want to minimize the absolute difference abs(sum - goal). Return the minimum possible value of abs(sum - goal). Note that a subsequence of an array is an array formed by removing some elements (possibly all or none) of the original array. ", + "category": [ + "Array", + "Two Pointers", + "Dynamic Programming", + "Bit Manipulation", + "Bitmask" + ], + "complexity": "Hard", + "successrate": 36.3, + "totalsubmissions": 23471, + "totalaccepted": 8525, + "likes": 436, + "dislikes": 58, + "hints": "The naive solution is to check all possible subsequences. This works in O(2^n). Divide the array into two parts of nearly is equal size. Consider all subsets of one part and make a list of all possible subset sums and sort this list. Consider all subsets of the other part, and for each one, let its sum = x, do binary search to get the nearest possible value to goal - x in the first part.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [5,-7,3,5], goal = 6", + "expected_output": "0", + "explanation": "Choose the whole array as a subsequence, with a sum of 6.\nThis is equal to the goal, so the absolute difference is 0." + }, + { + "example_num": 2, + "expected_input": "nums = [7,-9,15,-2], goal = -5", + "expected_output": "1", + "explanation": "Choose the subsequence [7,-9,-2], with a sum of -4.\nThe absolute difference is abs(-4 - (-5)) = abs(1) = 1, which is the minimum." + }, + { + "example_num": 3, + "expected_input": "nums = [1,2,3], goal = -7", + "expected_output": "7", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} nums\n * @param {number} goal\n * @return {number}\n */\nconst minAbsDifference = function (nums, goal) {\n let min = Math.abs(goal)\n if (!nums.length) return min\n const generateSums = (a) => {\n let sums = []\n for (let i = 0; i < a.length; i++) {\n const l = sums.length\n for (let j = 0; j < l; j++) {\n sums.push(sums[j] + a[i])\n min = Math.min(min, Math.abs(sums[j] + a[i] - goal))\n if (min === 0) return\n }\n sums.push(a[i])\n min = Math.min(min, Math.abs(a[i] - goal))\n if (min === 0) return\n }\n return sums\n }\n\n const n1 = nums.slice(0, Math.ceil(nums.length / 2))\n const n2 = nums.slice(Math.ceil(nums.length / 2), nums.length)\n const sums1 = generateSums(n1)\n if (min === 0) return min\n const sums2 = generateSums(n2)\n if (min === 0) return min\n\n sums2.sort((a, b) => a - b)\n for (let i = 0; i < sums1.length; i++) {\n if (min === 0) return min\n let l = 0\n let r = sums2.length\n let sum\n while (l < r) {\n const h = Math.floor((l + r) / 2)\n sum = sums1[i] + sums2[h]\n min = Math.min(min, Math.abs(sum - goal))\n if (min === 0) return min\n if (sum - goal < 0) {\n l = h + 1\n } else {\n r = h\n }\n }\n }\n return min\n}\n\n\n// another\n\n/**\n * @param {number[]} nums\n * @param {number} goal\n * @return {number}\n */\nvar minAbsDifference = function(a, b) {\n let n = a.length, m = (n / 2) >> 0, r = n - m;\n let ans = 2e9;\n const {max, min, abs} = Math\n const va = [], vb = [];\n for(let i=0;i<1<>j&1) tmp+=a[j];\n }\n ans=min(ans,abs(tmp-b));\n va.push(tmp);\n }\n // sort(va.begin(), va.end());\n va.sort((a, b) => a - b)\n for(let i=0;i<1<>j&1) tmp+=a[j+m];\n }\n ans=min(ans,abs(tmp-b));\n let k=b-tmp;\n let pos=lower_bound(va, k);\n for(let j=pos-1;j<=pos+1;++j) {\n if(j>=0 && j 0) {\n step = Math.floor(len / 2);\n middle = first + step;\n if (less(array[middle], value, middle)) {\n first = middle;\n first += 1;\n len = len - step - 1;\n } else {\n len = step;\n }\n }\n return first;\n};\n\n" + }, + { + "_id": "66f925ddfdfb8e1665720e0e", + "questionid": 835, + "title": "Maximal Network Rank", + "slug": "maximal-network-rank", + "description": "There is an infrastructure of n cities with some number of roads connecting these cities. Each roads[i] = [ai, bi] indicates that there is a bidirectional road between cities ai and bi. The network rank of two different cities is defined as the total number of\u00a0directly connected roads to either city. If a road is directly connected to both cities, it is only counted once. The maximal network rank of the infrastructure is the maximum network rank of all pairs of different cities. Given the integer n and the array roads, return the maximal network rank of the entire infrastructure. ", + "category": [ + "Graph" + ], + "complexity": "Medium", + "successrate": 56.8, + "totalsubmissions": 66604, + "totalaccepted": 37798, + "likes": 645, + "dislikes": 123, + "hints": "Try every pair of different cities and calculate its network rank. The network rank of two vertices is almost the sum of their degrees. How can you efficiently check if there is a road connecting two different cities?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 4, roads = [[0,1],[0,3],[1,2],[1,3]]", + "expected_output": "4", + "explanation": "The network rank of cities 0 and 1 is 4 as there are 4 roads that are connected to either 0 or 1. The road between 0 and 1 is only counted once." + }, + { + "example_num": 2, + "expected_input": "n = 5, roads = [[0,1],[0,3],[1,2],[1,3],[2,3],[2,4]]", + "expected_output": "5", + "explanation": "There are 5 roads that are connected to cities 1 or 2." + }, + { + "example_num": 3, + "expected_input": "n = 8, roads = [[0,1],[1,2],[2,3],[2,4],[5,6],[5,7]]", + "expected_output": "5", + "explanation": "The network rank of 2 and 5 is 5. Notice that all the cities do not have to be connected." + } + ], + "solution": "/**\n * @param {number} n\n * @param {number[][]} roads\n * @return {number}\n */\nconst maximalNetworkRank = function (n, roads) {\n const edgeCount = new Array(n).fill(0);\n const m = roads.length;\n const map = new Map();\n for (let i = 0; i < m; i++) {\n edgeCount[roads[i][0]]++;\n edgeCount[roads[i][1]]++;\n if (!map.has(roads[i][0])) {\n map.set(roads[i][0], new Set());\n }\n if (!map.has(roads[i][1])) {\n map.set(roads[i][1], new Set());\n }\n const A = map.get(roads[i][0]);\n A.add(roads[i][1]);\n const B = map.get(roads[i][1]);\n B.add(roads[i][0]);\n }\n\n let maxRank = 0;\n for (let i = 0; i < m; i++) {\n let rank = edgeCount[roads[i][0]] + edgeCount[roads[i][1]] - 1;\n if (rank > maxRank) {\n maxRank = rank;\n }\n }\n const keys = [];\n for (let k of map.keys()) keys.push(k);\n // console.log(keys, map)\n for (let i = 0, len = keys.length; i < m - 1; i++) {\n const tmp = map.get(keys[i]);\n for (let j = i + 1; j < m; j++) {\n // console.log(tmp, i, j, tmp.has(keys[j]))\n if (tmp && !tmp.has(keys[j])) {\n let rank = edgeCount[keys[i]] + edgeCount[keys[j]];\n if (rank > maxRank) {\n maxRank = rank;\n }\n }\n }\n }\n \n\n return maxRank;\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720e1b", + "questionid": 848, + "title": "Furthest Building You Can Reach", + "slug": "furthest-building-you-can-reach", + "description": "You are given an integer array heights representing the heights of buildings, some bricks, and some ladders. You start your journey from building 0 and move to the next building by possibly using bricks or ladders. While moving from building i to building i+1 (0-indexed), Return the furthest building index (0-indexed) you can reach if you use the given ladders and bricks optimally. ", + "category": [ + "Array", + "Greedy", + "Heap (Priority Queue)" + ], + "complexity": "Medium", + "successrate": 45, + "totalsubmissions": 104786, + "totalaccepted": 47206, + "likes": 1634, + "dislikes": 49, + "hints": "Assume the problem is to check whether you can reach the last building or not. You'll have to do a set of jumps, and choose for each one whether to do it using a ladder or bricks. It's always optimal to use ladders in the largest jumps. Iterate on the buildings, maintaining the largest r jumps and the sum of the remaining ones so far, and stop whenever this sum exceeds b.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "heights = [4,2,7,6,9,14,12], bricks = 5, ladders = 1", + "expected_output": "4", + "explanation": "Starting at building 0, you can follow these steps:\n- Go to building 1 without using ladders nor bricks since 4 >= 2.\n- Go to building 2 using 5 bricks. You must use either bricks or ladders because 2 < 7.\n- Go to building 3 without using ladders nor bricks since 7 >= 6.\n- Go to building 4 using your only ladder. You must use either bricks or ladders because 6 < 9.\nIt is impossible to go beyond building 4 because you do not have any more bricks or ladders." + }, + { + "example_num": 2, + "expected_input": "heights = [4,12,2,7,3,18,20,3,19], bricks = 10, ladders = 2", + "expected_output": "7", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "heights = [14,3,19,3], bricks = 17, ladders = 0", + "expected_output": "3", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} heights\n * @param {number} bricks\n * @param {number} ladders\n * @return {number}\n */\nconst furthestBuilding = function(heights, bricks, ladders) {\n const pq = new PriorityQueue((a, b) => a < b)\n const len = heights.length\n for(let i = 0; i < len - 1; i++) {\n const diff = heights[i + 1] - heights[i]\n if(diff > 0) pq.push(diff)\n if(pq.size() > ladders) {\n bricks -= pq.pop()\n }\n if(bricks < 0) return i\n }\n return len - 1\n};\nclass PriorityQueue {\n constructor(comparator = (a, b) => a > b) {\n this.heap = []\n this.top = 0\n this.comparator = comparator\n }\n size() {\n return this.heap.length\n }\n isEmpty() {\n return this.size() === 0\n }\n peek() {\n return this.heap[this.top]\n }\n push(...values) {\n values.forEach((value) => {\n this.heap.push(value)\n this.siftUp()\n })\n return this.size()\n }\n pop() {\n const poppedValue = this.peek()\n const bottom = this.size() - 1\n if (bottom > this.top) {\n this.swap(this.top, bottom)\n }\n this.heap.pop()\n this.siftDown()\n return poppedValue\n }\n replace(value) {\n const replacedValue = this.peek()\n this.heap[this.top] = value\n this.siftDown()\n return replacedValue\n }\n\n parent = (i) => ((i + 1) >>> 1) - 1\n left = (i) => (i << 1) + 1\n right = (i) => (i + 1) << 1\n greater = (i, j) => this.comparator(this.heap[i], this.heap[j])\n swap = (i, j) => ([this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]])\n siftUp = () => {\n let node = this.size() - 1\n while (node > this.top && this.greater(node, this.parent(node))) {\n this.swap(node, this.parent(node))\n node = this.parent(node)\n }\n }\n siftDown = () => {\n let node = this.top\n while (\n (this.left(node) < this.size() && this.greater(this.left(node), node)) ||\n (this.right(node) < this.size() && this.greater(this.right(node), node))\n ) {\n let maxChild =\n this.right(node) < this.size() &&\n this.greater(this.right(node), this.left(node))\n ? this.right(node)\n : this.left(node)\n this.swap(node, maxChild)\n node = maxChild\n }\n }\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720e1c", + "questionid": 849, + "title": "Maximum Repeating Substring", + "slug": "maximum-repeating-substring", + "description": "For a string sequence, a string word is k-repeating if word concatenated k times is a substring of sequence. The word's maximum k-repeating value is the highest value k where word is k-repeating in sequence. If word is not a substring of sequence, word's maximum k-repeating value is 0. Given strings sequence and word, return the maximum k-repeating value of word in sequence. ", + "category": [ + "String", + "String Matching" + ], + "complexity": "Easy", + "successrate": 39.6, + "totalsubmissions": 59819, + "totalaccepted": 23687, + "likes": 368, + "dislikes": 125, + "hints": "The constraints are low enough for a brute force approach. Try every k value from 0 upwards until word is no longer k-repeating.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "sequence = "ababc", word = "ab"", + "expected_output": "2\nExplanation: "abab" is a substring in "ababc".", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "sequence = "ababc", word = "ba"", + "expected_output": "1\nExplanation: "ba" is a substring in "ababc". "baba" is not a substring in "ababc".", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "sequence = "ababc", word = "ac"", + "expected_output": "0\nExplanation: "ac" is not a substring in "ababc".", + "explanation": "" + } + ], + "solution": "/**\n * @param {string} sequence\n * @param {string} word\n * @return {number}\n */\nconst maxRepeating = function(sequence, word) {\n let count = 1;\n while (sequence.includes(word.repeat(count))) count += 1\n return count - 1;\n};\n\n// another\n\n/**\n * @param {string} sequence\n * @param {string} word\n * @return {number}\n */\nconst maxRepeating = function(sequence, word) {\n const s = sequence.length, w = word.length\n const max_repeat = (s / w) >> 0\n const failure = Array(w * max_repeat + 1).fill(0)\n const repeat_words = word.repeat(max_repeat) + '$'\n let result = 0, j = 0\n \n for(let i = 1, hi = repeat_words.length; i < hi; i++) {\n while(j > 0 && repeat_words[j] !== repeat_words[i]) j = failure[j - 1]\n j += (repeat_words[j] === repeat_words[i] ? 1 : 0)\n failure[i] = j\n }\n\n j = 0\n for(let i = 0, len = sequence.length; i < len; i++) {\n while(j > 0 && repeat_words[j] !== sequence[i]) j = failure[j - 1]\n j += (repeat_words[j] === sequence[i] ? 1 : 0)\n result = Math.max(result, (j / w) >> 0)\n }\n return result\n};\n\n" + }, + { + "_id": "66f925ddfdfb8e1665720e23", + "questionid": 856, + "title": "Sum of Absolute Differences in a Sorted Array", + "slug": "sum-of-absolute-differences-in-a-sorted-array", + "description": "You are given an integer array nums sorted in non-decreasing order. Build and return an integer array result with the same length as nums such that result[i] is equal to the summation of absolute differences between nums[i] and all the other elements in the array. In other words, result[i] is equal to sum(|nums[i]-nums[j]|) where 0 <= j < nums.length and j != i (0-indexed). ", + "category": [ + "Array", + "Math", + "Prefix Sum" + ], + "complexity": "Medium", + "successrate": 65.6, + "totalsubmissions": 29678, + "totalaccepted": 19461, + "likes": 673, + "dislikes": 22, + "hints": "Absolute difference is the same as max(a, b) - min(a, b). How can you use this fact with the fact that the array is sorted? For nums[i], the answer is (nums[i] - nums[0]) + (nums[i] - nums[1]) + ... + (nums[i] - nums[i-1]) + (nums[i+1] - nums[i]) + (nums[i+2] - nums[i]) + ... + (nums[n-1] - nums[i]). It can be simplified to (nums[i] * i - (nums[0] + nums[1] + ... + nums[i-1])) + ((nums[i+1] + nums[i+2] + ... + nums[n-1]) - nums[i] * (n-i-1)). One can build prefix and suffix sums to compute this quickly.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [2,3,5]", + "expected_output": "[4,3,5]", + "explanation": "Assuming the arrays are 0-indexed, then\nresult[0] = |2-2| + |2-3| + |2-5| = 0 + 1 + 3 = 4,\nresult[1] = |3-2| + |3-3| + |3-5| = 1 + 0 + 2 = 3,\nresult[2] = |5-2| + |5-3| + |5-5| = 3 + 2 + 0 = 5." + }, + { + "example_num": 2, + "expected_input": "nums = [1,4,6,8,10]", + "expected_output": "[24,15,13,15,21]", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} nums\n * @return {number[]}\n */\nconst getSumAbsoluteDifferences = function(nums) {\n const n = nums.length, { abs } = Math\n const res = []\n let e0 = 0\n for(let i = 1; i < n; i++) {\n e0 += abs(nums[i] - nums[0])\n }\n res[0] = e0\n for(let i = 1; i < n; i++) {\n const pre = res[i - 1], diff = nums[i] - nums[i - 1]\n let cur = pre + diff * (i - 1) - diff * (n - 1 - i)\n res.push(cur)\n }\n \n return res\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720e25", + "questionid": 858, + "title": "Find the Most Competitive Subsequence", + "slug": "find-the-most-competitive-subsequence", + "description": "Given an integer array nums and a positive integer k, return the most competitive subsequence of nums of size k. An array's subsequence is a resulting sequence obtained by erasing some (possibly zero) elements from the array. We define that a subsequence a is more competitive than a subsequence b (of the same length) if in the first position where a and b differ, subsequence a has a number less than the corresponding number in b. For example, [1,3,4] is more competitive than [1,3,5] because the first position they differ is at the final number, and 4 is less than 5. ", + "category": [ + "Array", + "Stack", + "Greedy", + "Monotonic Stack" + ], + "complexity": "Medium", + "successrate": 48.4, + "totalsubmissions": 86550, + "totalaccepted": 41852, + "likes": 1258, + "dislikes": 59, + "hints": "In lexicographical order, the elements to the left have higher priority than those that come after. Can you think of a strategy that incrementally builds the answer from left to right?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [3,5,2,6], k = 2", + "expected_output": "[2,6]", + "explanation": "Among the set of every possible subsequence: {[3,5], [3,2], [3,6], [5,2], [5,6], [2,6]}, [2,6] is the most competitive." + }, + { + "example_num": 2, + "expected_input": "nums = [2,4,3,3,5,4,9,6], k = 4", + "expected_output": "[2,3,3,4]", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} nums\n * @param {number} k\n * @return {number[]}\n */\nconst mostCompetitive = function (nums, k) {\n const res = new Array(k).fill(0)\n let start = -1\n let idx = 0\n for (let i = k; i > 0; i--) {\n let min = Number.MAX_VALUE\n for (let j = start + 1; j < nums.length - i + 1; j++) {\n if (nums[j] < min) {\n start = j\n min = nums[j]\n }\n }\n res[idx++] = min\n }\n return res\n}\n\n// another\n\n/**\n * @param {number[]} nums\n * @param {number} k\n * @return {number[]}\n */\nconst mostCompetitive = function (nums, k) {\n const stack = [],\n n = nums.length\n let i = 0\n while (i < n) {\n while (\n stack.length &&\n stack[stack.length - 1] > nums[i] &&\n n - i + stack.length > k\n )\n stack.pop()\n if (stack.length < k) stack.push(nums[i])\n i++\n }\n return stack\n}\n\n// another\n\n/**\n * @param {number[]} nums\n * @param {number} k\n * @return {number[]}\n */\nconst mostCompetitive = function (nums, k) {\n const n = nums.length, stack = []\n for(let i = 0; i < n; i++) {\n const ch = nums[i]\n while(\n stack.length &&\n ch < stack[stack.length - 1] &&\n stack.length + (n - 1 - i) >= k\n ) {\n stack.pop()\n }\n if(stack.length < k) stack.push(ch)\n }\n return stack\n}\n\n" + }, + { + "_id": "66f925ddfdfb8e1665720e27", + "questionid": 860, + "title": "Goal Parser Interpretation", + "slug": "goal-parser-interpretation", + "description": "You own a Goal Parser that can interpret a string command. The command consists of an alphabet of \"G\", \"()\" and/or \"(al)\" in some order. The Goal Parser will interpret \"G\" as the string \"G\", \"()\" as the string \"o\", and \"(al)\" as the string \"al\". The interpreted strings are then concatenated in the original order. Given the string command, return the Goal Parser's interpretation of command. ", + "category": [ + "String" + ], + "complexity": "Easy", + "successrate": 85.7, + "totalsubmissions": 120299, + "totalaccepted": 103140, + "likes": 676, + "dislikes": 61, + "hints": "You need to check at most 2 characters to determine which character comes next.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "command = "G()(al)"", + "expected_output": ""Goal"", + "explanation": " The Goal Parser interprets the command as follows:\nG -> G\n() -> o\n(al) -> al\nThe final concatenated result is "Goal"." + }, + { + "example_num": 2, + "expected_input": "command = "G()()()()(al)"", + "expected_output": ""Gooooal"", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "command = "(al)G(al)()()G"", + "expected_output": ""alGalooG"", + "explanation": "" + } + ], + "solution": "/**\n * @param {string} command\n * @return {string}\n */\nconst interpret = function(c) {\n const stack = [c[0]]\n const n = c.length\n let i = 1\n while(i < n) {\n if(c[i] === ')') {\n if(stack[stack.length - 1] === '(') {\n stack.pop()\n stack.push('o')\n i++\n } else {\n let res = ''\n while(stack[stack.length - 1] !== '(') {\n const tmp = stack.pop()\n res = tmp + res\n }\n stack.pop()\n stack.push(res)\n i++\n }\n } else {\n stack.push(c[i])\n i++\n }\n }\n return stack.join('')\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720e2a", + "questionid": 863, + "title": "Concatenation of Consecutive Binary Numbers", + "slug": "concatenation-of-consecutive-binary-numbers", + "description": "Given an integer n, return the decimal value of the binary string formed by concatenating the binary representations of 1 to n in order, modulo 109 + 7. ", + "category": [ + "Math", + "Bit Manipulation", + "Simulation" + ], + "complexity": "Medium", + "successrate": 52.6, + "totalsubmissions": 64004, + "totalaccepted": 33637, + "likes": 338, + "dislikes": 206, + "hints": "Express the nth number value in a recursion formula and think about how we can do a fast evaluation.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 1", + "expected_output": "1\nExplanation: "1" in binary corresponds to the decimal value 1.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "n = 3", + "expected_output": "27\nExplanation: In binary, 1, 2, and 3 corresponds to "1", "10", and "11".\nAfter concatenating them, we have "11011", which corresponds to the decimal value 27.", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "n = 12", + "expected_output": "505379714\nExplanation: The concatenation results in "1101110010111011110001001101010111100".\nThe decimal value of that is 118505380540.\nAfter modulo 109 + 7, the result is 505379714.", + "explanation": "" + } + ], + "solution": "/**\n * @param {number} n\n * @return {number}\n */\nconst concatenatedBinary = function(n) {\n let res = ''\n const mod = 10 ** 9 + 7\n for(let i = 1; i <= n; i++) {\n res += dec2bin(i)\n res = dec2bin(parseInt(res, 2) % mod)\n }\n return parseInt(res, 2) % mod\n};\nfunction dec2bin(dec){\n return (dec >>> 0).toString(2);\n}\n\n// another\n\n/**\n * @param {number} n\n * @return {number}\n */\nconst concatenatedBinary = function (n) {\n const mod = BigInt(1e9 + 7)\n let res = 0n\n for (let i = 1n, shift = 0n; i <= n; i++) {\n let singleBit = (i & (i - 1n)) == 0\n if (singleBit) shift++\n res <<= shift\n res += i\n res %= mod\n }\n return res\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720e30", + "questionid": 869, + "title": "Checking Existence of Edge Length Limited Paths", + "slug": "checking-existence-of-edge-length-limited-paths", + "description": "An undirected graph of n nodes is defined by edgeList, where edgeList[i] = [ui, vi, disi] denotes an edge between nodes ui and vi with distance disi. Note that there may be multiple edges between two nodes. Given an array queries, where queries[j] = [pj, qj, limitj], your task is to determine for each queries[j] whether there is a path between pj and qj such that each edge on the path has a distance strictly less than limitj . Return a boolean array answer, where answer.length == queries.length and the jth value of answer is true if there is a path for queries[j] is true, and false otherwise. ", + "category": [ + "Array", + "Union Find", + "Graph", + "Sorting" + ], + "complexity": "Hard", + "successrate": 48.7, + "totalsubmissions": 15985, + "totalaccepted": 7788, + "likes": 444, + "dislikes": 9, + "hints": "All the queries are given in advance. Is there a way you can reorder the queries to avoid repeated computations?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 3, edgeList = [[0,1,2],[1,2,4],[2,0,8],[1,0,16]], queries = [[0,1,2],[0,2,5]]", + "expected_output": "[false,true]", + "explanation": "The above figure shows the given graph. Note that there are two overlapping edges between 0 and 1 with distances 2 and 16.\nFor the first query, between 0 and 1 there is no path where each distance is less than 2, thus we return false for this query.\nFor the second query, there is a path (0 -> 1 -> 2) of two edges with distances less than 5, thus we return true for this query." + }, + { + "example_num": 2, + "expected_input": "n = 5, edgeList = [[0,1,10],[1,2,5],[2,3,9],[3,4,13]], queries = [[0,4,14],[1,4,13]]", + "expected_output": "[true,false]", + "explanation": "The above figure shows the given graph." + } + ], + "solution": "/**\n * @param {number} n\n * @param {number[][]} edgeList\n * @param {number[][]} queries\n * @return {boolean[]}\n */\nconst distanceLimitedPathsExist = function (n, edgeList, queries) {\n edgeList.sort((a, b) => a[2] - b[2])\n const m = queries.length\n const res = Array(m).fill(false)\n const order = Array(m).fill(0)\n for (let i = 0; i < m; ++i) order[i] = i\n order.sort((i, j) => queries[i][2] - queries[j][2])\n const uf = new UF(n)\n let idx = 0\n for (let i of order) {\n const limit = queries[i][2]\n while (idx < edgeList.length && edgeList[idx][2] < limit) {\n const [u, v] = edgeList[idx]\n uf.union(u, v)\n idx++\n }\n const [u0, v0] = queries[i]\n if (uf.find(u0) === uf.find(v0)) res[i] = true\n }\n return res\n}\n\nclass UF {\n constructor(n) {\n this.root = Array(n)\n .fill(null)\n .map((_, i) => i)\n }\n find(x) {\n if (this.root[x] !== x) {\n this.root[x] = this.find(this.root[x])\n }\n return this.root[x]\n }\n union(x, y) {\n const xr = this.find(x)\n const yr = this.find(y)\n this.root[yr] = xr\n }\n}\n\n\n// another\n\n/**\n * @param {number} n\n * @param {number[][]} edgeList\n * @param {number[][]} queries\n * @return {boolean[]}\n */\nconst distanceLimitedPathsExist = function (n, edgeList, queries) {\n edgeList.sort((a, b) => a[2] - b[2])\n const m = queries.length\n const ans = Array(m).fill(false)\n const order = Array(m).fill(0)\n for (let i = 0; i < m; ++i) order[i] = i\n order.sort((i, j) => queries[i][2] - queries[j][2])\n const uf = new UnionFind(n)\n let idx = 0\n for (let i of order) {\n const limit = queries[i][2]\n while (idx < edgeList.length && edgeList[idx][2] < limit) {\n const [u, v] = edgeList[idx]\n uf.union(u, v)\n idx++\n }\n const [u0, v0] = queries[i]\n if (uf.find(u0) === uf.find(v0)) ans[i] = true\n }\n return ans\n}\nclass UnionFind {\n constructor(n) {\n this.parents = Array(n)\n .fill(0)\n .map((e, i) => i)\n this.ranks = Array(n).fill(0)\n }\n root(x) {\n while (x !== this.parents[x]) {\n this.parents[x] = this.parents[this.parents[x]]\n x = this.parents[x]\n }\n return x\n }\n find(x) {\n return this.root(x)\n }\n check(x, y) {\n return this.root(x) === this.root(y)\n }\n union(x, y) {\n const [rx, ry] = [this.find(x), this.find(y)]\n if (this.ranks[rx] >= this.ranks[ry]) {\n this.parents[ry] = rx\n this.ranks[rx] += this.ranks[ry]\n } else if (this.ranks[ry] > this.ranks[rx]) {\n this.parents[rx] = ry\n this.ranks[ry] += this.ranks[rx]\n }\n }\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720e32", + "questionid": 871, + "title": "Maximum Score From Removing Substrings", + "slug": "maximum-score-from-removing-substrings", + "description": "You are given a string s and two integers x and y. You can perform two types of operations any number of times. Return the maximum points you can gain after applying the above operations on s. ", + "category": [ + "String", + "Stack", + "Greedy" + ], + "complexity": "Medium", + "successrate": 44.9, + "totalsubmissions": 20889, + "totalaccepted": 9371, + "likes": 394, + "dislikes": 18, + "hints": "Note that it is always more optimal to take one type of substring before another You can use a stack to handle erasures", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "cdbcbbaaabab", x = 4, y = 5", + "expected_output": "19", + "explanation": "- Remove the "ba" underlined in "cdbcbbaaabab". Now, s = "cdbcbbaaab" and 5 points are added to the score.\n- Remove the "ab" underlined in "cdbcbbaaab". Now, s = "cdbcbbaa" and 4 points are added to the score.\n- Remove the "ba" underlined in "cdbcbbaa". Now, s = "cdbcba" and 5 points are added to the score.\n- Remove the "ba" underlined in "cdbcba". Now, s = "cdbc" and 5 points are added to the score.\nTotal score = 5 + 4 + 5 + 5 = 19." + }, + { + "example_num": 2, + "expected_input": "s = "aabbaaxybbaabb", x = 5, y = 4", + "expected_output": "20", + "explanation": "" + } + ], + "solution": "/**\n * @param {string} s\n * @param {number} x\n * @param {number} y\n * @return {number}\n */\nconst maximumGain = function (s, x, y) {\n let sb = s.split('')\n if (x > y) {\n return remove(sb, 'ab', x) + remove(sb, 'ba', y)\n }\n return remove(sb, 'ba', y) + remove(sb, 'ab', x)\n function remove(sb, pattern, point) {\n let i = 0,\n res = 0\n for (let j = 0; j < sb.length; j++) {\n sb[i++] = sb[j]\n if (\n i > 1 &&\n sb[i - 2] == pattern.charAt(0) &&\n sb[i - 1] == pattern.charAt(1)\n ) {\n i -= 2\n res += point\n }\n }\n sb.splice(i)\n return res\n }\n}\n\n// another\n\n/**\n * @param {string} s\n * @param {number} x\n * @param {number} y\n * @return {number}\n */\nconst maximumGain = function (s, x, y) {\n return Math.max(go(s, x, y, 'a', 'b'), go(s, y, x, 'b', 'a'))\n}\n\nfunction go(s, x, y, a, b) {\n const n = s.length\n const st = new Array(n)\n let sc = 0\n let p = 0\n for (let c of s) {\n if (p - 1 >= 0 && st[p - 1] === a && c === b) {\n sc += x\n p--\n } else {\n st[p++] = c\n }\n }\n const st2 = new Array(p)\n let q = 0\n for (let u = 0; u < p; u++) {\n let c = st[u]\n if (q - 1 >= 0 && st2[q - 1] === b && c === a) {\n sc += y\n q--\n } else {\n st2[q++] = c\n }\n }\n return sc\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720e33", + "questionid": 872, + "title": "Determine if String Halves Are Alike", + "slug": "determine-if-string-halves-are-alike", + "description": "You are given a string s of even length. Split this string into two halves of equal lengths, and let a be the first half and b be the second half. Two strings are alike if they have the same number of vowels ('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'). Notice that s contains uppercase and lowercase letters. Return true if a and b are alike. Otherwise, return false. ", + "category": [ + "String", + "Counting" + ], + "complexity": "Easy", + "successrate": 78.1, + "totalsubmissions": 106734, + "totalaccepted": 83321, + "likes": 509, + "dislikes": 35, + "hints": "Create a function that checks if a character is a vowel, either uppercase or lowercase.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "book"", + "expected_output": "true", + "explanation": "a = "bo" and b = "ok". a has 1 vowel and b has 1 vowel. Therefore, they are alike." + }, + { + "example_num": 2, + "expected_input": "s = "textbook"", + "expected_output": "false", + "explanation": "a = "text" and b = "book". a has 1 vowel whereas b has 2. Therefore, they are not alike.\nNotice that the vowel o is counted twice." + } + ], + "solution": "/**\n * @param {string} s\n * @return {boolean}\n */\nconst halvesAreAlike = function(s) {\n const set = new Set(['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'])\n const n = s.length\n const mid = n / 2\n const first = s.slice(0, mid), second = s.slice(mid)\n return chk(first, set) === chk(second, set)\n};\n\nfunction chk(str, set) {\n let res = 0\n for(let i = 0, len = str.length; i < len; i++) {\n if(set.has(str[i])) res++\n }\n return res\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720e35", + "questionid": 874, + "title": "Find Minimum Time to Finish All Jobs", + "slug": "find-minimum-time-to-finish-all-jobs", + "description": "You are given an integer array jobs, where jobs[i] is the amount of time it takes to complete the ith job. There are k workers that you can assign jobs to. Each job should be assigned to exactly one worker. The working time of a worker is the sum of the time it takes to complete all jobs assigned to them. Your goal is to devise an optimal assignment such that the maximum working time of any worker is minimized. Return the minimum possible maximum working time of any assignment. ", + "category": [ + "Array", + "Dynamic Programming", + "Backtracking", + "Bit Manipulation", + "Bitmask" + ], + "complexity": "Hard", + "successrate": 42.9, + "totalsubmissions": 32104, + "totalaccepted": 13776, + "likes": 491, + "dislikes": 14, + "hints": "We can select a subset of tasks and assign it to a worker then solve the subproblem on the remaining tasks", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "jobs = [3,2,3], k = 3", + "expected_output": "3", + "explanation": "By assigning each person one job, the maximum time is 3." + }, + { + "example_num": 2, + "expected_input": "jobs = [1,2,4,7,8], k = 2", + "expected_output": "11", + "explanation": "Assign the jobs the following way:\nWorker 1: 1, 2, 8 (working time = 1 + 2 + 8 = 11)\nWorker 2: 4, 7 (working time = 4 + 7 = 11)\nThe maximum working time is 11." + } + ], + "solution": "/**\n * @param {number[]} jobs\n * @param {number} k\n * @return {number}\n */\nconst minimumTimeRequired = function(jobs, k) {\n const n = jobs.length\n const limit = 1 << n\n const sum = Array(limit).fill(0)\n const { min, max } = Math\n \n for(let mask = 0; mask < limit; mask++) {\n for(let i = 0; i < n; i++) {\n if((mask & (1 << i))) sum[mask] += jobs[i]\n }\n }\n \n const dp = Array.from({ length: k + 1 }, () => Array(limit).fill(0))\n for(let i = 0; i < limit; i++) dp[1][i] = sum[i]\n \n for(let i = 2; i <= k; i++) {\n for(let mask = 0; mask < limit; mask++) {\n dp[i][mask] = dp[i - 1][mask]\n for(let sub = mask; sub; sub = (sub - 1) & mask) {\n dp[i][mask] = min(dp[i][mask], max(dp[i - 1][mask - sub], sum[sub]))\n }\n }\n }\n \n return dp[k][limit - 1]\n};\n\n// another\n\n/**\n * @param {number[]} jobs\n * @param {number} k\n * @return {number}\n */\nconst minimumTimeRequired = function(jobs, k) {\n const workers = Array(k).fill(0)\n let res = Infinity\n const n = jobs.length\n\n dfs(0)\n \n return res\n\n function dfs(idx) {\n if(idx === n) {\n res = Math.min(res, Math.max(...workers))\n return\n }\n const e = jobs[idx]\n for(let i = 0; i < k; i++) {\n if(workers[i] + e >= res) continue\n workers[i] += e\n dfs(idx + 1)\n workers[i] -= e\n if(workers[i] === 0) break\n }\n }\n};\n\n// another\n\n/**\n * @param {number[]} jobs\n * @param {number} k\n * @return {number}\n */\nconst minimumTimeRequired = function (jobs, k) {\n if (jobs.length <= k) {\n return Math.max(...jobs)\n }\n\n // create a store to hold the number of hours each worker worked\n const workers = new Array(k).fill(0)\n\n let minLongestWorkingTime = Infinity\n const dfs = (i) => {\n if (i === jobs.length) {\n // if we assigned all the jobs, see if we have a better result\n minLongestWorkingTime = Math.min(\n minLongestWorkingTime,\n Math.max(...workers)\n )\n return\n }\n const lengthOfWork = jobs[i]\n\n for (let worker = 0; worker < k; worker++) {\n workers[worker] += lengthOfWork\n\n // if this combination is has a chance of decreasing our\n // answer, try it, otherwise skip it to save on time.\n if (workers[worker] <= minLongestWorkingTime) {\n dfs(i + 1)\n }\n workers[worker] -= lengthOfWork\n\n // We want to minimize the width of the tree\n // so if the worker has gotten their first job\n // don't try any workers after this worker.\n // All other workers after this worker will be 0 as well\n // so the combination is exactly the same.\n if (workers[worker] === 0) break\n }\n }\n\n dfs(0)\n return minLongestWorkingTime\n}\n\n// another\n\n/**\n * @param {number[]} jobs\n * @param {number} k\n * @return {number}\n */\nconst minimumTimeRequired = function(jobs, k) {\n return solution(jobs, k)\n};\n\nfunction solution(jobs, k) {\n const n = jobs.length\n let res = Infinity, arr = Array(k).fill(0)\n\n let start = 0\n bt(0)\n return res\n\n function bt(idx) {\n start++\n if(idx === n) {\n res = Math.min(res, Math.max(...arr))\n return\n }\n const visited = new Set()\n for(let j = start; j < start + k; j++) {\n const i = j % k\n if(visited.has(arr[i])) continue\n if(arr[i] + jobs[idx] > res) continue\n visited.add(arr[i])\n arr[i] += jobs[idx]\n bt(idx + 1)\n arr[i] -= jobs[idx]\n }\n } \n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720e39", + "questionid": 878, + "title": "Find the Highest Altitude", + "slug": "find-the-highest-altitude", + "description": "There is a biker going on a road trip. The road trip consists of n + 1 points at different altitudes. The biker starts his trip on point 0 with altitude equal 0. You are given an integer array gain of length n where gain[i] is the net gain in altitude between points i and i + 1 for all (0 <= i < n). Return the highest altitude of a point. ", + "category": [ + "Array", + "Prefix Sum" + ], + "complexity": "Easy", + "successrate": 78.9, + "totalsubmissions": 88185, + "totalaccepted": 69592, + "likes": 762, + "dislikes": 78, + "hints": "Let's note that the altitude of an element is the sum of gains of all the elements behind it Getting the altitudes can be done by getting the prefix sum array of the given array", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "gain = [-5,1,5,0,-7]", + "expected_output": "1", + "explanation": "The altitudes are [0,-5,-4,1,1,-6]. The highest is 1." + }, + { + "example_num": 2, + "expected_input": "gain = [-4,-3,-2,-1,4,3,2]", + "expected_output": "0", + "explanation": "The altitudes are [0,-4,-7,-9,-10,-6,-3,-1]. The highest is 0." + } + ], + "solution": "/**\n * @param {number[]} gain\n * @return {number}\n */\nconst largestAltitude = function(gain) {\n const h = [0]\n for(let e of gain) {\n h.push(h[h.length - 1] + e)\n }\n let max = 0\n for(let e of h) {\n max = Math.max(max, e)\n }\n return max\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720e3c", + "questionid": 881, + "title": "Decode XORed Array", + "slug": "decode-xored-array", + "description": "There is a hidden integer array arr that consists of n non-negative integers. It was encoded into another integer array encoded of length n - 1, such that encoded[i] = arr[i] XOR arr[i + 1]. For example, if arr = [1,0,2,1], then encoded = [1,2,3]. You are given the encoded array. You are also given an integer first, that is the first element of arr, i.e. arr[0]. Return the original array arr. It can be proved that the answer exists and is unique. ", + "category": [ + "Array", + "Bit Manipulation" + ], + "complexity": "Easy", + "successrate": 85.9, + "totalsubmissions": 79325, + "totalaccepted": 68161, + "likes": 723, + "dislikes": 134, + "hints": "Since that encoded[i] = arr[i] XOR arr[i+1], then arr[i+1] = encoded[i] XOR arr[i]. Iterate on i from beginning to end, and set arr[i+1] = encoded[i] XOR arr[i].", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "encoded = [1,2,3], first = 1", + "expected_output": "[1,0,2,1]", + "explanation": "If arr = [1,0,2,1], then first = 1 and encoded = [1 XOR 0, 0 XOR 2, 2 XOR 1] = [1,2,3]" + }, + { + "example_num": 2, + "expected_input": "encoded = [6,2,7,3], first = 4", + "expected_output": "[4,2,0,7,4]", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} encoded\n * @param {number} first\n * @return {number[]}\n */\nconst decode = function(encoded, first) {\n const res = [first]\n \n for(let i = 0, len = encoded.length; i < len; i++) {\n res[i + 1] = res[i] ^ encoded[i]\n }\n \n return res\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720e40", + "questionid": 885, + "title": "Largest Submatrix With Rearrangements", + "slug": "largest-submatrix-with-rearrangements", + "description": "You are given a binary matrix matrix of size m x n, and you are allowed to rearrange the columns of the matrix in any order. Return the area of the largest submatrix within matrix where every element of the submatrix is 1 after reordering the columns optimally. ", + "category": [ + "Array", + "Greedy", + "Sorting", + "Matrix" + ], + "complexity": "Medium", + "successrate": 60.4, + "totalsubmissions": 19339, + "totalaccepted": 11682, + "likes": 641, + "dislikes": 16, + "hints": "For each column, find the number of consecutive ones ending at each position. For each row, sort the cumulative ones in non-increasing order and \"fit\" the largest submatrix.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "matrix = [[0,0,1],[1,1,1],[1,0,1]]", + "expected_output": "4", + "explanation": "You can rearrange the columns as shown above.\nThe largest submatrix of 1s, in bold, has an area of 4." + }, + { + "example_num": 2, + "expected_input": "matrix = [[1,0,1,0,1]]", + "expected_output": "3", + "explanation": "You can rearrange the columns as shown above.\nThe largest submatrix of 1s, in bold, has an area of 3." + }, + { + "example_num": 3, + "expected_input": "matrix = [[1,1,0],[1,0,1]]", + "expected_output": "2", + "explanation": "Notice that you must rearrange entire columns, and there is no way to make a submatrix of 1s larger than an area of 2." + } + ], + "solution": "/**\n * @param {number[][]} matrix\n * @return {number}\n */\nconst largestSubmatrix = function(matrix) {\n const n = matrix.length;\n const m = matrix[0].length;\n const cols = Array(m).fill(0)\n let res = 0\n for(let i = 0; i < n; i++) {\n for(let j = 0; j < m; j++) {\n cols[j] = matrix[i][j] === 1 ? cols[j] + 1 : 0\n }\n const tmp = cols.slice()\n tmp.sort((a, b) => b - a)\n for(let j = 0; j < m; j++) {\n res = Math.max(res, (j + 1) * tmp[j])\n }\n }\n return res\n};\n\n" + }, + { + "_id": "66f925ddfdfb8e1665720e42", + "questionid": 887, + "title": "Find Kth Largest XOR Coordinate Value", + "slug": "find-kth-largest-xor-coordinate-value", + "description": "You are given a 2D matrix of size m x n, consisting of non-negative integers. You are also given an integer k. The value of coordinate (a, b) of the matrix is the XOR of all matrix[i][j] where 0 <= i <= a < m and 0 <= j <= b < n (0-indexed). Find the kth largest value (1-indexed) of all the coordinates of matrix. ", + "category": [ + "Array", + "Divide and Conquer", + "Bit Manipulation", + "Heap (Priority Queue)", + "Matrix", + "Prefix Sum", + "Quickselect" + ], + "complexity": "Medium", + "successrate": 62.1, + "totalsubmissions": 22787, + "totalaccepted": 14142, + "likes": 306, + "dislikes": 45, + "hints": "Use a 2D prefix sum to precalculate the xor-sum of the upper left submatrix.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "matrix = [[5,2],[1,6]], k = 1", + "expected_output": "7", + "explanation": "The value of coordinate (0,1) is 5 XOR 2 = 7, which is the largest value." + }, + { + "example_num": 2, + "expected_input": "matrix = [[5,2],[1,6]], k = 2", + "expected_output": "5", + "explanation": "The value of coordinate (0,0) is 5 = 5, which is the 2nd largest value." + }, + { + "example_num": 3, + "expected_input": "matrix = [[5,2],[1,6]], k = 3", + "expected_output": "4", + "explanation": "The value of coordinate (1,0) is 5 XOR 1 = 4, which is the 3rd largest value." + } + ], + "solution": "/**\n * @param {number[][]} matrix\n * @param {number} k\n * @return {number}\n */\nvar kthLargestValue = function(matrix, k) {\n let m = matrix.length;\n let n = matrix[0].length;\n const v = [], d = Array(n).fill(0);\n d[0] = matrix[0][0];\n v.push(d[0]);\n for (let i = 1; i < n; ++i) {\n d[i] = matrix[0][i] ^ d[i - 1];\n v.push(d[i]);\n }\n for (let i = 1; i < m; ++i) {\n let cur = matrix[i][0];\n d[0] ^= cur;\n v.push(d[0]);\n for (let j = 1; j < n; ++j) {\n cur ^= matrix[i][j];\n d[j] ^= cur;\n v.push(d[j]);\n }\n }\n v.sort((a, b) => b - a)\n return v[k - 1];\n};\n\n// another\n\n/**\n * @param {number[][]} matrix\n * @param {number} k\n * @return {number}\n */\nconst kthLargestValue = function(matrix, k) {\n const tmp = []\n const n = matrix.length, m = matrix[0].length\n const dp = Array.from({ length: n }, () => Array(m).fill(0))\n dp[0][0] = matrix[0][0]\n tmp.push(dp[0][0])\n for(let j = 1; j < m; j++) {\n dp[0][j] = dp[0][j - 1] ^ matrix[0][j]\n tmp.push(dp[0][j])\n }\n for(let i = 1; i < n; i++) {\n dp[i][0] = dp[i - 1][0] ^ matrix[i][0]\n tmp.push(dp[i][0])\n }\n for(let i = 1; i < n; i++) {\n for(let j = 1; j < m; j++) {\n dp[i][j] = dp[i][j - 1] ^ dp[i - 1][j] ^ matrix[i][j] ^ dp[i - 1][j - 1]\n tmp.push(dp[i][j])\n }\n }\n tmp.sort((a, b) => b - a)\n return tmp[k - 1]\n};\n\n\n// another\n\n/**\n * @param {number[][]} matrix\n * @param {number} k\n * @return {number}\n */\nconst kthLargestValue = function(matrix, k) {\n if(matrix == null || matrix[0] == null) return 0\n const m = matrix.length, n = matrix[0].length\n const res = Array.from({ length: m }, () => Array(n).fill(0))\n res[0][0] = matrix[0][0]\n for(let i = 1; i < m; i++) {\n res[i][0] = res[i - 1][0] ^ matrix[i][0]\n }\n for(let j = 1; j < n; j++) {\n res[0][j] = res[0][j - 1] ^ matrix[0][j]\n }\n \n for(let i = 1; i < m; i++) {\n for(let j = 1; j < n; j++) {\n res[i][j] = res[i][j - 1] ^ res[i - 1][j] ^ res[i - 1][j - 1] ^ matrix[i][j]\n }\n }\n \n const pq = new PriorityQueue((a, b) => a < b)\n for(let i = 0; i < m; i++) {\n for(let j = 0; j < n; j++) {\n pq.push(res[i][j])\n if(pq.size() > k) pq.pop()\n }\n }\n \n return pq.pop()\n \n};\n\nclass PriorityQueue {\n constructor(comparator = (a, b) => a > b) {\n this.heap = []\n this.top = 0\n this.comparator = comparator\n }\n size() {\n return this.heap.length\n }\n isEmpty() {\n return this.size() === 0\n }\n peek() {\n return this.heap[this.top]\n }\n push(...values) {\n values.forEach((value) => {\n this.heap.push(value)\n this.siftUp()\n })\n return this.size()\n }\n pop() {\n const poppedValue = this.peek()\n const bottom = this.size() - 1\n if (bottom > this.top) {\n this.swap(this.top, bottom)\n }\n this.heap.pop()\n this.siftDown()\n return poppedValue\n }\n replace(value) {\n const replacedValue = this.peek()\n this.heap[this.top] = value\n this.siftDown()\n return replacedValue\n }\n\n parent = (i) => ((i + 1) >>> 1) - 1\n left = (i) => (i << 1) + 1\n right = (i) => (i + 1) << 1\n greater = (i, j) => this.comparator(this.heap[i], this.heap[j])\n swap = (i, j) => ([this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]])\n siftUp = () => {\n let node = this.size() - 1\n while (node > this.top && this.greater(node, this.parent(node))) {\n this.swap(node, this.parent(node))\n node = this.parent(node)\n }\n }\n siftDown = () => {\n let node = this.top\n while (\n (this.left(node) < this.size() && this.greater(this.left(node), node)) ||\n (this.right(node) < this.size() && this.greater(this.right(node), node))\n ) {\n let maxChild =\n this.right(node) < this.size() &&\n this.greater(this.right(node), this.left(node))\n ? this.right(node)\n : this.left(node)\n this.swap(node, maxChild)\n node = maxChild\n }\n }\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720e43", + "questionid": 888, + "title": "Restore the Array From Adjacent Pairs", + "slug": "restore-the-array-from-adjacent-pairs", + "description": "There is an integer array nums that consists of n unique elements, but you have forgotten it. However, you do remember every pair of adjacent elements in nums. You are given a 2D integer array adjacentPairs of size n - 1 where each adjacentPairs[i] = [ui, vi] indicates that the elements ui and vi are adjacent in nums. It is guaranteed that every adjacent pair of elements nums[i] and nums[i+1] will exist in adjacentPairs, either as [nums[i], nums[i+1]] or [nums[i+1], nums[i]]. The pairs can appear in any order. Return the original array nums. If there are multiple solutions, return any of them. ", + "category": [ + "Array", + "Hash Table" + ], + "complexity": "Medium", + "successrate": 68.1, + "totalsubmissions": 36826, + "totalaccepted": 25075, + "likes": 624, + "dislikes": 11, + "hints": "Find the first element of nums - it will only appear once in adjacentPairs. The adjacent pairs are like edges of a graph. Perform a depth-first search from the first element.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "adjacentPairs = [[2,1],[3,4],[3,2]]", + "expected_output": "[1,2,3,4]", + "explanation": "This array has all its adjacent pairs in adjacentPairs.\nNotice that adjacentPairs[i] may not be in left-to-right order." + }, + { + "example_num": 2, + "expected_input": "adjacentPairs = [[4,-2],[1,4],[-3,1]]", + "expected_output": "[-2,4,1,-3]", + "explanation": "There can be negative numbers.\nAnother solution is [-3,1,4,-2], which would also be accepted." + }, + { + "example_num": 3, + "expected_input": "adjacentPairs = [[100000,-100000]]", + "expected_output": "[100000,-100000]", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[][]} adjacentPairs\n * @return {number[]}\n */\nconst restoreArray = function(pairs) {\n const m = {}\n for(let e of pairs) {\n const [k, v] = e\n if(m[k] == null) m[k] = new Set()\n if(m[v] == null) m[v] = new Set()\n m[k].add(v)\n m[v].add(k)\n }\n const q = [pairs[0]]\n let res = pairs[0]\n m[res[0]].delete(res[1])\n m[res[1]].delete(res[0])\n let n = pairs.length\n while(n) {\n const front = res[0], rear = res[res.length - 1]\n \n if(m[front]) {\n const newf = [...m[front].values()][0]\n if(m[front].size) res.unshift(newf)\n if(m[front]) m[front].delete(newf)\n if(m[newf]) m[newf].delete(front)\n if(m[front].size === 0) delete m[front]\n }\n \n if(m[rear]) {\n const newr = [...m[rear].values()][0]\n if(m[rear].size) res.push(newr)\n if(m[rear]) m[rear].delete(newr)\n if(m[newr]) m[newr].delete(rear)\n if(m[rear].size === 0) delete m[rear]\n }\n n--\n }\n \n return res\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720e47", + "questionid": 892, + "title": "Tree of Coprimes", + "slug": "tree-of-coprimes", + "description": "There is a tree (i.e.,\u00a0a connected, undirected graph that has no cycles) consisting of n nodes numbered from 0 to n - 1 and exactly n - 1 edges. Each node has a value associated with it, and the root of the tree is node 0. To represent this tree, you are given an integer array nums and a 2D array edges. Each nums[i] represents the ith node's value, and each edges[j] = [uj, vj] represents an edge between nodes uj and vj in the tree. Two values x and y are coprime if gcd(x, y) == 1 where gcd(x, y) is the greatest common divisor of x and y. An ancestor of a node i is any other node on the shortest path from node i to the root. A node is not considered an ancestor of itself. Return an array ans of size n, where ans[i] is the closest ancestor to node i such that nums[i] and nums[ans[i]] are coprime, or -1 if there is no such ancestor. ", + "category": [ + "Math", + "Tree", + "Depth-First Search", + "Breadth-First Search" + ], + "complexity": "Hard", + "successrate": 38.3, + "totalsubmissions": 14330, + "totalaccepted": 5486, + "likes": 224, + "dislikes": 17, + "hints": "Note that for a node, it's not optimal to consider two nodes with the same value. Note that the values are small enough for you to iterate over them instead of iterating over the parent nodes.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [2,3,3,2], edges = [[0,1],[1,2],[1,3]]", + "expected_output": "[-1,0,0,1]", + "explanation": "In the above figure, each node's value is in parentheses.\n- Node 0 has no coprime ancestors.\n- Node 1 has only one ancestor, node 0. Their values are coprime (gcd(2,3) == 1).\n- Node 2 has two ancestors, nodes 1 and 0. Node 1's value is not coprime (gcd(3,3) == 3), but node 0's\n value is (gcd(2,3) == 1), so node 0 is the closest valid ancestor.\n- Node 3 has two ancestors, nodes 1 and 0. It is coprime with node 1 (gcd(3,2) == 1), so node 1 is its\n closest valid ancestor." + }, + { + "example_num": 2, + "expected_input": "nums = [5,6,10,2,3,6,15], edges = [[0,1],[0,2],[1,3],[1,4],[2,5],[2,6]]", + "expected_output": "[-1,0,-1,0,0,0,-1]", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} nums\n * @param {number[][]} edges\n * @return {number[]}\n */\nconst getCoprimes = function (nums, edges) {\n const output = Array(nums.length).fill(null)\n const graph = new Map()\n for (let [u, v] of edges) {\n if (!graph.has(u)) graph.set(u, [])\n if (!graph.has(v)) graph.set(v, [])\n graph.get(u).push(v)\n graph.get(v).push(u)\n }\n\n function getGCD(a, b) {\n if (!b) return a\n return getGCD(b, a % b)\n }\n\n // ancestors is an array of unique ancestors from the recent to the farthest\n // indices maps the index of each ancestor\n function dfs(i, ancestors, indices) {\n for (let num of ancestors) {\n const gcd = getGCD(nums[i], num)\n if (gcd === 1) {\n output[i] = indices[num]\n break\n }\n }\n\n if (output[i] === null) output[i] = -1\n ancestors = [nums[i], ...ancestors.filter((x) => x !== nums[i])]\n indices[nums[i]] = i\n for (let next of graph.get(i)) {\n if (output[next] === null) {\n dfs(next, ancestors, [...indices])\n }\n }\n }\n\n dfs(0, [], Array(51))\n return output\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720e4b", + "questionid": 896, + "title": "Count Number of Homogenous Substrings", + "slug": "count-number-of-homogenous-substrings", + "description": "Given a string s, return the number of homogenous substrings of s. Since the answer may be too large, return it modulo 109 + 7. A string is homogenous if all the characters of the string are the same. A substring is a contiguous sequence of characters within a string. ", + "category": [ + "Math", + "String" + ], + "complexity": "Medium", + "successrate": 46.4, + "totalsubmissions": 38800, + "totalaccepted": 18005, + "likes": 376, + "dislikes": 38, + "hints": "A string of only 'a's of length k contains k choose 2 homogenous substrings. Split the string into substrings where each substring contains only one letter, and apply the formula on each substring's length.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "abbcccaa"", + "expected_output": "13", + "explanation": "The homogenous substrings are listed as below:\n"a" appears 3 times.\n"aa" appears 1 time.\n"b" appears 2 times.\n"bb" appears 1 time.\n"c" appears 3 times.\n"cc" appears 2 times.\n"ccc" appears 1 time.\n3 + 1 + 2 + 1 + 3 + 2 + 1 = 13." + }, + { + "example_num": 2, + "expected_input": "s = "xy"", + "expected_output": "2", + "explanation": "The homogenous substrings are "x" and "y"." + }, + { + "example_num": 3, + "expected_input": "s = "zzzzz"", + "expected_output": "15", + "explanation": "" + } + ], + "solution": "/**\n * @param {string} s\n * @return {number}\n */\nconst countHomogenous = function(s) {\n const mod = 10 ** 9 + 7\n let pre = s[0], res = 0, curL = 1\n for(let i = 1, len = s.length; i < len; i++) {\n if(s[i] === pre) {\n curL++\n } else {\n res = (res + helper(curL)) % mod\n pre = s[i]\n curL = 1\n }\n }\n if(curL === 1) res = (res + 1) % mod\n else res = (res + helper(curL)) % mod\n return res\n\n function helper(num) {\n return (num * (num + 1)) / 2\n }\n};\n\n" + }, + { + "_id": "66f925ddfdfb8e1665720e5a", + "questionid": 911, + "title": "Maximum Score of a Good Subarray", + "slug": "maximum-score-of-a-good-subarray", + "description": "You are given an array of integers nums (0-indexed) and an integer k. The score of a subarray (i, j) is defined as min(nums[i], nums[i+1], ..., nums[j]) * (j - i + 1). A good subarray is a subarray where i <= k <= j. Return the maximum possible score of a good subarray. ", + "category": [ + "Array", + "Two Pointers", + "Binary Search", + "Stack", + "Monotonic Stack" + ], + "complexity": "Hard", + "successrate": 51.5, + "totalsubmissions": 25890, + "totalaccepted": 13338, + "likes": 580, + "dislikes": 24, + "hints": "Try thinking about the prefix before index k and the suffix after index k as two separate arrays. Using two pointers or binary search, we can find the maximum prefix of each array where the numbers are less than or equal to a certain value", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,4,3,7,4,5], k = 3", + "expected_output": "15", + "explanation": "The optimal subarray is (1, 5) with a score of min(4,3,7,4,5) * (5-1+1) = 3 * 5 = 15." + }, + { + "example_num": 2, + "expected_input": "nums = [5,5,4,5,4,1,1,1], k = 0", + "expected_output": "20", + "explanation": "The optimal subarray is (0, 4) with a score of min(5,5,4,5,4) * (4-0+1) = 4 * 5 = 20." + } + ], + "solution": "/**\n * @param {number[]} nums\n * @param {number} k\n * @return {number}\n */\nconst maximumScore = function(nums, k) {\n const n = nums.length, {min, max} = Math\n let mini = nums[k];\n let ans = mini;\n let i = k;\n let j = k;\n\n while (i > 0 || j < n - 1) {\n if (i === 0 || (j + 1 < n && nums[i - 1] <= nums[j + 1])) {\n j++;\n mini = min(mini, nums[j]);\n } else {\n i--;\n mini = min(mini, nums[i]);\n }\n ans = max(ans, mini * (j - i + 1));\n }\n\n return ans;\n};\n\n// another\n\n/**\n * @param {number[]} nums\n * @param {number} k\n * @return {number}\n */\nconst maximumScore = function(nums, k) {\n const n = nums.length, { max, min } = Math\n let l = k, r = k, mi = nums[k]\n let res = nums[k]\n while(l > 0 || r < n - 1) {\n if(l === 0) r++\n else if(r === n - 1) l--\n else if(nums[l - 1] < nums[r + 1]) r++\n else l--\n mi = min(mi, nums[l], nums[r])\n res = max(res, mi * (r - l + 1))\n }\n \n return res\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720e4c", + "questionid": 897, + "title": "Minimum Degree of a Connected Trio in a Graph", + "slug": "minimum-degree-of-a-connected-trio-in-a-graph", + "description": "You are given an undirected graph. You are given an integer n which is the number of nodes in the graph and an array edges, where each edges[i] = [ui, vi] indicates that there is an undirected edge between ui and vi. A connected trio is a set of three nodes where there is an edge between every pair of them. The degree of a connected trio is the number of edges where one endpoint is in the trio, and the other is not. Return the minimum degree of a connected trio in the graph, or -1 if the graph has no connected trios. ", + "category": [ + "Graph" + ], + "complexity": "Hard", + "successrate": 41.4, + "totalsubmissions": 36422, + "totalaccepted": 15094, + "likes": 189, + "dislikes": 208, + "hints": "Consider a trio with nodes u, v, and w. The degree of the trio is just degree(u) + degree(v) + degree(w) - 6. The -6 comes from subtracting the edges u-v, u-w, and v-w, which are counted twice each in the vertex degree calculation. To get the trios (u,v,w), you can iterate on u, then iterate on each w,v such that w and v are neighbors of u and are neighbors of each other.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 6, edges = [[1,2],[1,3],[3,2],[4,1],[5,2],[3,6]]", + "expected_output": "3", + "explanation": "There is exactly one trio, which is [1,2,3]. The edges that form its degree are bolded in the figure above." + }, + { + "example_num": 2, + "expected_input": "n = 7, edges = [[1,3],[4,1],[4,3],[2,5],[5,6],[6,7],[7,5],[2,6]]", + "expected_output": "0", + "explanation": "There are exactly three trios:\n1) [1,4,3] with degree 0.\n2) [2,5,6] with degree 2.\n3) [5,6,7] with degree 2." + } + ], + "solution": "/**\n * @param {number} n\n * @param {number[][]} edges\n * @return {number}\n */\nconst minTrioDegree = function (n, edges) {\n let ans = 10 ** 8\n const adj = []\n const deg = {}\n\n function incDeg(u) {\n if (deg[u] == null) deg[u] = 0\n deg[u]++\n }\n for (let i = 0; i < n; i++) {\n adj.push(Array(n).fill(false))\n }\n\n for (let [u, v] of edges) {\n adj[u - 1][v - 1] = true\n adj[v - 1][u - 1] = true\n incDeg(u - 1)\n incDeg(v - 1)\n }\n for (let u1 = 0; u1 < n; u1++) {\n for (let u2 = u1 + 1; u2 < n; u2++) {\n for (let u3 = u2 + 1; u3 < n; u3++) {\n if (adj[u1][u2] && adj[u2][u3] && adj[u3][u1]) {\n let tmp = deg[u1] + deg[u2] + deg[u3] - 6\n ans = Math.min(ans, tmp)\n }\n }\n }\n }\n\n if (ans > 10000000) ans = -1\n return ans\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720e5e", + "questionid": 915, + "title": "Maximum Ascending Subarray Sum", + "slug": "maximum-ascending-subarray-sum", + "description": "Given an array of positive integers nums, return the maximum possible sum of an ascending subarray in nums. A subarray is defined as a contiguous sequence of numbers in an array. A subarray [numsl, numsl+1, ..., numsr-1, numsr] is ascending if for all i where l <= i < r, numsi < numsi+1. Note that a subarray of size 1 is ascending. ", + "category": [ + "Array" + ], + "complexity": "Easy", + "successrate": 64.4, + "totalsubmissions": 45315, + "totalaccepted": 29180, + "likes": 374, + "dislikes": 13, + "hints": "It is fast enough to check all possible subarrays The end of each ascending subarray will be the start of the next", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [10,20,30,5,10,50]", + "expected_output": "65\nExplanation: [5,10,50] is the ascending subarray with the maximum sum of 65.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "nums = [10,20,30,40,50]", + "expected_output": "150\nExplanation: [10,20,30,40,50] is the ascending subarray with the maximum sum of 150.", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "nums = [12,17,15,13,10,11,12]", + "expected_output": "33\nExplanation: [10,11,12] is the ascending subarray with the maximum sum of 33.", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} nums\n * @return {number}\n */\nconst maxAscendingSum = function(nums) {\n let res = -Infinity\n \n const n = nums.length\n let cur = 0\n for(let i = 0; i < n; i++) {\n if(i === 0) cur = nums[i]\n if(i > 0) {\n if(nums[i] > nums[i - 1]) {\n cur += nums[i]\n res = Math.max(res, cur)\n } else {\n res = Math.max(res, cur)\n cur = nums[i]\n } \n }\n }\n res = Math.max(res, cur) \n return res\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720e5f", + "questionid": 916, + "title": "Maximum Number of Consecutive Values You Can Make", + "slug": "maximum-number-of-consecutive-values-you-can-make", + "description": "You are given an integer array coins of length n which represents the n coins that you own. The value of the ith coin is coins[i]. You can make some value x if you can choose some of your n coins such that their values sum up to x. Return the maximum number of consecutive integer values that you can make with your coins starting from and including 0. Note that you may have multiple coins of the same value. ", + "category": [ + "Array", + "Greedy" + ], + "complexity": "Medium", + "successrate": 51.7, + "totalsubmissions": 18646, + "totalaccepted": 9633, + "likes": 468, + "dislikes": 36, + "hints": "If you can make the first x values and you have a value v, then you can make all the values \u2030\u00a4 v + x Sort the array of coins. You can always make the value 0 so you can start with x = 0. Process the values starting from the smallest and stop when there is a value that cannot be achieved with the current x.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "coins = [1,3]", + "expected_output": "2\nExplanation: You can make the following values:\n- 0: take []\n- 1: take [1]\nYou can make 2 consecutive integer values starting from 0.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "coins = [1,1,1,4]", + "expected_output": "8\nExplanation: You can make the following values:\n- 0: take []\n- 1: take [1]\n- 2: take [1,1]\n- 3: take [1,1,1]\n- 4: take [4]\n- 5: take [4,1]\n- 6: take [4,1,1]\n- 7: take [4,1,1,1]\nYou can make 8 consecutive integer values starting from 0.", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "coins = [1,4,10,3,1]", + "expected_output": "20", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} coins\n * @return {number}\n */\nconst getMaximumConsecutive = function(coins) {\n coins.sort((a, b) => a - b);\n let res = 1;\n for (let a of coins) {\n if (a > res) break;\n res += a;\n }\n return res; \n};\n\n// another\n\n/**\n * @param {number[]} coins\n * @return {number}\n */\nconst getMaximumConsecutive = function(coins) {\n coins.sort((a, b) => a - b)\n let sum = 1, res = 1, i = 0\n while(true) {\n const e = coins[i]\n if(i >= coins.length) break\n if(e <= sum) {\n sum += e\n i++\n } else {\n break\n }\n }\n\n return sum\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720e64", + "questionid": 921, + "title": "Number of Different Subsequences GCDs", + "slug": "number-of-different-subsequences-gcds", + "description": "You are given an array nums that consists of positive integers. The GCD of a sequence of numbers is defined as the greatest integer that divides all the numbers in the sequence evenly. A subsequence of an array is a sequence that can be formed by removing some elements (possibly none) of the array. Return the number of different GCDs among all non-empty subsequences of nums. ", + "category": [ + "Array", + "Math", + "Counting", + "Number Theory" + ], + "complexity": "Hard", + "successrate": 37, + "totalsubmissions": 15129, + "totalaccepted": 5600, + "likes": 253, + "dislikes": 33, + "hints": "Think of how to check if a number x is a gcd of a subsequence. If there is such subsequence, then all of it will be divisible by x. Moreover, if you divide each number in the subsequence by x , then the gcd of the resulting numbers will be 1. Adding a number to a subsequence cannot increase its gcd. So, if there is a valid subsequence for x , then the subsequence that contains all multiples of x is a valid one too. Iterate on all possiblex from 1 to 10^5, and check if there is a valid subsequence for x.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [6,10,3]", + "expected_output": "5", + "explanation": "The figure shows all the non-empty subsequences and their GCDs.\nThe different GCDs are 6, 10, 3, 2, and 1." + }, + { + "example_num": 2, + "expected_input": "nums = [5,15,40,5,6]", + "expected_output": "7", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} nums\n * @return {number}\n */\nconst countDifferentSubsequenceGCDs = function(nums) {\n const MAX = 2e5 + 1;\n const cnt = Array(MAX).fill(0)\n for (let x of nums) cnt[x] = true;\n let ret = 0;\n for (let x=1; x x2 -> x3 -> ... -> xk such that there is a directed edge from xi to xi+1 for every 1 <= i < k. The color value of the path is the number of nodes that are colored the most frequently occurring color along that path. Return the largest color value of any valid path in the given graph, or -1 if the graph contains a cycle. ", + "category": [ + "Hash Table", + "Dynamic Programming", + "Graph", + "Topological Sort", + "Memoization", + "Counting" + ], + "complexity": "Hard", + "successrate": 39.8, + "totalsubmissions": 27398, + "totalaccepted": 10897, + "likes": 436, + "dislikes": 16, + "hints": "Use topological sort. let dp[u][c] := the maximum count of vertices with color c of any path starting from vertex u. (by JerryJin2905)", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "colors = "abaca", edges = [[0,1],[0,2],[2,3],[3,4]]", + "expected_output": "3", + "explanation": "The path 0 -> 2 -> 3 -> 4 contains 3 nodes that are colored "a" (red in the above image)." + }, + { + "example_num": 2, + "expected_input": "colors = "a", edges = [[0,0]]", + "expected_output": "-1", + "explanation": "There is a cycle from 0 to 0." + } + ], + "solution": "/**\n * @param {string} colors\n * @param {number[][]} edges\n * @return {number}\n */\nconst largestPathValue = function (colors, edges) {\n const graph = {}\n const n = colors.length,\n a = 'a'.charCodeAt(0)\n const indegree = Array(colors.length).fill(0)\n for (let e of edges) {\n if (graph[e[0]] == null) graph[e[0]] = []\n graph[e[0]].push(e[1])\n indegree[e[1]]++\n }\n // cnt[i][j] is the maximum count of j-th color from the ancester nodes to node i.\n const cnt = Array.from({ length: n }, () => Array(26).fill(0))\n const q = []\n for (let i = 0; i < n; i++) { \n if (indegree[i] === 0) {\n q.push(i)\n cnt[i][colors.charCodeAt(i) - a] = 1\n }\n }\n let res = 0,\n seen = 0\n while (q.length) {\n const u = q[0]\n q.shift()\n const val = Math.max(...cnt[u])\n res = Math.max(res, val)\n seen++\n for (let v of (graph[u] || [])) {\n for (let i = 0; i < 26; i++) {\n cnt[v][i] = Math.max(\n cnt[v][i],\n cnt[u][i] + (i === colors.charCodeAt(v) - a)\n )\n }\n if (--indegree[v] === 0) q.push(v)\n }\n }\n return seen < colors.length ? -1 : res\n}\n\n// another\n\n/**\n * @param {string} colors\n * @param {number[][]} edges\n * @return {number}\n */\n const largestPathValue = function(colors, edges) {\n const graph = {}, n = colors.length, a = 'a'.charCodeAt(0)\n const indegree = Array(n).fill(0)\n for (const [from, to] of edges) {\n if (graph[from] == null) graph[from] = []\n graph[from].push(to)\n indegree[to]++\n }\n const cnt = Array.from({ length: n }, () => Array(26).fill(0))\n const code = idx => colors.charCodeAt(idx) - a\n const q = []\n for (let i = 0; i < n; i++) {\n if(indegree[i] === 0) {\n q.push(i)\n cnt[i][code(i)] = 1\n }\n }\n let res = 0, seen = 0\n\n while(q.length) {\n const u = q.pop()\n const val = cnt[u][code(u)]\n res = Math.max(res, val)\n seen++\n for(const next of (graph[u] || [])) {\n for(let i = 0; i < 26; i++) {\n cnt[next][i] = Math.max(cnt[next][i], cnt[u][i] + (i === code(next) ? 1 : 0))\n }\n if(--indegree[next] === 0) {\n q.push(next)\n }\n }\n }\n return seen < n ? -1 : res\n};\n\n// another\n\n\n/**\n * @param {string} colors\n * @param {number[][]} edges\n * @return {number}\n */\nconst largestPathValue = function (colors, edges) {\n const graph = {}\n const n = colors.length,\n a = 'a'.charCodeAt(0)\n const indegree = Array(colors.length).fill(0)\n for (let e of edges) {\n if (graph[e[0]] == null) graph[e[0]] = []\n graph[e[0]].push(e[1])\n indegree[e[1]]++\n }\n const cnt = Array.from({ length: n }, () => Array(26).fill(0))\n const q = []\n for (let i = 0; i < n; i++) {\n if (indegree[i] === 0) {\n q.push(i)\n cnt[i][colors.charCodeAt(i) - a] = 1\n }\n }\n let res = 0,\n seen = 0\n while (q.length) {\n const u = q[0]\n q.shift()\n const val = Math.max(...cnt[u])\n res = Math.max(res, val)\n seen++\n if (graph[u] == null) continue\n for (let v of graph[u]) {\n for (let i = 0; i < 26; i++) {\n cnt[v][i] = Math.max(\n cnt[v][i],\n cnt[u][i] + (i === colors.charCodeAt(v) - a)\n )\n }\n if (--indegree[v] === 0) q.push(v)\n }\n }\n return seen < colors.length ? -1 : res\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720e80", + "questionid": 949, + "title": "Determine Whether Matrix Can Be Obtained By Rotation", + "slug": "determine-whether-matrix-can-be-obtained-by-rotation", + "description": "Given two n x n binary matrices mat and target, return true if it is possible to make mat equal to target by rotating mat in 90-degree increments, or false otherwise. ", + "category": [ + "Array", + "Matrix" + ], + "complexity": "Easy", + "successrate": 55.2, + "totalsubmissions": 52447, + "totalaccepted": 28970, + "likes": 571, + "dislikes": 52, + "hints": "What is the maximum number of rotations you have to check? Is there a formula you can use to rotate a matrix 90 degrees?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "mat = [[0,1],[1,0]], target = [[1,0],[0,1]]", + "expected_output": "true\nExplanation: We can rotate mat 90 degrees clockwise to make mat equal target.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "mat = [[0,1],[1,1]], target = [[1,0],[0,1]]", + "expected_output": "false", + "explanation": "It is impossible to make mat equal to target by rotating mat." + }, + { + "example_num": 3, + "expected_input": "mat = [[0,0,0],[0,1,0],[1,1,1]], target = [[1,1,1],[0,1,0],[0,0,0]]", + "expected_output": "true\nExplanation: We can rotate mat 90 degrees clockwise two times to make mat equal target.", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[][]} mat\n * @param {number[][]} target\n * @return {boolean}\n */\nconst findRotation = function(mat, target) {\n if(chk(mat, target)) return true\n for(let i = 0; i < 3; i++) {\n rotate(mat)\n if(chk(mat, target)) return true\n }\n return false\n};\n\nfunction chk(m1, m2) {\n for(let i = 0; i < m1.length; i++) {\n for(let j = 0; j < m1.length; j++) {\n if(m1[i][j] !== m2[i][j]) return false\n }\n }\n return true\n}\n\nfunction rotate(matrix) {\n matrix.reverse()\n for (let i = 0; i < matrix.length; ++i) {\n for (let j = matrix[i].length - 1; j > i; j--) swap(matrix, i, j)\n }\n}\n\nfunction swap(matrix, i, j) {\n const tmp = matrix[j][i]\n matrix[j][i] = matrix[i][j]\n matrix[i][j] = tmp\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720e84", + "questionid": 953, + "title": "Redistribute Characters to Make All Strings Equal", + "slug": "redistribute-characters-to-make-all-strings-equal", + "description": "You are given an array of strings words (0-indexed). In one operation, pick two distinct indices i and j, where words[i] is a non-empty string, and move any character from words[i] to any position in words[j]. Return true if you can make every string in words equal using any number of operations, and false otherwise. ", + "category": [ + "Hash Table", + "String", + "Counting" + ], + "complexity": "Easy", + "successrate": 60.1, + "totalsubmissions": 35911, + "totalaccepted": 21568, + "likes": 256, + "dislikes": 32, + "hints": "Characters are independent\u20ac\u201donly the frequency of characters matters. It is possible to distribute characters if all characters can be divided equally among all strings.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "words = ["abc","aabc","bc"]", + "expected_output": "true", + "explanation": "Move the first 'a' in words[1] to the front of words[2],\nto make words[1] = "abc" and words[2] = "abc".\nAll the strings are now equal to "abc", so return true." + }, + { + "example_num": 2, + "expected_input": "words = ["ab","a"]", + "expected_output": "false", + "explanation": "It is impossible to make all the strings equal using the operation." + } + ], + "solution": "/**\n * @param {string[]} words\n * @return {boolean}\n */\nconst makeEqual = function(words) {\n const arr = Array(26).fill(0)\n const a = 'a'.charCodeAt(0)\n for(let w of words) {\n for(let ch of w) {\n arr[ch.charCodeAt(0) - a]++\n }\n }\n const n = words.length\n for(let i = 0; i < 26; i++) {\n if(arr[i] % n !== 0) return false\n }\n return true\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720e85", + "questionid": 954, + "title": "Maximum Number of Removable Characters", + "slug": "maximum-number-of-removable-characters", + "description": "You are given two strings s and p where p is a subsequence of s. You are also given a distinct 0-indexed integer array removable containing a subset of indices of s (s is also 0-indexed). You want to choose an integer k (0 <= k <= removable.length) such that, after removing k characters from s using the first k indices in removable, p is still a subsequence of s. More formally, you will mark the character at s[removable[i]] for each 0 <= i < k, then remove all marked characters and check if p is still a subsequence. Return the maximum k you can choose such that p is still a subsequence of s after the removals. A subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters. ", + "category": [ + "Array", + "String", + "Binary Search" + ], + "complexity": "Medium", + "successrate": 35.9, + "totalsubmissions": 34885, + "totalaccepted": 12511, + "likes": 544, + "dislikes": 63, + "hints": "First, we need to think about solving an easier problem, If we remove a set of indices from the string does P exist in S as a subsequence We can binary search the K and check by solving the above problem.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "abcacb", p = "ab", removable = [3,1,0]", + "expected_output": "2\nExplanation: After removing the characters at indices 3 and 1, "abcacb" becomes "accb".\n"ab" is a subsequence of "accb".\nIf we remove the characters at indices 3, 1, and 0, "abcacb" becomes "ccb", and "ab" is no longer a subsequence.\nHence, the maximum k is 2.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "s = "abcbddddd", p = "abcd", removable = [3,2,1,4,5,6]", + "expected_output": "1\nExplanation: After removing the character at index 3, "abcbddddd" becomes "abcddddd".\n"abcd" is a subsequence of "abcddddd".", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "s = "abcab", p = "abc", removable = [0,1,2,3,4]", + "expected_output": "0\nExplanation: If you remove the first index in the array removable, "abc" is no longer a subsequence.", + "explanation": "" + } + ], + "solution": "/**\n * @param {string} s\n * @param {string} p\n * @param {number[]} removable\n * @return {number}\n */\nconst maximumRemovals = function (s, p, removable) {\n const n = removable.length\n let l = 0,\n r = n\n while (l < r) {\n let mid = (l + r + 1) >> 1\n if (is_valid(s, p, removable, mid)) l = mid\n else r = mid - 1\n }\n return l\n}\n\nfunction is_valid(s, p, removable, cnt) {\n let len1 = s.length,\n len2 = p.length\n const check = Array(len1).fill(0)\n for (let i = 0; i < cnt; i++) check[removable[i]] = 1\n let ind1 = 0,\n ind2 = 0\n while (ind1 < len1 && ind2 < len2) {\n if (s[ind1] != p[ind2] || check[ind1]) {\n ind1++\n continue\n }\n ind1++, ind2++\n }\n return ind2 == len2\n}\n\n// another\n\n/**\n * @param {string} s\n * @param {string} p\n * @param {number[]} removable\n * @return {number}\n */\nconst maximumRemovals = function(s, p, removable) {\n let l = 0, r = removable.length\n while(l < r) {\n const mid = r - Math.floor((r - l) / 2)\n if(valid(mid)) l = mid\n else r = mid - 1\n }\n return l\n \n function valid(mid) {\n let arr = s.split('')\n for (let i = 0; i < mid; i++) arr[removable[i]] = null\n arr = arr.filter(e => e !== null)\n \n for(let i = 0, j = 0; i < arr.length && j < p.length;) {\n if(arr[i] === p[j]) i++, j++\n else i++\n if(j === p.length) return true\n }\n return false\n }\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720e86", + "questionid": 955, + "title": "The Earliest and Latest Rounds Where Players Compete", + "slug": "the-earliest-and-latest-rounds-where-players-compete", + "description": "There is a tournament where n players are participating. The players are standing in a single row and are numbered from 1 to n based on their initial standing position (player 1 is the first player in the row, player 2 is the second player in the row, etc.). The tournament consists of multiple rounds (starting from round number 1). In each round, the ith player from the front of the row competes against the ith player from the end of the row, and the winner advances to the next round. When the number of players is odd for the current round, the player in the middle automatically advances to the next round. After each round is over, the winners are lined back up in the row based on the original ordering assigned to them initially (ascending order). The players numbered firstPlayer and secondPlayer are the best in the tournament. They can win against any other player before they compete against each other. If any two other players compete against each other, either of them might win, and thus you may choose the outcome of this round. Given the integers n, firstPlayer, and secondPlayer, return an integer array containing two values, the earliest possible round number and the\u00a0latest possible round number in which these two players will compete against each other, respectively. ", + "category": [ + "Dynamic Programming", + "Memoization" + ], + "complexity": "Hard", + "successrate": 51.6, + "totalsubmissions": 7437, + "totalaccepted": 3834, + "likes": 162, + "dislikes": 15, + "hints": "Brute force using bitmasks and simulate the rounds. Calculate each state one time and save its solution.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 11, firstPlayer = 2, secondPlayer = 4", + "expected_output": "[3,4]", + "explanation": "One possible scenario which leads to the earliest round number:\nFirst round: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11\nSecond round: 2, 3, 4, 5, 6, 11\nThird round: 2, 3, 4\nOne possible scenario which leads to the latest round number:\nFirst round: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11\nSecond round: 1, 2, 3, 4, 5, 6\nThird round: 1, 2, 4\nFourth round: 2, 4" + }, + { + "example_num": 2, + "expected_input": "n = 5, firstPlayer = 1, secondPlayer = 5", + "expected_output": "[1,1]", + "explanation": "The players numbered 1 and 5 compete in the first round.\nThere is no way to make them compete in any other round." + } + ], + "solution": "/**\n * @param {number} n\n * @param {number} firstPlayer\n * @param {number} secondPlayer\n * @return {number[]}\n */\nconst earliestAndLatest = function (n, firstPlayer, secondPlayer) {\n const { max, min } = Math\n const hash = {}\n function dp(l, r, m) {\n const key = `${l}${r}${m}`\n if (hash[key] != null) return hash[key]\n if (l > r) return dp(r, l, m)\n if (l === r) return [1, 1]\n let nxt_m = (m + 1) >> 1\n let ans = [n, 0]\n for (let i = 1; i < l + 1; i++) {\n let l_win = i - 1,\n l_lose = l - i\n for (\n let j = max(r - ~~(m / 2) - 1, 0) + l_lose + 1;\n j < min(r - 1 - l_win, nxt_m - i) + 1;\n j++\n ) {\n let tmp = dp(i, j, nxt_m)\n ans = [min(ans[0], tmp[0]), max(ans[1], tmp[1])]\n }\n }\n hash[key] = [ans[0] + 1, ans[1] + 1]\n return hash[key]\n }\n\n return dp(firstPlayer, n - secondPlayer + 1, n)\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720e87", + "questionid": 956, + "title": "Egg Drop With 2 Eggs and N Floors", + "slug": "egg-drop-with-2-eggs-and-n-floors", + "description": "You are given two identical eggs and you have access to a building with n floors labeled from 1 to n. You know that there exists a floor f where 0 <= f <= n such that any egg dropped at a floor higher than f will break, and any egg dropped at or below floor f will not break. In each move, you may take an unbroken egg and drop it from any floor x (where 1 <= x <= n). If the egg breaks, you can no longer use it. However, if the egg does not break, you may reuse it in future moves. Return the minimum number of moves that you need to determine with certainty what the value of f is. ", + "category": [ + "Math", + "Dynamic Programming" + ], + "complexity": "Medium", + "successrate": 70.3, + "totalsubmissions": 27756, + "totalaccepted": 19517, + "likes": 694, + "dislikes": 61, + "hints": "Is it really optimal to always drop the egg on the middle floor for each move? Can we create states based on the number of unbroken eggs and floors to build our solution?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 2", + "expected_output": "2", + "explanation": "We can drop the first egg from floor 1 and the second egg from floor 2.\nIf the first egg breaks, we know that f = 0.\nIf the second egg breaks but the first egg didn't, we know that f = 1.\nOtherwise, if both eggs survive, we know that f = 2." + }, + { + "example_num": 2, + "expected_input": "n = 100", + "expected_output": "14", + "explanation": "One optimal strategy is:\n- Drop the 1st egg at floor 9. If it breaks, we know f is between 0 and 8. Drop the 2nd egg starting from floor 1 and going up one at a time to find f within 8 more drops. Total drops is 1 + 8 = 9.\n- If the 1st egg does not break, drop the 1st egg again at floor 22. If it breaks, we know f is between 9 and 21. Drop the 2nd egg starting from floor 10 and going up one at a time to find f within 12 more drops. Total drops is 2 + 12 = 14.\n- If the 1st egg does not break again, follow a similar process dropping the 1st egg from floors 34, 45, 55, 64, 72, 79, 85, 90, 94, 97, 99, and 100.\nRegardless of the outcome, it takes at most 14 drops to determine f." + } + ], + "solution": "/**\n * @param {number} n\n * @return {number}\n */\nconst twoEggDrop = function (n) {\n const dp = Array(n + 1).fill(0)\n\n helper(n)\n// console.log(dp)\n return dp[n]\n\n function helper(k) {\n if(k === 0) return 0\n if (dp[k] === 0) {\n for (let i = 1; i <= k; i++) {\n dp[k] = Math.min(\n dp[k] === 0 ? k : dp[k],\n 1 + Math.max(i - 1, helper(k - i))\n )\n }\n }\n return dp[k]\n }\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720e8a", + "questionid": 959, + "title": "Count Square Sum Triples", + "slug": "count-square-sum-triples", + "description": "A square triple (a,b,c) is a triple where a, b, and c are integers and a2 + b2 = c2. Given an integer n, return the number of square triples such that 1 <= a, b, c <= n. ", + "category": [ + "Math", + "Enumeration" + ], + "complexity": "Easy", + "successrate": 67.4, + "totalsubmissions": 30768, + "totalaccepted": 20742, + "likes": 179, + "dislikes": 19, + "hints": "Iterate over all possible pairs (a,b) and check that the square root of a * a + b * b is an integers less than or equal n You can check that the square root of an integer is an integer using binary seach or a builtin function like sqrt", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 5", + "expected_output": "2\nExplanation: The square triples are (3,4,5) and (4,3,5).", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "n = 10", + "expected_output": "4\nExplanation: The square triples are (3,4,5), (4,3,5), (6,8,10), and (8,6,10).", + "explanation": "" + } + ], + "solution": "/**\n * @param {number} n\n * @return {number}\n */\nconst countTriples = function(n) {\n let res = 0\n const hash = {}\n for(let i = 1; i<= n; i++) {\n hash[i * i] = 1\n }\n \n for(let i = 1; i <= n; i++) {\n for(let j = i; i * i + j * j <= n * n; j++) {\n res += (hash[i * i + j * j] || 0) * 2\n }\n }\n\n return res\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720e8b", + "questionid": 960, + "title": "Nearest Exit from Entrance in Maze", + "slug": "nearest-exit-from-entrance-in-maze", + "description": "You are given an m x n matrix maze (0-indexed) with empty cells (represented as '.') and walls (represented as '+'). You are also given the entrance of the maze, where entrance = [entrancerow, entrancecol] denotes the row and column of the cell you are initially standing at. In one step, you can move one cell up, down, left, or right. You cannot step into a cell with a wall, and you cannot step outside the maze. Your goal is to find the nearest exit from the entrance. An exit is defined as an empty cell that is at the border of the maze. The entrance does not count as an exit. Return the number of steps in the shortest path from the entrance to the nearest exit, or -1 if no such path exists. ", + "category": [ + "Array", + "Breadth-First Search", + "Matrix" + ], + "complexity": "Medium", + "successrate": 40.1, + "totalsubmissions": 43797, + "totalaccepted": 17564, + "likes": 450, + "dislikes": 19, + "hints": "Which type of traversal lets you find the distance from a point? Try using a Breadth First Search.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "maze = [["+","+",".","+"],[".",".",".","+"],["+","+","+","."]], entrance = [1,2]", + "expected_output": "1", + "explanation": "There are 3 exits in this maze at [1,0], [0,2], and [2,3].\nInitially, you are at the entrance cell [1,2].\n- You can reach [1,0] by moving 2 steps left.\n- You can reach [0,2] by moving 1 step up.\nIt is impossible to reach [2,3] from the entrance.\nThus, the nearest exit is [0,2], which is 1 step away." + }, + { + "example_num": 2, + "expected_input": "maze = [["+","+","+"],[".",".","."],["+","+","+"]], entrance = [1,0]", + "expected_output": "2", + "explanation": "There is 1 exit in this maze at [1,2].\n[1,0] does not count as an exit since it is the entrance cell.\nInitially, you are at the entrance cell [1,0].\n- You can reach [1,2] by moving 2 steps right.\nThus, the nearest exit is [1,2], which is 2 steps away." + }, + { + "example_num": 3, + "expected_input": "maze = [[".","+"]], entrance = [0,0]", + "expected_output": "-1", + "explanation": "There are no exits in this maze." + } + ], + "solution": null + }, + { + "_id": "66f925ddfdfb8e1665720e4e", + "questionid": 899, + "title": "Sum of Beauty of All Substrings", + "slug": "sum-of-beauty-of-all-substrings", + "description": "The beauty of a string is the difference in frequencies between the most frequent and least frequent characters. Given a string s, return the sum of beauty of all of its substrings. ", + "category": [ + "Hash Table", + "String", + "Counting" + ], + "complexity": "Medium", + "successrate": 59.9, + "totalsubmissions": 21629, + "totalaccepted": 12952, + "likes": 306, + "dislikes": 83, + "hints": "Maintain a prefix sum for the frequencies of characters. You can iterate over all substring then iterate over the alphabet and find which character appears most and which appears least using the prefix sum array", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "aabcb"", + "expected_output": "5\nExplanation: The substrings with non-zero beauty are ["aab","aabc","aabcb","abcb","bcb"], each with beauty equal to 1.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "s = "aabcbaa"", + "expected_output": "17", + "explanation": "" + } + ], + "solution": "/**\n * @param {string} s\n * @return {number}\n */\nconst beautySum = function(s) {\n let ans = 0\n const a = 'a'.charCodeAt(0)\n const min = arr => {\n let res = Infinity\n for(let e of arr) {\n if(e !== 0) res = Math.min(e, res)\n }\n return res\n }\n for(let i = 0, n = s.length; i < n; i++) {\n let freq = Array(26).fill(0)\n for(let j = i; j < n; j++) {\n freq[s.charCodeAt(j) - a]++\n ans += Math.max(...freq) - min(freq)\n }\n }\n return ans \n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720e57", + "questionid": 908, + "title": "Check if One String Swap Can Make Strings Equal", + "slug": "check-if-one-string-swap-can-make-strings-equal", + "description": "You are given two strings s1 and s2 of equal length. A string swap is an operation where you choose two indices in a string (not necessarily different) and swap the characters at these indices. Return true if it is possible to make both strings equal by performing at most one string swap on exactly one of the strings. Otherwise, return false. ", + "category": [ + "Hash Table", + "String", + "Counting" + ], + "complexity": "Easy", + "successrate": 45.9, + "totalsubmissions": 84230, + "totalaccepted": 38673, + "likes": 452, + "dislikes": 18, + "hints": "The answer is false if the number of nonequal positions in the strings is not equal to 0 or 2. Check that these positions have the same set of characters.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s1 = "bank", s2 = "kanb"", + "expected_output": "true", + "explanation": "For example, swap the first character with the last character of s2 to make "bank"." + }, + { + "example_num": 2, + "expected_input": "s1 = "attack", s2 = "defend"", + "expected_output": "false", + "explanation": "It is impossible to make them equal with one string swap." + }, + { + "example_num": 3, + "expected_input": "s1 = "kelb", s2 = "kelb"", + "expected_output": "true", + "explanation": "The two strings are already equal, so no string swap operation is required." + } + ], + "solution": "/**\n * @param {string} s1\n * @param {string} s2\n * @return {boolean}\n */\nconst areAlmostEqual = function(s1, s2) {\n if (s1 === s2) return true\n let arr = []\n for(let i = 0, len = s1.length; i < len; i++) {\n if(s1[i] !== s2[i]) arr.push(i)\n \n if(arr.length > 2) return false\n }\n \n if(arr.length === 1) return false\n const [i1, i2] = arr\n if(s1[i2] === s2[i1] && s1[i1] === s2[i2]) return true\n return false\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720e5c", + "questionid": 913, + "title": "Sentence Similarity III", + "slug": "sentence-similarity-iii", + "description": "A sentence is a list of words that are separated by a single space with no leading or trailing spaces. For example, \"Hello World\", \"HELLO\", \"hello world hello world\" are all sentences. Words consist of only uppercase and lowercase English letters. Two sentences sentence1 and sentence2 are similar if it is possible to insert an arbitrary sentence (possibly empty) inside one of these sentences such that the two sentences become equal. For example, sentence1 = \"Hello my name is Jane\" and sentence2 = \"Hello Jane\" can be made equal by inserting \"my name is\" between \"Hello\" and \"Jane\" in sentence2. Given two sentences sentence1 and sentence2, return true if sentence1 and sentence2 are similar. Otherwise, return false. ", + "category": [ + "Array", + "Two Pointers", + "String" + ], + "complexity": "Medium", + "successrate": 32.4, + "totalsubmissions": 29402, + "totalaccepted": 9519, + "likes": 213, + "dislikes": 39, + "hints": "One way to look at it is to find one sentence as a concatenation of a prefix and suffix from the other sentence. Get the longest common prefix between them and the longest common suffix.", + "deleted": false, + "examples": [], + "solution": null + }, + { + "_id": "66f925ddfdfb8e1665720e65", + "questionid": 922, + "title": "Replace All Digits with Characters", + "slug": "replace-all-digits-with-characters", + "description": "You are given a 0-indexed string s that has lowercase English letters in its even indices and digits in its odd indices. There is a function shift(c, x), where c is a character and x is a digit, that returns the xth character after c. For every odd\u00a0index i, you want to replace the digit s[i] with shift(s[i-1], s[i]). Return s after replacing all digits. It is guaranteed that shift(s[i-1], s[i]) will never exceed 'z'. ", + "category": [ + "String" + ], + "complexity": "Easy", + "successrate": 80.1, + "totalsubmissions": 48332, + "totalaccepted": 38693, + "likes": 377, + "dislikes": 46, + "hints": "We just need to replace every even positioned character with the character s[i] positions ahead of the character preceding it Get the position of the preceeding character in alphabet then advance it s[i] positions and get the character at that position", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "a1c1e1"", + "expected_output": ""abcdef"\nExplanation: The digits are replaced as follows:\n- s[1] -> shift('a',1) = 'b'\n- s[3] -> shift('c',1) = 'd'\n- s[5] -> shift('e',1) = 'f'", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "s = "a1b2c3d4e"", + "expected_output": ""abbdcfdhe"\nExplanation: The digits are replaced as follows:\n- s[1] -> shift('a',1) = 'b'\n- s[3] -> shift('b',2) = 'd'\n- s[5] -> shift('c',3) = 'f'\n- s[7] -> shift('d',4) = 'h'", + "explanation": "" + } + ], + "solution": "/**\n * @param {string} s\n * @return {string}\n */\nconst replaceDigits = function(s) {\n let arr = s.split('')\n for(let i = 1; i < s.length; i += 2) {\n arr[i] = shift(s[i - 1], +s[i])\n }\n\n return arr.join('')\n\n function shift(ch, x) {\n return String.fromCharCode(ch.charCodeAt(0) + x)\n }\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720e66", + "questionid": 923, + "title": "Check if the Sentence Is Pangram", + "slug": "check-if-the-sentence-is-pangram", + "description": "A pangram is a sentence where every letter of the English alphabet appears at least once. Given a string sentence containing only lowercase English letters, return true if sentence is a pangram, or false otherwise. ", + "category": [ + "Hash Table", + "String" + ], + "complexity": "Easy", + "successrate": 81.4, + "totalsubmissions": 98831, + "totalaccepted": 80461, + "likes": 707, + "dislikes": 18, + "hints": "Iterate over the string and mark each character as found (using a boolean array, bitmask, or any other similar way). Check if the number of found characters equals the alphabet length.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "sentence = "thequickbrownfoxjumpsoverthelazydog"", + "expected_output": "true", + "explanation": "sentence contains at least one of every letter of the English alphabet." + }, + { + "example_num": 2, + "expected_input": "sentence = "leetcode"", + "expected_output": "false", + "explanation": "" + } + ], + "solution": "/**\n * @param {string} sentence\n * @return {boolean}\n */\nconst checkIfPangram = function(sentence) {\n const hash = new Map()\n for(let ch of sentence) {\n if(!hash.has(ch)) hash.set(ch, 0)\n hash.set(ch, hash.get(ch) + 1)\n }\n return hash.size >= 26\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720e6d", + "questionid": 930, + "title": "Splitting a String Into Descending Consecutive Values", + "slug": "splitting-a-string-into-descending-consecutive-values", + "description": "You are given a string s that consists of only digits. Check if we can split s into two or more non-empty substrings such that the numerical values of the substrings are in descending order and the difference between numerical values of every two adjacent substrings is equal to 1. Return true if it is possible to split s as described above, or false otherwise. A substring is a contiguous sequence of characters in a string. ", + "category": [ + "String", + "Backtracking" + ], + "complexity": "Medium", + "successrate": 31.2, + "totalsubmissions": 45020, + "totalaccepted": 14056, + "likes": 309, + "dislikes": 82, + "hints": "One solution is to try all possible splits using backtrack Look out for trailing zeros in string", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "1234"", + "expected_output": "false", + "explanation": "There is no valid way to split s." + }, + { + "example_num": 2, + "expected_input": "s = "050043"", + "expected_output": "true", + "explanation": "s can be split into ["05", "004", "3"] with numerical values [5,4,3].\nThe values are in descending order with adjacent values differing by 1." + }, + { + "example_num": 3, + "expected_input": "s = "9080701"", + "expected_output": "false", + "explanation": "There is no valid way to split s." + } + ], + "solution": "/**\n * @param {string} s\n * @return {boolean}\n */\nconst splitString = function(s) {\n return helper(s, null)\n};\n\nfunction helper(str, previous) {\n for(let i = 0, n = str.length; i < n; i++) {\n const tmp = +(str.slice(0, i + 1))\n if(previous == null) {\n if(helper(str.slice(i + 1), tmp)) return true\n } else if(previous - tmp === 1 && (i === n - 1 || helper(str.slice(i + 1), tmp))) return true\n }\n \n return false\n}\n\n\n// another\n\n\n/**\n * @param {string} s\n * @return {boolean}\n */\nconst splitString = function(s) {\n return dfs(s, 0, [Infinity])\n};\n\nfunction dfs(str, idx, arr) {\n if(idx >= str.length && arr.length > 2) return true\n for(let i = idx; i < str.length; i++) {\n const tmp = str.slice(idx, i + 1)\n const num = parseInt(tmp, 10)\n const pre = arr[arr.length - 1]\n if(num < pre && (pre === Infinity || pre - num === 1)) {\n arr.push(num)\n if(dfs(str, i + 1, arr)) return true \n arr.pop()\n }\n }\n return false\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720e76", + "questionid": 939, + "title": "Minimum Number of Swaps to Make the Binary String Alternating", + "slug": "minimum-number-of-swaps-to-make-the-binary-string-alternating", + "description": "Given a binary string s, return the minimum number of character swaps to make it alternating, or -1 if it is impossible. The string is called alternating if no two adjacent characters are equal. For example, the strings \"010\" and \"1010\" are alternating, while the string \"0100\" is not. Any two characters may be swapped, even if they are\u00a0not adjacent. ", + "category": [ + "String", + "Greedy" + ], + "complexity": "Medium", + "successrate": 38.8, + "totalsubmissions": 33785, + "totalaccepted": 13095, + "likes": 298, + "dislikes": 22, + "hints": "Think about all valid strings of length n. Try to count the mismatched positions with each valid string of length n.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "111000"", + "expected_output": "1", + "explanation": "Swap positions 1 and 4: "111000" -> "101010"\nThe string is now alternating." + }, + { + "example_num": 2, + "expected_input": "s = "010"", + "expected_output": "0", + "explanation": "The string is already alternating, no swaps are needed." + }, + { + "example_num": 3, + "expected_input": "s = "1110"", + "expected_output": "-1", + "explanation": "" + } + ], + "solution": "/**\n * @param {string} s\n * @return {number}\n */\nconst minSwaps = function(s) {\n const valid = chk(s)\n if(valid === -1) return -1\n const [zeroNum, oneNum] = valid\n let res = Infinity\n if(zeroNum === oneNum) {\n // zero start\n let tmpZero = 0\n let cur = '0'\n for(let i = 0; i < s.length; i++) {\n if(i % 2 === 0 && s[i] !== '0') tmpZero++\n }\n \n res = Math.min(tmpZero, res)\n // one start\n let tmpOne = 0\n cur = '1'\n for(let i = 0; i < s.length; i++) {\n if(i % 2 === 0 && s[i] !== '1') tmpOne++\n }\n res = Math.min(tmpOne, res)\n } else if(zeroNum > oneNum) {\n let tmpZero = 0\n let cur = '0'\n for(let i = 0; i < s.length; i++) {\n if(i % 2 === 0 && s[i] !== '0') tmpZero++\n }\n \n res = Math.min(tmpZero, res) \n } else {\n let tmpOne = 0\n cur = '1'\n for(let i = 0; i < s.length; i++) {\n if(i % 2 === 0 && s[i] !== '1') tmpOne++\n }\n res = Math.min(tmpOne, res)\n }\n return res\n};\n\nfunction chk(str) {\n let oneNum = 0, zeroNum = 0\n for(let ch of str) {\n if(ch === '0') zeroNum++\n else oneNum++\n } \n return Math.abs(zeroNum - oneNum) <= 1 ? [zeroNum, oneNum] : -1\n}\n\n" + }, + { + "_id": "66f925ddfdfb8e1665720e82", + "questionid": 951, + "title": "Remove One Element to Make the Array Strictly Increasing", + "slug": "remove-one-element-to-make-the-array-strictly-increasing", + "description": "Given a 0-indexed integer array nums, return true if it can be made strictly increasing after removing exactly one element, or false otherwise. If the array is already strictly increasing, return true. The array nums is strictly increasing if nums[i - 1] < nums[i] for each index (1 <= i < nums.length). ", + "category": [ + "Array" + ], + "complexity": "Easy", + "successrate": 27.3, + "totalsubmissions": 92517, + "totalaccepted": 25295, + "likes": 484, + "dislikes": 195, + "hints": "For each index i in nums remove this index. If the array becomes sorted return true, otherwise revert to the original array and try different index.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,2,10,5,7]", + "expected_output": "true", + "explanation": "By removing 10 at index 2 from nums, it becomes [1,2,5,7].\n[1,2,5,7] is strictly increasing, so return true." + }, + { + "example_num": 2, + "expected_input": "nums = [2,3,1,2]", + "expected_output": "false", + "explanation": "[3,1,2] is the result of removing the element at index 0.\n[2,1,2] is the result of removing the element at index 1.\n[2,3,2] is the result of removing the element at index 2.\n[2,3,1] is the result of removing the element at index 3.\nNo resulting array is strictly increasing, so return false." + }, + { + "example_num": 3, + "expected_input": "nums = [1,1,1]", + "expected_output": "false", + "explanation": "The result of removing any element is [1,1].\n[1,1] is not strictly increasing, so return false." + } + ], + "solution": "/**\n * @param {number[]} nums\n * @return {boolean}\n */\nconst canBeIncreasing = function(nums) {\n\tlet previous = nums[0];\n\tlet used = false;\n\tfor (let i = 1; i < nums.length; i++){\n\t\tif (nums[i] <= previous) {\n if (used) return false;\n used = true;\n if (i === 1 || nums[i] > nums[i - 2]) previous = nums[i];\n\t\t} else previous = nums[i];\n\t}\n\treturn true;\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720e88", + "questionid": 957, + "title": "Largest Odd Number in String", + "slug": "largest-odd-number-in-string", + "description": "You are given a string num, representing a large integer. Return the largest-valued odd integer (as a string) that is a non-empty substring of num, or an empty string \"\" if no odd integer exists. A substring is a contiguous sequence of characters within a string. ", + "category": [ + "Math", + "String", + "Greedy" + ], + "complexity": "Easy", + "successrate": 56.9, + "totalsubmissions": 54918, + "totalaccepted": 31242, + "likes": 353, + "dislikes": 29, + "hints": "In what order should you iterate through the digits? If an odd number exists, where must the number start from?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "num = "52"", + "expected_output": ""5"", + "explanation": "The only non-empty substrings are "5", "2", and "52". "5" is the only odd number." + }, + { + "example_num": 2, + "expected_input": "num = "4206"", + "expected_output": """", + "explanation": "There are no odd numbers in "4206"." + }, + { + "example_num": 3, + "expected_input": "num = "35427"", + "expected_output": ""35427"", + "explanation": ""35427" is already an odd number." + } + ], + "solution": "/**\n * @param {string} num\n * @return {string}\n */\nconst largestOddNumber = function(num) {\n let idx= -1\n for(let i = 0, n = num.length; i < n; i++) {\n if((+num[i]) % 2 === 1) idx = i\n }\n return num.slice(0, idx+1)\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720e89", + "questionid": 958, + "title": "Count Sub Islands", + "slug": "count-sub-islands", + "description": "You are given two m x n binary matrices grid1 and grid2 containing only 0's (representing water) and 1's (representing land). An island is a group of 1's connected 4-directionally (horizontal or vertical). Any cells outside of the grid are considered water cells. An island in grid2 is considered a sub-island if there is an island in grid1 that contains all the cells that make up this island in grid2. Return the number of islands in grid2 that are considered sub-islands. ", + "category": [ + "Array", + "Depth-First Search", + "Breadth-First Search", + "Union Find", + "Matrix" + ], + "complexity": "Medium", + "successrate": 65.7, + "totalsubmissions": 45218, + "totalaccepted": 29705, + "likes": 876, + "dislikes": 27, + "hints": "Let's use floodfill to iterate over the islands of the second grid Let's note that if all the cells in an island in the second grid if they are represented by land in the first grid then they are connected hence making that island a sub-island", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "grid1 = [[1,1,1,0,0],[0,1,1,1,1],[0,0,0,0,0],[1,0,0,0,0],[1,1,0,1,1]], grid2 = [[1,1,1,0,0],[0,0,1,1,1],[0,1,0,0,0],[1,0,1,1,0],[0,1,0,1,0]]", + "expected_output": "3\nExplanation: In the picture above, the grid on the left is grid1 and the grid on the right is grid2.\nThe 1s colored red in grid2 are those considered to be part of a sub-island. There are three sub-islands.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "grid1 = [[1,0,1,0,1],[1,1,1,1,1],[0,0,0,0,0],[1,1,1,1,1],[1,0,1,0,1]], grid2 = [[0,0,0,0,0],[1,1,1,1,1],[0,1,0,1,0],[0,1,0,1,0],[1,0,0,0,1]]", + "expected_output": "2 \nExplanation: In the picture above, the grid on the left is grid1 and the grid on the right is grid2.\nThe 1s colored red in grid2 are those considered to be part of a sub-island. There are two sub-islands.", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[][]} grid1\n * @param {number[][]} grid2\n * @return {number}\n */\nconst countSubIslands = function(grid1, grid2) {\n let m = grid2.length, n = grid2[0].length, res = 0;\n for (let i = 0; i < m; i++) {\n for (let j = 0; j < n; j++) {\n if (grid2[i][j] === 1) res += dfs(grid1, grid2, i, j); \n }\n }\n return res; \n};\n\nfunction dfs(B, A, i, j) {\n let m = A.length, n = A[0].length, res = 1;\n if (i < 0 || i == m || j < 0 || j == n || A[i][j] == 0) return 1;\n A[i][j] = 0;\n res &= dfs(B, A, i - 1, j);\n res &= dfs(B, A, i + 1, j);\n res &= dfs(B, A, i, j - 1);\n res &= dfs(B, A, i, j + 1);\n return res & B[i][j];\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720e4d", + "questionid": 898, + "title": "Check if Number is a Sum of Powers of Three", + "slug": "check-if-number-is-a-sum-of-powers-of-three", + "description": "Given an integer n, return true if it is possible to represent n as the sum of distinct powers of three. Otherwise, return false. An integer y is a power of three if there exists an integer x such that y == 3x. ", + "category": [ + "Math" + ], + "complexity": "Medium", + "successrate": 64.7, + "totalsubmissions": 32597, + "totalaccepted": 21101, + "likes": 505, + "dislikes": 18, + "hints": "Let's note that the maximum power of 3 you'll use in your soln is 3^16 The number can not be represented as a sum of powers of 3 if it's ternary presentation has a 2 in it", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 12", + "expected_output": "true", + "explanation": "12 = 31 + 32" + }, + { + "example_num": 2, + "expected_input": "n = 91", + "expected_output": "true", + "explanation": "91 = 30 + 32 + 34" + }, + { + "example_num": 3, + "expected_input": "n = 21", + "expected_output": "false", + "explanation": "" + } + ], + "solution": "/**\n * @param {number} n\n * @return {boolean}\n */\nconst checkPowersOfThree = function(n) {\n const num = ~~(n / 3)\n const rem = n % 3\n if(num === 0 && rem === 1) return true\n if(rem === 2) return false\n return checkPowersOfThree(num)\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720e4f", + "questionid": 900, + "title": "Merge Strings Alternately", + "slug": "merge-strings-alternately", + "description": "You are given two strings word1 and word2. Merge the strings by adding letters in alternating order, starting with word1. If a string is longer than the other, append the additional letters onto the end of the merged string. Return the merged string. ", + "category": [ + "Two Pointers", + "String" + ], + "complexity": "Easy", + "successrate": 75.5, + "totalsubmissions": 71706, + "totalaccepted": 54156, + "likes": 544, + "dislikes": 8, + "hints": "Use two pointers, one pointer for each string. Alternately choose the character from each pointer, and move the pointer upwards.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "word1 = "abc", word2 = "pqr"", + "expected_output": ""apbqcr"", + "explanation": " The merged string will be merged as so:\r\nword1: a b c\r\nword2: p q r\r\nmerged: a p b q c r" + }, + { + "example_num": 2, + "expected_input": "word1 = "ab", word2 = "pqrs"", + "expected_output": ""apbqrs"", + "explanation": " Notice that as word2 is longer, "rs" is appended to the end.\r\nword1: a b \r\nword2: p q r s\r\nmerged: a p b q r s" + }, + { + "example_num": 3, + "expected_input": "word1 = "abcd", word2 = "pq"", + "expected_output": ""apbqcd"", + "explanation": " Notice that as word1 is longer, "cd" is appended to the end.\r\nword1: a b c d\r\nword2: p q \r\nmerged: a p b q c d" + } + ], + "solution": "/**\n * @param {string} word1\n * @param {string} word2\n * @return {string}\n */\nvar mergeAlternately = function(word1, word2) {\n let res = '', mark = 0, i = 0, j = 0\n while(i < word1.length && j < word2.length) {\n if(mark === 0) {\n res += word1[i++]\n mark = 1\n } else {\n res += word2[j++]\n mark = 0\n }\n }\n while(i < word1.length) res += word1[i++]\n while(j < word2.length) res += word2[j++]\n \n return res\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720e51", + "questionid": 902, + "title": "Equal Sum Arrays With Minimum Number of Operations", + "slug": "equal-sum-arrays-with-minimum-number-of-operations", + "description": "You are given two arrays of integers nums1 and nums2, possibly of different lengths. The values in the arrays are between 1 and 6, inclusive. In one operation, you can change any integer's value in any of the arrays to any value between 1 and 6, inclusive. Return the minimum number of operations required to make the sum of values in nums1 equal to the sum of values in nums2. Return -1 if it is not possible to make the sum of the two arrays equal. ", + "category": [ + "Array", + "Hash Table", + "Greedy", + "Counting" + ], + "complexity": "Medium", + "successrate": 51.4, + "totalsubmissions": 28446, + "totalaccepted": 14621, + "likes": 494, + "dislikes": 16, + "hints": "Let's note that we want to either decrease the sum of the array with a larger sum or increase the array's sum with the smaller sum. You can maintain the largest increase or decrease you can make in a binary search tree and each time get the maximum one.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums1 = [1,2,3,4,5,6], nums2 = [1,1,2,2,2,2]", + "expected_output": "3", + "explanation": "You can make the sums of nums1 and nums2 equal with 3 operations. All indices are 0-indexed.\n- Change nums2[0] to 6. nums1 = [1,2,3,4,5,6], nums2 = [6,1,2,2,2,2].\n- Change nums1[5] to 1. nums1 = [1,2,3,4,5,1], nums2 = [6,1,2,2,2,2].\n- Change nums1[2] to 2. nums1 = [1,2,2,4,5,1], nums2 = [6,1,2,2,2,2]." + }, + { + "example_num": 2, + "expected_input": "nums1 = [1,1,1,1,1,1,1], nums2 = [6]", + "expected_output": "-1", + "explanation": "There is no way to decrease the sum of nums1 or to increase the sum of nums2 to make them equal." + }, + { + "example_num": 3, + "expected_input": "nums1 = [6,6], nums2 = [1]", + "expected_output": "3", + "explanation": "You can make the sums of nums1 and nums2 equal with 3 operations. All indices are 0-indexed. \n- Change nums1[0] to 2. nums1 = [2,6], nums2 = [1].\n- Change nums1[1] to 2. nums1 = [2,2], nums2 = [1].\n- Change nums2[0] to 4. nums1 = [2,2], nums2 = [4]." + } + ], + "solution": "/**\n * @param {number[]} nums1\n * @param {number[]} nums2\n * @return {number}\n */\nconst minOperations = function(nums1, nums2) {\n const m = nums1.length, n = nums2.length\n if(m > n * 6 || n > m * 6) return -1\n let sum1 = sum(nums1), sum2 = sum(nums2)\n if(sum1 > sum2) return minOperations(nums2, nums1)\n\n const arr = Array(6).fill(0)\n nums1.forEach(e => arr[6 - e]++)\n nums2.forEach(e => arr[e - 1]++)\n\n let res = 0, i = 5\n while(sum1 < sum2) {\n while(arr[i] === 0) i--\n sum1 += i\n res++\n arr[i]--\n }\n\n return res\n};\n\nfunction sum(arr) {\n return arr.reduce((ac, e) => ac + e, 0)\n}\n\n// another\n\n/**\n * @param {number[]} nums1\n * @param {number[]} nums2\n * @return {number}\n */\nconst minOperations = function(nums1, nums2) {\n const m = nums1.length, n = nums2.length\n if(m > n * 6 || n > m * 6) return -1\n const sum1 = nums1.reduce((ac, e) => ac + e, 0)\n const sum2 = nums2.reduce((ac, e) => ac + e, 0)\n let largerArr, smallerArr\n if(sum1 === sum2) return 0\n if(sum1 > sum2) {\n largerArr = nums1\n smallerArr = nums2\n } else {\n largerArr = nums2\n smallerArr = nums1\n }\n \n const gain = []\n for(let e of largerArr) gain.push(e - 1)\n for(let e of smallerArr) gain.push(6 - e)\n gain.sort((a, b) => b - a)\n let diff = Math.abs(sum2 - sum1)\n let cnt = 0\n for(let e of gain) {\n diff -= e\n cnt++\n if(diff <= 0) return cnt\n }\n return -1\n};\n\n\n\n\n// another\n\n/**\n * @param {number[]} nums1\n * @param {number[]} nums2\n * @return {number}\n */\nconst minOperations = function(nums1, nums2) {\n const len1 = nums1.length, len2 = nums2.length;\n if (len1 > 6 * len2 || len2 > 6 * len1) return -1;\n let sum1 = 0, sum2 = 0;\n for (let x of nums1) sum1 += x;\n for (let x of nums2) sum2 += x;\n if (sum1 === sum2) return 0;\n nums1.sort((a, b) => a - b)\n nums2.sort((a, b) => a - b)\n let cnt = 0;\n if (sum1 > sum2) {\n let ind1 = len1 - 1, ind2 = 0;\n while (sum1 > sum2) { \n if (ind2 === len2 || nums1[ind1] - 1 > 6 - nums2[ind2]) sum1 -= nums1[ind1--] - 1;\n else sum2 += 6 - nums2[ind2++];\n cnt++;\n }\n return cnt;\n }\n let ind1 = 0, ind2 = len2 - 1;\n while (sum1 < sum2) {\n if (ind1 === len1 || nums2[ind2] - 1 > 6 - nums1[ind1]) sum2 -= nums2[ind2--] - 1;\n else sum1 += 6 - nums1[ind1++];\n cnt++;\n }\n return cnt;\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720e52", + "questionid": 903, + "title": "Second Largest Digit in a String", + "slug": "second-largest-digit-in-a-string", + "description": "Given an alphanumeric string s, return the second largest numerical digit that appears in s, or -1 if it does not exist. An alphanumeric string is a string consisting of lowercase English letters and digits. ", + "category": [ + "Hash Table", + "String" + ], + "complexity": "Easy", + "successrate": 49, + "totalsubmissions": 50676, + "totalaccepted": 24842, + "likes": 245, + "dislikes": 70, + "hints": "First of all, get the distinct characters since we are only interested in those Let's note that there might not be any digits.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "dfa12321afd"", + "expected_output": "2", + "explanation": "The digits that appear in s are [1, 2, 3]. The second largest digit is 2." + }, + { + "example_num": 2, + "expected_input": "s = "abc1111"", + "expected_output": "-1", + "explanation": "The digits that appear in s are [1]. There is no second largest digit." + } + ], + "solution": null + }, + { + "_id": "66f925ddfdfb8e1665720e54", + "questionid": 905, + "title": "Check if Binary String Has at Most One Segment of Ones", + "slug": "check-if-binary-string-has-at-most-one-segment-of-ones", + "description": "Given a binary string s without leading zeros, return true if s contains at most one contiguous segment of ones. Otherwise, return false. ", + "category": [ + "String" + ], + "complexity": "Easy", + "successrate": 40.8, + "totalsubmissions": 57619, + "totalaccepted": 23535, + "likes": 163, + "dislikes": 520, + "hints": "It's guaranteed to have at least one segment The string size is small so you can count all segments of ones with no that have no adjacent ones.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "1001"", + "expected_output": "false\nExplanation: The ones do not form a contiguous segment.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "s = "110"", + "expected_output": "true", + "explanation": "" + } + ], + "solution": "/**\n * @param {string} s\n * @return {boolean}\n */\nconst checkOnesSegment = function(s) {\n let res = 1\n for(let i = 1, len = s.length; i < len; i++) {\n if(s[i] === '1' && s[i - 1] === '0') res++\n if(s[i] === '1' && s[i - 1] === '1') continue\n }\n return res <= 1\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720e56", + "questionid": 907, + "title": "Number of Restricted Paths From First to Last Node", + "slug": "number-of-restricted-paths-from-first-to-last-node", + "description": "There is an undirected weighted connected graph. You are given a positive integer n which denotes that the graph has n nodes labeled from 1 to n, and an array edges where each edges[i] = [ui, vi, weighti] denotes that there is an edge between nodes ui and vi with weight equal to weighti. A path from node start to node end is a sequence of nodes [z0, z1, z2, ..., zk] such that z0 = start and zk = end and there is an edge between zi and zi+1 where 0 <= i <= k-1. The distance of a path is the sum of the weights on the edges of the path. Let distanceToLastNode(x) denote the shortest distance of a path between node n and node x. A restricted path is a path that also satisfies that distanceToLastNode(zi) > distanceToLastNode(zi+1) where 0 <= i <= k-1. Return the number of restricted paths from node 1 to node n. Since that number may be too large, return it modulo 109 + 7. ", + "category": [ + "Dynamic Programming", + "Graph", + "Topological Sort", + "Heap (Priority Queue)", + "Shortest Path" + ], + "complexity": "Medium", + "successrate": 38.6, + "totalsubmissions": 32401, + "totalaccepted": 12491, + "likes": 579, + "dislikes": 101, + "hints": "Run a Dijkstra from node numbered n to compute distance from the last node. Consider all edges [u, v] one by one and direct them such that distance of u to n > distance of v to n. If both u and v are at the same distance from n, discard this edge. Now this problem reduces to computing the number of paths from 1 to n in a DAG, a standard DP problem.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 5, edges = [[1,2,3],[1,3,3],[2,3,1],[1,4,2],[5,2,2],[3,5,1],[5,4,10]]", + "expected_output": "3", + "explanation": "Each circle contains the node number in black and its distanceToLastNode value in blue. The three restricted paths are:\n1) 1 --> 2 --> 5\n2) 1 --> 2 --> 3 --> 5\n3) 1 --> 3 --> 5" + }, + { + "example_num": 2, + "expected_input": "n = 7, edges = [[1,3,1],[4,1,2],[7,3,4],[2,5,3],[5,6,1],[6,7,2],[7,5,3],[2,6,4]]", + "expected_output": "1", + "explanation": "Each circle contains the node number in black and its distanceToLastNode value in blue. The only restricted path is 1 --> 3 --> 7." + } + ], + "solution": "/**\n * @param {number} n\n * @param {number[][]} edges\n * @return {number}\n */\nconst countRestrictedPaths = function(n, edges) {\n const adj = {}\n const MOD = 10 ** 9 + 7\n for(let edge of edges) {\n const [u,v,d] = edge\n if(adj[u] == null) adj[u] = []\n if(adj[v] == null) adj[v] = []\n adj[u].push([v, d])\n adj[v].push([u, d])\n }\n const dist = Array(n + 1).fill(Infinity)\n dist[n] = 0\n const pq = new PriorityQueue((a, b) => a[0] < b[0])\n pq.push([0, n])\n while(!pq.isEmpty()) {\n const [d, u] = pq.peek()\n pq.pop()\n if(d > dist[u]) continue\n for(let [v, c] of adj[u]) {\n if(d + c < dist[v]) {\n dist[v] = d + c\n pq.push([dist[v], v])\n }\n }\n }\n \n const order = Array(n).fill(0)\n for(let i = 0; i < n; i++) {\n order[i] = i + 1\n }\n \n order.sort((u, v) => dist[u] - dist[v])\n const ans = Array(n + 1).fill(0)\n ans[n] = 1\n for(let u of order) {\n for(let [v, c] of adj[u]) {\n if(dist[v] > dist[u]) {\n ans[v] = (ans[v] + ans[u]) % MOD\n }\n }\n }\n \n return ans[1]\n};\n\n\nclass PriorityQueue {\n constructor(comparator = (a, b) => a > b) {\n this.heap = []\n this.top = 0\n this.comparator = comparator\n }\n size() {\n return this.heap.length\n }\n isEmpty() {\n return this.size() === 0\n }\n peek() {\n return this.heap[this.top]\n }\n push(...values) {\n values.forEach((value) => {\n this.heap.push(value)\n this.siftUp()\n })\n return this.size()\n }\n pop() {\n const poppedValue = this.peek()\n const bottom = this.size() - 1\n if (bottom > this.top) {\n this.swap(this.top, bottom)\n }\n this.heap.pop()\n this.siftDown()\n return poppedValue\n }\n replace(value) {\n const replacedValue = this.peek()\n this.heap[this.top] = value\n this.siftDown()\n return replacedValue\n }\n\n parent = (i) => ((i + 1) >>> 1) - 1\n left = (i) => (i << 1) + 1\n right = (i) => (i + 1) << 1\n greater = (i, j) => this.comparator(this.heap[i], this.heap[j])\n swap = (i, j) => ([this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]])\n siftUp = () => {\n let node = this.size() - 1\n while (node > this.top && this.greater(node, this.parent(node))) {\n this.swap(node, this.parent(node))\n node = this.parent(node)\n }\n }\n siftDown = () => {\n let node = this.top\n while (\n (this.left(node) < this.size() && this.greater(this.left(node), node)) ||\n (this.right(node) < this.size() && this.greater(this.right(node), node))\n ) {\n let maxChild =\n this.right(node) < this.size() &&\n this.greater(this.right(node), this.left(node))\n ? this.right(node)\n : this.left(node)\n this.swap(node, maxChild)\n node = maxChild\n }\n }\n}\n\n// another\n\n/**\n * @param {number} n\n * @param {number[][]} edges\n * @return {number}\n */\nconst countRestrictedPaths = function(n, edges) {\n if (n === 1) return 0\n const graph = {}\n for(const [u, v, t] of edges) {\n if(graph[u] == null) graph[u] = {}\n if(graph[v] == null) graph[v] = {}\n graph[u][v] = t\n graph[v][u] = t\n }\n const dist = dijkstra(n, graph)\n const memo = Array(n + 1).fill(null)\n const res = dfs(1)\n return res\n\n function dijkstra(n, graph) {\n const dist = Array(n + 1).fill(Infinity)\n dist[n] = 0\n const pq = new PriorityQueue((a, b) => a[0] < b[0])\n pq.push([0, n])\n while(!pq.isEmpty()) {\n const [d, cur] = pq.pop()\n if(d !== dist[cur]) continue\n for(const next of Object.keys(graph[cur] || {})) {\n const delta = graph[cur][next]\n if(dist[next] > d + delta) {\n dist[next] = d + delta\n pq.push([d + delta, next])\n } \n }\n }\n return dist\n }\n\n function dfs(src) {\n if(memo[src] != null) return memo[src]\n if(src === n) return 1\n let res = 0\n for(let next of Object.keys(graph[src] || {})) {\n next = +next\n if(dist[src] > dist[next]) {\n res = ((res + dfs(next)) % (1e9 + 7))\n }\n }\n return memo[src] = res\n }\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720e59", + "questionid": 910, + "title": "Maximum Average Pass Ratio", + "slug": "maximum-average-pass-ratio", + "description": "There is a school that has classes of students and each class will be having a final exam. You are given a 2D integer array classes, where classes[i] = [passi, totali]. You know beforehand that in the ith class, there are totali total students, but only passi number of students will pass the exam. You are also given an integer extraStudents. There are another extraStudents brilliant students that are guaranteed to pass the exam of any class they are assigned to. You want to assign each of the extraStudents students to a class in a way that maximizes the average pass ratio across all the classes. The pass ratio of a class is equal to the number of students of the class that will pass the exam divided by the total number of students of the class. The average pass ratio is the sum of pass ratios of all the classes divided by the number of the classes. Return the maximum possible average pass ratio after assigning the extraStudents students. Answers within 10-5 of the actual answer will be accepted. ", + "category": [ + "Array", + "Greedy", + "Heap (Priority Queue)" + ], + "complexity": "Medium", + "successrate": 50.7, + "totalsubmissions": 29069, + "totalaccepted": 14741, + "likes": 474, + "dislikes": 58, + "hints": "Pay attention to how much the pass ratio changes when you add a student to the class. If you keep adding students, what happens to the change in pass ratio? The more students you add to a class, the smaller the change in pass ratio becomes. Since the change in the pass ratio is always decreasing with the more students you add, then the very first student you add to each class is the one that makes the biggest change in the pass ratio. Because each class's pass ratio is weighted equally, it's always optimal to put the student in the class that makes the biggest change among all the other classes. Keep a max heap of the current class sizes and order them by the change in pass ratio. For each extra student, take the top of the heap, update the class size, and put it back in the heap.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "classes = [[1,2],[3,5],[2,2]], extraStudents = 2", + "expected_output": "0.78333", + "explanation": "You can assign the two extra students to the first class. The average pass ratio will be equal to (3/4 + 3/5 + 2/2) / 3 = 0.78333." + }, + { + "example_num": 2, + "expected_input": "classes = [[2,4],[3,9],[4,5],[2,10]], extraStudents = 4", + "expected_output": "0.53485", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[][]} classes\n * @param {number} extraStudents\n * @return {number}\n */\nconst maxAverageRatio = function (classes, extraStudents) {\n const pq = new PriorityQueue((a, b) => a.delta > b.delta)\n const n = classes.length\n for (let e of classes) {\n pq.push({\n pass: e[0],\n total: e[1],\n ratio: e[0] / e[1],\n delta: (e[0] + 1) / (e[1] + 1) - e[0] / e[1],\n })\n }\n\n while (extraStudents) {\n const tmp = pq.pop()\n tmp.pass++\n tmp.total++\n tmp.ratio = tmp.pass / tmp.total\n tmp.delta = (tmp.pass + 1) / (tmp.total + 1) - tmp.ratio\n pq.push(tmp)\n extraStudents--\n }\n\n let res = 0\n while (!pq.isEmpty()) {\n const tmp = pq.pop()\n res += tmp.ratio\n }\n\n return res / n\n}\n\nclass PriorityQueue {\n constructor(comparator = (a, b) => a > b) {\n this.heap = []\n this.top = 0\n this.comparator = comparator\n }\n size() {\n return this.heap.length\n }\n isEmpty() {\n return this.size() === 0\n }\n peek() {\n return this.heap[this.top]\n }\n push(...values) {\n values.forEach((value) => {\n this.heap.push(value)\n this.siftUp()\n })\n return this.size()\n }\n pop() {\n const poppedValue = this.peek()\n const bottom = this.size() - 1\n if (bottom > this.top) {\n this.swap(this.top, bottom)\n }\n this.heap.pop()\n this.siftDown()\n return poppedValue\n }\n replace(value) {\n const replacedValue = this.peek()\n this.heap[this.top] = value\n this.siftDown()\n return replacedValue\n }\n\n parent = (i) => ((i + 1) >>> 1) - 1\n left = (i) => (i << 1) + 1\n right = (i) => (i + 1) << 1\n greater = (i, j) => this.comparator(this.heap[i], this.heap[j])\n swap = (i, j) => ([this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]])\n siftUp = () => {\n let node = this.size() - 1\n while (node > this.top && this.greater(node, this.parent(node))) {\n this.swap(node, this.parent(node))\n node = this.parent(node)\n }\n }\n siftDown = () => {\n let node = this.top\n while (\n (this.left(node) < this.size() && this.greater(this.left(node), node)) ||\n (this.right(node) < this.size() && this.greater(this.right(node), node))\n ) {\n let maxChild =\n this.right(node) < this.size() &&\n this.greater(this.right(node), this.left(node))\n ? this.right(node)\n : this.left(node)\n this.swap(node, maxChild)\n node = maxChild\n }\n }\n}\n\n\n\n// another\n\n/**\n * @param {number[][]} classes\n * @param {number} extraStudents\n * @return {number}\n */\nconst maxAverageRatio = function(classes, extraStudents) {\n const pq = new PriorityQueue((a, b) => a.up > b.up);\n for (let x of classes) pq.push(new Node(x[0], x[1]));\n while (extraStudents--) {\n let temp = pq.peek();\n pq.pop();\n temp.pass++, temp.total++;\n temp.calUp();\n pq.push(temp);\n }\n let total = 0.0;\n let n = classes.length;\n while (!pq.isEmpty()) {\n let temp = pq.peek();\n pq.pop();\n total += temp.pass / temp.total;\n }\n return total / n;\n};\n\nclass Node {\n constructor(pass, total) {\n this.pass = pass\n this.total = total\n this.calUp()\n }\n calUp() {\n this.up = (this.pass + 1) / (this.total + 1) - this.pass / this.total\n }\n}\n\nclass PriorityQueue {\n constructor(comparator = (a, b) => a > b) {\n this.heap = []\n this.top = 0\n this.comparator = comparator\n }\n size() {\n return this.heap.length\n }\n isEmpty() {\n return this.size() === 0\n }\n peek() {\n return this.heap[this.top]\n }\n push(...values) {\n values.forEach((value) => {\n this.heap.push(value)\n this.siftUp()\n })\n return this.size()\n }\n pop() {\n const poppedValue = this.peek()\n const bottom = this.size() - 1\n if (bottom > this.top) {\n this.swap(this.top, bottom)\n }\n this.heap.pop()\n this.siftDown()\n return poppedValue\n }\n replace(value) {\n const replacedValue = this.peek()\n this.heap[this.top] = value\n this.siftDown()\n return replacedValue\n }\n\n parent = (i) => ((i + 1) >>> 1) - 1\n left = (i) => (i << 1) + 1\n right = (i) => (i + 1) << 1\n greater = (i, j) => this.comparator(this.heap[i], this.heap[j])\n swap = (i, j) => ([this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]])\n siftUp = () => {\n let node = this.size() - 1\n while (node > this.top && this.greater(node, this.parent(node))) {\n this.swap(node, this.parent(node))\n node = this.parent(node)\n }\n }\n siftDown = () => {\n let node = this.top\n while (\n (this.left(node) < this.size() && this.greater(this.left(node), node)) ||\n (this.right(node) < this.size() && this.greater(this.right(node), node))\n ) {\n let maxChild =\n this.right(node) < this.size() &&\n this.greater(this.right(node), this.left(node))\n ? this.right(node)\n : this.left(node)\n this.swap(node, maxChild)\n node = maxChild\n }\n }\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720e5d", + "questionid": 914, + "title": "Maximum Number of Groups Getting Fresh Donuts", + "slug": "maximum-number-of-groups-getting-fresh-donuts", + "description": "There is a donuts shop that bakes donuts in batches of batchSize. They have a rule where they must serve all of the donuts of a batch before serving any donuts of the next batch. You are given an integer batchSize and an integer array groups, where groups[i] denotes that there is a group of groups[i] customers that will visit the shop. Each customer will get exactly one donut. When a group visits the shop, all customers of the group must be served before serving any of the following groups. A group will be happy if they all get fresh donuts. That is, the first customer of the group does not receive a donut that was left over from the previous group. You can freely rearrange the ordering of the groups. Return the maximum possible number of happy groups after rearranging the groups. ", + "category": [ + "Array", + "Dynamic Programming", + "Bit Manipulation", + "Memoization", + "Bitmask" + ], + "complexity": "Hard", + "successrate": 39.9, + "totalsubmissions": 10493, + "totalaccepted": 4186, + "likes": 223, + "dislikes": 15, + "hints": "The maximum number of happy groups is the maximum number of partitions you can split the groups into such that the sum of group sizes in each partition is 0 mod batchSize. At most one partition is allowed to have a different remainder (the first group will get fresh donuts anyway). Suppose you have an array freq of length k where freq[i] = number of groups of size i mod batchSize. How can you utilize this in a dp solution? Make a DP state dp[freq][r] that represents \"the maximum number of partitions you can form given the current freq and current remainder r\". You can hash the freq array to store it more easily in the dp table. For each i from 0 to batchSize-1, the next DP state is dp[freq`][(r+i)%batchSize] where freq` is freq but with freq[i] decremented by 1. Take the largest of all of the next states and store it in ans. If r == 0, then return ans+1 (because you can form a new partition), otherwise return ans (continuing the current partition).", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "batchSize = 3, groups = [1,2,3,4,5,6]", + "expected_output": "4", + "explanation": "You can arrange the groups as [6,2,4,5,1,3]. Then the 1st, 2nd, 4th, and 6th groups will be happy." + }, + { + "example_num": 2, + "expected_input": "batchSize = 4, groups = [1,3,2,5,2,2,1,6]", + "expected_output": "4", + "explanation": "" + } + ], + "solution": "/**\n * @param {number} batchSize\n * @param {number[]} groups\n * @return {number}\n */\nconst maxHappyGroups = function (batchSize, groups) {\n const arr = new Array(batchSize + 1).fill(0)\n let result = 0\n // reduce group to groups of size group%n\n for (let gSize of groups) {\n arr[gSize % batchSize]++\n }\n\n // Only need 1 step\n result += arr[0]\n arr[0] = 0\n\n // Only need 2 step\n for (let i = 1; i < batchSize / 2; i++) {\n let min = Math.min(arr[i], arr[batchSize - i])\n arr[i] -= min\n arr[batchSize - i] -= min\n result += min\n }\n result += dfs(arr, 0, new Map())\n return result\n}\n\nfunction dfs(arr, remain, cache) {\n let n = arr.length - 1\n const key = arr.join(',')\n if (cache.has(key)) return cache.get(key)\n let result = 0\n // greedy and short cut when we can finish the current round\n if (remain > 0 && arr[n - remain] > 0) {\n arr[n - remain]--\n result = dfs(arr, 0, cache)\n arr[n - remain]++\n } else {\n for (let i = 1; i < arr.length; i++) {\n if (arr[i] > 0) {\n arr[i]--\n result = Math.max(\n result,\n dfs(arr, (remain + i) % n, cache) + (remain == 0 ? 1 : 0)\n )\n arr[i]++\n }\n }\n }\n cache.set(key, result)\n return result\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720e60", + "questionid": 917, + "title": "Minimum Operations to Make the Array Increasing", + "slug": "minimum-operations-to-make-the-array-increasing", + "description": "You are given an integer array nums (0-indexed). In one operation, you can choose an element of the array and increment it by 1. Return the minimum number of operations needed to make nums strictly increasing. An array nums is strictly increasing if nums[i] < nums[i+1] for all 0 <= i < nums.length - 1. An array of length 1 is trivially strictly increasing. ", + "category": [ + "Array", + "Greedy" + ], + "complexity": "Easy", + "successrate": 78.3, + "totalsubmissions": 52341, + "totalaccepted": 40963, + "likes": 569, + "dislikes": 30, + "hints": "nums[i+1] must be at least equal to nums[i] + 1. Think greedily. You don't have to increase nums[i+1] beyond nums[i]+1. Iterate on i and set nums[i] = max(nums[i-1]+1, nums[i]) .", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,1,1]", + "expected_output": "3", + "explanation": "You can do the following operations:\r\n1) Increment nums[2], so nums becomes [1,1,2].\r\n2) Increment nums[1], so nums becomes [1,2,2].\r\n3) Increment nums[2], so nums becomes [1,2,3]." + }, + { + "example_num": 2, + "expected_input": "nums = [1,5,2,4,1]", + "expected_output": "14", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "nums = [8]", + "expected_output": "0", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} nums\n * @return {number}\n */\nconst minOperations = function(nums) {\n let res = 0\n let pre = nums[0]\n for(let i = 1, n = nums.length; i < n; i++) {\n const e = nums[i]\n if(e <= pre) {\n res += pre - e + 1\n pre++\n } else {\n pre = e\n }\n }\n return res\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720e63", + "questionid": 920, + "title": "Finding the Users Active Minutes", + "slug": "finding-the-users-active-minutes", + "description": "You are given the logs for users' actions on LeetCode, and an integer k. The logs are represented by a 2D integer array logs where each logs[i] = [IDi, timei] indicates that the user with IDi performed an action at the minute timei. Multiple users can perform actions simultaneously, and a single user can perform multiple actions in the same minute. The user active minutes (UAM) for a given user is defined as the number of unique minutes in which the user performed an action on LeetCode. A minute can only be counted once, even if multiple actions occur during it. You are to calculate a 1-indexed array answer of size k such that, for each j (1 <= j <= k), answer[j] is the number of users whose UAM equals j. Return the array answer as described above. ", + "category": [ + "Array", + "Hash Table" + ], + "complexity": "Medium", + "successrate": 80.8, + "totalsubmissions": 40195, + "totalaccepted": 32468, + "likes": 410, + "dislikes": 157, + "hints": "Try to find the number of different minutes when action happened for each user. For each user increase the value of the answer array index which matches the UAM for this user.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "logs = [[0,5],[1,2],[0,2],[0,5],[1,3]], k = 5", + "expected_output": "[0,2,0,0,0]", + "explanation": "The user with ID=0 performed actions at minutes 5, 2, and 5 again. Hence, they have a UAM of 2 (minute 5 is only counted once).\nThe user with ID=1 performed actions at minutes 2 and 3. Hence, they have a UAM of 2.\nSince both users have a UAM of 2, answer[2] is 2, and the remaining answer[j] values are 0." + }, + { + "example_num": 2, + "expected_input": "logs = [[1,1],[2,2],[2,3]], k = 4", + "expected_output": "[1,1,0,0]", + "explanation": "The user with ID=1 performed a single action at minute 1. Hence, they have a UAM of 1.\nThe user with ID=2 performed actions at minutes 2 and 3. Hence, they have a UAM of 2.\nThere is one user with a UAM of 1 and one with a UAM of 2.\nHence, answer[1] = 1, answer[2] = 1, and the remaining values are 0." + } + ], + "solution": "/**\n * @param {number[][]} logs\n * @param {number} k\n * @return {number[]}\n */\nconst findingUsersActiveMinutes = function(logs, k) {\n const hash = {}, map = {}\n logs.forEach(l => {\n const [id, mi] = l\n if(hash[mi] == null) hash[mi] = new Set()\n if(map[id] == null) map[id] = new Set()\n hash[mi].add(id)\n map[id].add(mi)\n })\n\n const res = Array(k).fill(0)\n Object.keys(map).forEach(k => {\n const num = map[k].size\n res[num - 1]++\n })\n \n return res\n \n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720e67", + "questionid": 924, + "title": "Find XOR Sum of All Pairs Bitwise AND", + "slug": "find-xor-sum-of-all-pairs-bitwise-and", + "description": "The XOR sum of a list is the bitwise XOR of all its elements. If the list only contains one element, then its XOR sum will be equal to this element. You are given two 0-indexed arrays arr1 and arr2 that consist only of non-negative integers. Consider the list containing the result of arr1[i] AND arr2[j] (bitwise AND) for every (i, j) pair where 0 <= i < arr1.length and 0 <= j < arr2.length. Return the XOR sum of the aforementioned list. ", + "category": [ + "Array", + "Math", + "Bit Manipulation" + ], + "complexity": "Hard", + "successrate": 58.7, + "totalsubmissions": 17587, + "totalaccepted": 10326, + "likes": 306, + "dislikes": 32, + "hints": "Think about (a&b) ^ (a&c). Can you simplify this expression? It is equal to a&(b^c). Then, (arr1[i]&arr2[0])^(arr1[i]&arr2[1]).. = arr1[i]&(arr2[0]^arr2[1]^arr[2]...). Let arr2XorSum = (arr2[0]^arr2[1]^arr2[2]...), arr1XorSum = (arr1[0]^arr1[1]^arr1[2]...) so the final answer is (arr2XorSum&arr1[0]) ^ (arr2XorSum&arr1[1]) ^ (arr2XorSum&arr1[2]) ^ ... = arr2XorSum & arr1XorSum.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "arr1 = [1,2,3], arr2 = [6,5]", + "expected_output": "0", + "explanation": "The list = [1 AND 6, 1 AND 5, 2 AND 6, 2 AND 5, 3 AND 6, 3 AND 5] = [0,1,2,0,2,1].\nThe XOR sum = 0 XOR 1 XOR 2 XOR 0 XOR 2 XOR 1 = 0." + }, + { + "example_num": 2, + "expected_input": "arr1 = [12], arr2 = [4]", + "expected_output": "4", + "explanation": "The list = [12 AND 4] = [4]. The XOR sum = 4." + } + ], + "solution": "/**\n * @param {number[]} arr1\n * @param {number[]} arr2\n * @return {number}\n */\nconst getXORSum = function(arr1, arr2) {\n let a = 0, b = 0\n for(const e of arr1) a ^= e\n for(const e of arr2) b ^= e\n \n return a & b\n};\n\n\n// another\n\n// On every bit XOR acts as modulo 2 addition and AND acts as modulo 2 multiplication.\n// The set {0,1} with modulo 2 addition and multiplication is the field GF(2) and the distributive property holds in every field.\n\n/**\n * @param {number[]} arr1\n * @param {number[]} arr2\n * @return {number}\n */\nconst getXORSum = function(arr1, arr2) {\n const bits = Array(32).fill(0)\n for (let v of arr2) {\n let pos = 0;\n while (v > 0) {\n if (v & 1) {\n bits[pos]++;\n }\n v = v >> 1;\n pos++;\n }\n }\n\n let res = 0;\n\n for (let v of arr1) {\n let pos = 0;\n let 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// another\n\n/**\n * @param {number[]} arr1\n * @param {number[]} arr2\n * @return {number}\n */\nconst getXORSum = function(arr1, arr2) {\n let x1 = arr1[0], x2 = arr2[0]\n for(let i = 1; i < arr1.length; i++) x1 ^= arr1[i]\n for(let i = 1; i < arr2.length; i++) x2 ^= arr2[i]\n return x1 & x2\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720e68", + "questionid": 925, + "title": "Sum of Digits in Base K", + "slug": "sum-of-digits-in-base-k", + "description": "Given an integer n (in base 10) and a base k, return the sum of the digits of n after converting n from base 10 to base k. After converting, each digit should be interpreted as a base 10 number, and the sum should be returned in base 10. ", + "category": [ + "Math" + ], + "complexity": "Easy", + "successrate": 76.4, + "totalsubmissions": 35662, + "totalaccepted": 27239, + "likes": 282, + "dislikes": 24, + "hints": "Convert the given number into base k. Use mod-10 to find what each digit is after the conversion and sum the digits.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 34, k = 6", + "expected_output": "9\nExplanation: 34 (base 10) expressed in base 6 is 54. 5 + 4 = 9.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "n = 10, k = 10", + "expected_output": "1\nExplanation: n is already in base 10. 1 + 0 = 1.", + "explanation": "" + } + ], + "solution": "/**\n * @param {number} n\n * @param {number} k\n * @return {number}\n */\nconst sumBase = function(n, k) {\n let str = n.toString(k)\n let res = 0\n for(let ch of str) res += +ch\n \n return res\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720e69", + "questionid": 926, + "title": "Frequency of the Most Frequent Element", + "slug": "frequency-of-the-most-frequent-element", + "description": "The frequency of an element is the number of times it occurs in an array. You are given an integer array nums and an integer k. In one operation, you can choose an index of nums and increment the element at that index by 1. Return the maximum possible frequency of an element after performing at most k operations. ", + "category": [ + "Array", + "Binary Search", + "Greedy", + "Sliding Window", + "Sorting", + "Prefix Sum" + ], + "complexity": "Medium", + "successrate": 36.6, + "totalsubmissions": 56651, + "totalaccepted": 20716, + "likes": 1162, + "dislikes": 24, + "hints": "Note that you can try all values in a brute force manner and find the maximum frequency of that value. To find the maximum frequency of a value consider the biggest elements smaller than or equal to this value", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,2,4], k = 5", + "expected_output": "3\nExplanation: Increment the first element three times and the second element two times to make nums = [4,4,4].\n4 has a frequency of 3.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "nums = [1,4,8,13], k = 5", + "expected_output": "2", + "explanation": "There are multiple optimal solutions:\n- Increment the first element three times to make nums = [4,4,8,13]. 4 has a frequency of 2.\n- Increment the second element four times to make nums = [1,8,8,13]. 8 has a frequency of 2.\n- Increment the third element five times to make nums = [1,4,13,13]. 13 has a frequency of 2." + }, + { + "example_num": 3, + "expected_input": "nums = [3,9,6], k = 2", + "expected_output": "1", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} nums\n * @param {number} k\n * @return {number}\n */\nconst maxFrequency = function(nums, k) {\n nums.sort((a, b) => a - b)\n let res = 1\n const n = nums.length\n let i = 0, sum = 0\n for(let j = 1; j < n; j++) {\n const e = nums[j]\n const delta = e - nums[j - 1]\n sum += (j - i) * delta\n while(sum > k) {\n sum -= e - nums[i]\n i++\n }\n res = Math.max(res, j - i + 1)\n }\n \n\n return res\n};\n\n// another\n\n\n/**\n * @param {number[]} nums\n * @param {number} k\n * @return {number}\n */\nconst maxFrequency = function(nums, k) {\n let res = 1, i = 0, j = 0, sum = 0\n const n = nums.length\n nums.sort((a, b) => a - b)\n for(j = 0; j < n; j++) {\n sum += nums[j]\n while(sum + k < (j - i + 1) * nums[j]) {\n sum -= nums[i]\n i++\n }\n res = Math.max(res, j - i + 1)\n } \n return res\n};\n\n// another\n\n/**\n * @param {number[]} nums\n * @param {number} k\n * @return {number}\n */\nconst maxFrequency = function(nums, k) {\n nums.sort((a, b) => a - b)\n let i = 0, sum = 0, res = 1\n for(let j = 0; j < nums.length; j++) {\n sum += nums[j]\n while(sum + k < (j - i + 1) * nums[j]) {\n sum -= nums[i]\n i++\n }\n res = Math.max(res, j - i + 1)\n }\n return res\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720e6c", + "questionid": 929, + "title": "Minimum Distance to the Target Element", + "slug": "minimum-distance-to-the-target-element", + "description": "Given an integer array nums (0-indexed) and two integers target and start, find an index i such that nums[i] == target and abs(i - start) is minimized. Note that\u00a0abs(x)\u00a0is the absolute value of x. Return abs(i - start). It is guaranteed that target exists in nums. ", + "category": [ + "Array" + ], + "complexity": "Easy", + "successrate": 59.7, + "totalsubmissions": 41147, + "totalaccepted": 24574, + "likes": 172, + "dislikes": 39, + "hints": "Loop in both directions until you find the target element. For each index i such that nums[i] == target calculate abs(i - start).", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,2,3,4,5], target = 5, start = 3", + "expected_output": "1", + "explanation": "nums[4] = 5 is the only value equal to target, so the answer is abs(4 - 3) = 1." + }, + { + "example_num": 2, + "expected_input": "nums = [1], target = 1, start = 0", + "expected_output": "0", + "explanation": "nums[0] = 1 is the only value equal to target, so the answer is abs(0 - 0) = 0." + }, + { + "example_num": 3, + "expected_input": "nums = [1,1,1,1,1,1,1,1,1,1], target = 1, start = 0", + "expected_output": "0", + "explanation": "Every value of nums is 1, but nums[0] minimizes abs(i - start), which is abs(0 - 0) = 0." + } + ], + "solution": "/**\n * @param {number[]} nums\n * @param {number} target\n * @param {number} start\n * @return {number}\n */\nconst getMinDistance = function(nums, target, start) {\n let min = Infinity, res = -1\n for(let i = 0; i < nums.length; i++) {\n if(nums[i] === target) {\n if(min > Math.abs(i - start)) {\n res = i\n min = Math.abs(i - start)\n }\n }\n }\n \n return min\n \n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720e6f", + "questionid": 932, + "title": "Minimum Adjacent Swaps to Reach the Kth Smallest Number", + "slug": "minimum-adjacent-swaps-to-reach-the-kth-smallest-number", + "description": "You are given a string num, representing a large integer, and an integer k. We call some integer wonderful if it is a permutation of the digits in num and is greater in value than num. There can be many wonderful integers. However, we only care about the smallest-valued ones. Return the minimum number of adjacent digit swaps that needs to be applied to num to reach the kth smallest wonderful integer. The tests are generated in such a way that kth\u00a0smallest wonderful integer exists. ", + "category": [ + "Two Pointers", + "String", + "Greedy" + ], + "complexity": "Medium", + "successrate": 72.1, + "totalsubmissions": 19150, + "totalaccepted": 13807, + "likes": 443, + "dislikes": 56, + "hints": "Find the next permutation of the given string k times. Try to move each element to its correct position and calculate the number of steps.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "num = "5489355142", k = 4", + "expected_output": "2", + "explanation": "The 4th smallest wonderful number is "5489355421". To get this number:\n- Swap index 7 with index 8: "5489355142" -> "5489355412"\n- Swap index 8 with index 9: "5489355412" -> "5489355421"" + }, + { + "example_num": 2, + "expected_input": "num = "11112", k = 4", + "expected_output": "4", + "explanation": "The 4th smallest wonderful number is "21111". To get this number:\n- Swap index 3 with index 4: "11112" -> "11121"\n- Swap index 2 with index 3: "11121" -> "11211"\n- Swap index 1 with index 2: "11211" -> "12111"\n- Swap index 0 with index 1: "12111" -> "21111"" + }, + { + "example_num": 3, + "expected_input": "num = "00123", k = 1", + "expected_output": "1", + "explanation": "The 1st smallest wonderful number is "00132". To get this number:\n- Swap index 3 with index 4: "00123" -> "00132"" + } + ], + "solution": "/**\n * @param {string} num\n * @param {number} k\n * @return {number}\n */\n const getMinSwaps = function (num, k) {\n const temp = num.split('')\n for (let i = 0; i < k; i++) nextPermutation(temp)\n return count(num.split(''), temp, temp.length)\n}\n\nfunction nextPermutation(a) {\n let i = a.length - 2\n //Find the first element which isn't in increasing order fom behind\n while (i >= 0 && a[i] >= a[i + 1]) i--\n //If we found an element\n if (i >= 0) {\n // Find the rightmost element such that a[j] > a[i]\n const j = bSearch(a, i + 1, a.length - 1, a[i])\n // swap a[i] and a[j]\n a[i] = a[i] ^ a[j] ^ (a[j] = a[i])\n }\n //reverse array from i + 1 till end\n reverse(a, i + 1, a.length - 1)\n}\n\nfunction bSearch(a, i, j, key) {\n while (i <= j) {\n const mid = (i + j) >>> 1\n if (key < a[mid]) i = mid + 1\n else j = mid - 1\n }\n return i - 1\n}\n\nfunction reverse(a, i, j) {\n while (i < j) a[i] = a[i] ^ a[j] ^ (a[j--] = a[i++])\n}\n\nfunction count(s1, s2, n) {\n let i = 0,\n j = 0,\n res = 0\n\n while (i < n) {\n j = i\n while (s1[j] != s2[i]) j++\n while (i < j) {\n const temp = s1[j]\n s1[j] = s1[j - 1]\n s1[j-- - 1] = temp\n ++res\n }\n ++i\n }\n return res\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720e70", + "questionid": 933, + "title": "Maximum Population Year", + "slug": "maximum-population-year", + "description": "You are given a 2D integer array logs where each logs[i] = [birthi, deathi] indicates the birth and death years of the ith person. The population of some year x is the number of people alive during that year. The ith person is counted in year x's population if x is in the inclusive range [birthi, deathi - 1]. Note that the person is not counted in the year that they die. Return the earliest year with the maximum population. ", + "category": [ + "Array", + "Counting" + ], + "complexity": "Easy", + "successrate": 58.6, + "totalsubmissions": 49364, + "totalaccepted": 28951, + "likes": 539, + "dislikes": 77, + "hints": "For each year find the number of people whose birth_i \u2030\u00a4 year and death_i > year. Find the maximum value between all years.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "logs = [[1993,1999],[2000,2010]]", + "expected_output": "1993", + "explanation": "The maximum population is 1, and 1993 is the earliest year with this population." + }, + { + "example_num": 2, + "expected_input": "logs = [[1950,1961],[1960,1971],[1970,1981]]", + "expected_output": "1960", + "explanation": "The maximum population is 2, and it had happened in years 1960 and 1970.\nThe earlier year between them is 1960." + } + ], + "solution": "/**\n * @param {number[][]} logs\n * @return {number}\n */\nconst maximumPopulation = function(logs) {\n const n = logs.length\n const arr = Array(101).fill(0)\n const base = 1950\n for(let log of logs) {\n const [start, end] = log\n arr[start - base]++\n arr[end - base]--\n }\n \n let res = 0, tmp = -Infinity\n for(let i = 1; i < 101; i++) {\n arr[i] += arr[i - 1]\n }\n for(let i = 0; i < 101; i++) {\n if(arr[i] > tmp) {\n res = i\n tmp = arr[i]\n }\n }\n return res + base\n};\n\n\n// another\n\n/**\n * @param {number[][]} logs\n * @return {number}\n */\nconst maximumPopulation = function(logs) {\n logs.sort((a, b) => {\n if(a[0] === b[0]) return a[1] - b[1]\n return a[0] - b[0]\n })\n const arr = Array(101).fill(0)\n const bit = new FenwickTree(101)\n for(let i = 0, len = logs.length; i < len; i++) {\n const [start, end] = logs[i]\n const idx = start - 1950\n bit.update(idx + 1, 1)\n }\n for(let i = 0, len = logs.length; i < len; i++) {\n const [start, end] = logs[i]\n const idx = end - 1950\n bit.update(idx + 1, -1)\n }\n let max = 0\n for(let i = 1; i <= 101; i++) {\n max = Math.max(max, bit.query(i))\n }\n let tmp\n for(let i = 1; i <= 101; i++) {\n if(bit.query(i) === max) {\n tmp = i\n break\n }\n }\n \n return 1950 + tmp - 1\n};\n\nconst lowBit = (x) => x & -x\nclass FenwickTree {\n constructor(n) {\n if (n < 1) return\n this.sum = Array(n + 1).fill(0)\n }\n update(i, delta) {\n if (i < 1) return\n while (i < this.sum.length) {\n this.sum[i] += delta\n i += lowBit(i)\n }\n }\n query(i) {\n if (i < 1) return\n let sum = 0\n while (i > 0) {\n sum += this.sum[i]\n i -= lowBit(i)\n }\n return sum\n }\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720e71", + "questionid": 934, + "title": "Maximum Distance Between a Pair of Values", + "slug": "maximum-distance-between-a-pair-of-values", + "description": "You are given two non-increasing 0-indexed integer arrays nums1 and nums2. A pair of indices (i, j), where 0 <= i < nums1.length and 0 <= j < nums2.length, is valid if both i <= j and nums1[i] <= nums2[j]. The distance of the pair is j - i. Return the maximum distance of any valid pair (i, j). If there are no valid pairs, return 0. An array arr is non-increasing if arr[i-1] >= arr[i] for every 1 <= i < arr.length. ", + "category": [ + "Array", + "Two Pointers", + "Binary Search", + "Greedy" + ], + "complexity": "Medium", + "successrate": 50, + "totalsubmissions": 43219, + "totalaccepted": 21602, + "likes": 564, + "dislikes": 11, + "hints": "Since both arrays are sorted in a non-increasing way this means that for each value in the first array. We can find the farthest value smaller than it using binary search. There is another solution using a two pointers approach since the first array is non-increasing the farthest j such that nums2[j] \u2030\u00a5 nums1[i] is at least as far as the farthest j such that nums2[j] \u2030\u00a5 nums1[i-1]", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums1 = [55,30,5,4,2], nums2 = [100,20,10,10,5]", + "expected_output": "2", + "explanation": "The valid pairs are (0,0), (2,2), (2,3), (2,4), (3,3), (3,4), and (4,4).\nThe maximum distance is 2 with pair (2,4)." + }, + { + "example_num": 2, + "expected_input": "nums1 = [2,2,2], nums2 = [10,10,1]", + "expected_output": "1", + "explanation": "The valid pairs are (0,0), (0,1), and (1,1).\nThe maximum distance is 1 with pair (0,1)." + }, + { + "example_num": 3, + "expected_input": "nums1 = [30,29,19,5], nums2 = [25,25,25,25,25]", + "expected_output": "2", + "explanation": "The valid pairs are (2,2), (2,3), (2,4), (3,3), and (3,4).\nThe maximum distance is 2 with pair (2,4)." + } + ], + "solution": "/**\n * @param {number[]} nums1\n * @param {number[]} nums2\n * @return {number}\n */\nconst maxDistance = function(nums1, nums2) {\n let res = 0\n const m = nums1.length, n = nums2.length\n for(let i = 0; i < m; i++) {\n const idx = bSearch(nums2, i, n - 1, nums1[i])\n res = Math.max(res, idx - i)\n }\n return res\n};\n\nfunction bSearch(a, i, j, key) {\n while (i <= j) {\n let mid = (i + j) >>> 1\n if (key <= a[mid]) i = mid + 1\n else if(key > a[mid]) j = mid - 1\n }\n return i - 1\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720e72", + "questionid": 935, + "title": "Maximum Subarray Min-Product", + "slug": "maximum-subarray-min-product", + "description": "The min-product of an array is equal to the minimum value in the array multiplied by the array's sum. Given an array of integers nums, return the maximum min-product of any non-empty subarray of nums. Since the answer may be large, return it modulo 109 + 7. Note that the min-product should be maximized before performing the modulo operation. Testcases are generated such that the maximum min-product without modulo will fit in a 64-bit signed integer. A subarray is a contiguous part of an array. ", + "category": [ + "Array", + "Stack", + "Monotonic Stack", + "Prefix Sum" + ], + "complexity": "Medium", + "successrate": 35.4, + "totalsubmissions": 33411, + "totalaccepted": 11814, + "likes": 745, + "dislikes": 43, + "hints": "Is there a way we can sort the elements to simplify the problem? Can we find the maximum min-product for every value in the array?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,2,3,2]", + "expected_output": "14", + "explanation": "The maximum min-product is achieved with the subarray [2,3,2] (minimum value is 2).\n2 * (2+3+2) = 2 * 7 = 14." + }, + { + "example_num": 2, + "expected_input": "nums = [2,3,3,1,2]", + "expected_output": "18", + "explanation": "The maximum min-product is achieved with the subarray [3,3] (minimum value is 3).\n3 * (3+3) = 3 * 6 = 18." + }, + { + "example_num": 3, + "expected_input": "nums = [3,1,5,6,4,2]", + "expected_output": "60", + "explanation": "The maximum min-product is achieved with the subarray [5,6,4] (minimum value is 4).\n4 * (5+6+4) = 4 * 15 = 60." + } + ], + "solution": "/**\n * @param {number[]} nums\n * @return {number}\n */\nconst maxSumMinProduct = function(nums) {\n const n = nums.length, left = Array(n).fill(0), right = Array(n).fill(n - 1)\n const mod = BigInt(1e9 + 7)\n let res = 0n\n let stk = []\n for(let i = 0; i < n; i++) {\n while(stk.length && nums[stk[stk.length - 1]] >= nums[i]) {\n stk.pop()\n }\n left[i] = stk.length ? stk[stk.length - 1] + 1 : 0\n stk.push(i)\n }\n \n stk = []\n for(let i = n - 1; i >= 0; i--) {\n while(stk.length && nums[stk[stk.length - 1]] >= nums[i]) {\n stk.pop()\n }\n right[i] = stk.length ? stk[stk.length - 1] - 1 : n - 1\n stk.push(i)\n }\n \n const preSum = []\n for(let i = 0; i < n; i++) {\n preSum[i] = (i === 0 ? 0n : preSum[i - 1]) + BigInt(nums[i])\n }\n for(let i = 0; i < n; i++) {\n res = max(res, fn(nums[i], left[i], right[i]))\n }\n \n return res % mod\n \n function max(a, b) {\n return a > b ? a : b\n }\n function fn(v, l, r) {\n return BigInt(v) * (l === 0 ? preSum[r] : preSum[r] - preSum[l - 1])\n }\n};\n\n// another\n\n\n/**\n * @param {number[]} nums\n * @return {number}\n */\nconst maxSumMinProduct = function (nums) {\n const n = nums.length\n const mod = BigInt(10 ** 9 + 7)\n const preSum = Array(n + 1).fill(0n)\n for (let i = 0; i < n; i++) {\n preSum[i + 1] = preSum[i] + BigInt(nums[i])\n }\n const l = Array(n).fill(0) // l[i] stores index of farthest element greater or equal to nums[i]\n const r = Array(n).fill(0) // r[i] stores index of farthest element greater or equal to nums[i]\n let st = []\n\n for (let i = 0; i < n; i++) {\n while (st.length && nums[st[st.length - 1]] >= nums[i]) st.pop()\n if (st.length) l[i] = st[st.length - 1] + 1\n else l[i] = 0\n st.push(i)\n }\n \n st = []\n for (let i = n - 1; i >= 0; i--) {\n while (st.length && nums[st[st.length - 1]] >= nums[i]) st.pop()\n if (st.length) r[i] = st[st.length - 1] - 1\n else r[i] = n - 1\n st.push(i)\n }\n function getSum(left, right) {\n // inclusive\n return preSum[right + 1] - preSum[left]\n }\n\n let maxProduct = 0n\n for (let i = 0; i < n; i++) {\n maxProduct = bigint_max(maxProduct, BigInt(nums[i]) * getSum(l[i], r[i]))\n }\n return maxProduct % mod\n}\nfunction bigint_max(...args){\n if (args.length < 1){ throw 'Max of empty list'; }\n m = args[0];\n args.forEach(a=>{if (a > m) {m = a}});\n return m;\n}\n\n// another\n\n/**\n * @param {number[]} nums\n * @return {number}\n */\nconst maxSumMinProduct = function(nums) {\n const n = nums.length, s1 = [], s2 = [],\n left = Array(n), right = Array(n), mod = BigInt(1e9 + 7)\n for(let i = 0; i < n; i++) {\n while(s1.length && nums[s1[s1.length - 1]] >= nums[i]) s1.pop()\n if(s1.length) left[i] = s1[s1.length - 1] + 1\n else left[i] = 0\n s1.push(i)\n }\n \n for(let i = n - 1; i >= 0; i--) {\n while(s2.length && nums[s2[s2.length - 1]] >= nums[i]) s2.pop()\n if(s2.length) right[i] = s2[s2.length - 1] - 1\n else right[i] = n - 1\n s2.push(i)\n }\n \n const preSum = Array(n)\n for(let i = 0; i < n; i++) {\n preSum[i] = (i === 0 ? 0n : preSum[i - 1]) + BigInt(nums[i])\n }\n let res = 0n\n for(let i = 0; i < n; i++) {\n res = max(res, getSum(preSum, left[i], right[i]) * BigInt(nums[i]))\n }\n return res % mod\n \n};\n\nfunction getSum(arr, l, r) {\n return arr[r] - (l === 0 ? 0n : arr[l - 1])\n}\n\nfunction max(...args) {\n let res = -Infinity\n for(let e of args) {\n if(e > res) res = e\n }\n return res\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720e74", + "questionid": 937, + "title": "Substrings of Size Three with Distinct Characters", + "slug": "substrings-of-size-three-with-distinct-characters", + "description": "A string is good if there are no repeated characters. Given a string s, return the number of good substrings of length three in s. Note that if there are multiple occurrences of the same substring, every occurrence should be counted. A substring is a contiguous sequence of characters in a string. ", + "category": [ + "Hash Table", + "String", + "Sliding Window", + "Counting" + ], + "complexity": "Easy", + "successrate": 69.7, + "totalsubmissions": 57457, + "totalaccepted": 40059, + "likes": 556, + "dislikes": 19, + "hints": "Try using a set to find out the number of distinct characters in a substring.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "xyzzaz"", + "expected_output": "1", + "explanation": "There are 4 substrings of size 3: "xyz", "yzz", "zza", and "zaz". \nThe only good substring of length 3 is "xyz"." + }, + { + "example_num": 2, + "expected_input": "s = "aababcabc"", + "expected_output": "4", + "explanation": "There are 7 substrings of size 3: "aab", "aba", "bab", "abc", "bca", "cab", and "abc".\nThe good substrings are "abc", "bca", "cab", and "abc"." + } + ], + "solution": "/**\n * @param {string} s\n * @return {number}\n */\n const countGoodSubstrings = function(s) {\n let res = 0\n for(let i = 2; i < s.length; i++) {\n if(chk(s, i)) res++\n }\n \n return res\n};\n\nfunction chk(s, i) {\n return s[i - 2] !== s[i - 1] &&\n s[i - 2] !== s[i] &&\n s[i - 1] !== s[i]\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720e75", + "questionid": 938, + "title": "Minimum XOR Sum of Two Arrays", + "slug": "minimum-xor-sum-of-two-arrays", + "description": "You are given two integer arrays nums1 and nums2 of length n. The XOR sum of the two integer arrays is (nums1[0] XOR nums2[0]) + (nums1[1] XOR nums2[1]) + ... + (nums1[n - 1] XOR nums2[n - 1]) (0-indexed). Rearrange the elements of nums2 such that the resulting XOR sum is minimized. Return the XOR sum after the rearrangement. ", + "category": [ + "Array", + "Dynamic Programming", + "Bit Manipulation", + "Bitmask" + ], + "complexity": "Hard", + "successrate": 42.2, + "totalsubmissions": 18212, + "totalaccepted": 7684, + "likes": 401, + "dislikes": 8, + "hints": "Since n <= 14, we can consider every subset of nums2. We can represent every subset of nums2 using bitmasks.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums1 = [1,2], nums2 = [2,3]", + "expected_output": "2\nExplanation: Rearrange nums2 so that it becomes [3,2].\nThe XOR sum is (1 XOR 3) + (2 XOR 2) = 2 + 0 = 2.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "nums1 = [1,0,3], nums2 = [5,3,4]", + "expected_output": "8\nExplanation: Rearrange nums2 so that it becomes [5,4,3]. \nThe XOR sum is (1 XOR 5) + (0 XOR 4) + (3 XOR 3) = 4 + 4 + 0 = 8.", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} nums1\n * @param {number[]} nums2\n * @return {number}\n */\nconst minimumXORSum = function (nums1, nums2) {\n const n = nums1.length\n const limit = 1 << n\n const dp = Array(limit).fill(Infinity)\n dp[0] = 0\n for (let mask = 1; mask < limit; ++mask) {\n for (let i = 0; i < n; ++i) {\n if ((mask >> i) & 1) {\n dp[mask] = Math.min(\n dp[mask],\n dp[mask ^ (1 << i)] + (nums1[bitCnt(mask) - 1] ^ nums2[i])\n )\n }\n }\n }\n return dp[limit - 1]\n}\n\nfunction bitCnt(num) {\n let res = 0\n while (num) {\n res++\n num = num & (num - 1)\n }\n\n return res\n}\n\n\n// another\n\n/**\n * @param {number[]} nums1\n * @param {number[]} nums2\n * @return {number}\n */\nconst minimumXORSum = function (nums1, nums2) {\n const n = nums1.length, dp = Array(1 << n).fill(Infinity)\n return dfs(0, 0)\n function dfs(i, mask) {\n if(i === n) return 0\n if(dp[mask] !== Infinity) return dp[mask]\n for(let j = 0; j < n; j++) {\n if((mask & (1 << j)) === 0) {\n dp[mask] = Math.min(\n dp[mask], \n (nums1[i] ^ nums2[j]) + dfs(i + 1, mask | (1 << j))\n )\n }\n }\n return dp[mask]\n }\n}\n\n// another\n\n/**\n * @param {number[]} nums1\n * @param {number[]} nums2\n * @return {number}\n */\nconst minimumXORSum = function(nums1, nums2) {\n const dp = Array(1 << nums2.length).fill(Infinity)\n return dfs(dp, nums1, nums2, 0, 0)\n};\n\nfunction dfs(dp, a, b, i, mask) {\n if(i >= a.length) return 0\n if(dp[mask] === Infinity) {\n for(let j = 0; j < b.length; j++) {\n if((mask & (1 << j)) === 0) {\n dp[mask] = Math.min(dp[mask], (a[i] ^ b[j]) + dfs(dp, a, b, i + 1, mask + (1 << j)))\n }\n }\n }\n return dp[mask]\n}\n\n// another\n\n/**\n * @param {number[]} nums1\n * @param {number[]} nums2\n * @return {number}\n */\nconst minimumXORSum = function (nums1, nums2) {\n const dp = Array(1 << nums2.length).fill(Infinity)\n return dfs(0, 0)\n \n function dfs(i, mask) {\n if(i >= nums2.length) return 0\n if(dp[mask] != Infinity) return dp[mask]\n for(let j = 0; j < nums2.length; j++) {\n if((mask & (1 << j)) === 0) {\n dp[mask] = Math.min(dp[mask], (nums1[i] ^ nums2[j]) + dfs(i + 1, mask + (1 << j)) ) \n }\n } \n return dp[mask]\n }\n}\n\n// another\n\n/**\n * @param {number[]} nums1\n * @param {number[]} nums2\n * @return {number}\n */\nconst minimumXORSum = function (nums1, nums2) {\n const n = nums1.length, dp = Array(1 << n).fill(Infinity)\n return dfs(0, 0)\n\n function dfs(i, mask) {\n if(i >= n) return 0\n if(dp[mask] !== Infinity) return dp[mask]\n for(let j = 0; j < n; j++) {\n if((mask & (1 << j)) === 0) {\n dp[mask] = Math.min(dp[mask], (nums1[i] ^ nums2[j]) + dfs(i + 1, mask | (1 << j)))\n }\n }\n return dp[mask]\n }\n}\n\n" + }, + { + "_id": "66f925ddfdfb8e1665720e77", + "questionid": 940, + "title": "Number of Ways to Rearrange Sticks With K Sticks Visible", + "slug": "number-of-ways-to-rearrange-sticks-with-k-sticks-visible", + "description": "There are n uniquely-sized sticks whose lengths are integers from 1 to n. You want to arrange the sticks such that exactly k\u00a0sticks are visible from the left. A stick\u00a0is visible from the left if there are no longer\u00a0sticks to the left of it. Given n and k, return the number of such arrangements. Since the answer may be large, return it modulo 109 + 7. ", + "category": [ + "Math", + "Dynamic Programming", + "Combinatorics" + ], + "complexity": "Hard", + "successrate": 55.3, + "totalsubmissions": 14390, + "totalaccepted": 7953, + "likes": 437, + "dislikes": 10, + "hints": "Is there a way to build the solution from a base case? How many ways are there if we fix the position of one stick?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 3, k = 2", + "expected_output": "3", + "explanation": "[1,3,2], [2,3,1], and [2,1,3] are the only arrangements such that exactly 2 sticks are visible.\nThe visible sticks are underlined." + }, + { + "example_num": 2, + "expected_input": "n = 5, k = 5", + "expected_output": "1", + "explanation": "[1,2,3,4,5] is the only arrangement such that all 5 sticks are visible.\nThe visible sticks are underlined." + }, + { + "example_num": 3, + "expected_input": "n = 20, k = 11", + "expected_output": "647427950", + "explanation": "There are 647427950 (mod 109 + 7) ways to rearrange the sticks such that exactly 11 sticks are visible." + } + ], + "solution": "/**\n * @param {number} n\n * @param {number} k\n * @return {number}\n */\nconst rearrangeSticks = function(n, k) {\n const mod = BigInt(1e9 + 7)\n const g = Array.from({ length: 1001 }, () => Array(1001).fill(0n))\n g[1][1] = 1n\n for(let i = 2; i <= 1000; i++) {\n for(let j = 1; j <= i; j++ ) {\n g[i][j] = (g[i - 1][j - 1] + BigInt(i - 1) * g[i - 1][j] % mod) % mod\n }\n }\n return g[n][k]\n};\n\n// another\n\n/**\n * @param {number} n\n * @param {number} k\n * @return {number}\n */\nconst rearrangeSticks = function(n, k) {\n const MOD = 1e9 + 7;\n // first # can be smallest # in which case we recurse for (n - 1, k - 1) \n // or it can not be and smallest can be in any of n - 1 otehr positions for recursed(n - 1, k)\n const dp = new Array(n + 1).fill().map( _ => new Array(k + 1).fill(0) );\n for (let i = 1; i <= n; ++i) {\n for (let j = 1; j <= k; ++j) {\n if (j === i) {\n dp[i][j] = 1;\n } else if (j < i) {\n dp[i][j] = (dp[i - 1][j - 1] + (i - 1) * dp[i - 1][j]) % MOD;\n }\n }\n }\n return dp[n][k] % MOD;\n \n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720e78", + "questionid": 941, + "title": "Longer Contiguous Segments of Ones than Zeros", + "slug": "longer-contiguous-segments-of-ones-than-zeros", + "description": "Given a binary string s, return true if the longest contiguous segment of 1's is strictly longer than the longest contiguous segment of 0's in s, or return false otherwise. Note that if there are no 0's, then the longest continuous segment of 0's is considered to have a length 0. The same applies if there is no 1's. ", + "category": [ + "String" + ], + "complexity": "Easy", + "successrate": 60.3, + "totalsubmissions": 46660, + "totalaccepted": 28113, + "likes": 281, + "dislikes": 6, + "hints": "Check every possible segment of 0s and 1s. Is there a way to iterate through the string to keep track of the current character and its count?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "1101"", + "expected_output": "true", + "explanation": "The longest contiguous segment of 1s has length 2: "1101"\nThe longest contiguous segment of 0s has length 1: "1101"\nThe segment of 1s is longer, so return true." + }, + { + "example_num": 2, + "expected_input": "s = "111000"", + "expected_output": "false", + "explanation": "The longest contiguous segment of 1s has length 3: "111000"\nThe longest contiguous segment of 0s has length 3: "111000"\nThe segment of 1s is not longer, so return false." + }, + { + "example_num": 3, + "expected_input": "s = "110100010"", + "expected_output": "false", + "explanation": "The longest contiguous segment of 1s has length 2: "110100010"\nThe longest contiguous segment of 0s has length 3: "110100010"\nThe segment of 1s is not longer, so return false." + } + ], + "solution": "/**\n * @param {string} s\n * @return {boolean}\n */\nconst checkZeroOnes = function(s) {\n const stack = []\n let zl = 0, ol = 0\n for(let e of s) {\n let tmp = 0, zo = ''\n while(stack.length && stack[stack.length - 1] !== e) {\n if(zo === '') zo = stack[stack.length - 1]\n tmp++\n stack.pop()\n }\n if(zo === '1') ol = Math.max(tmp, ol)\n if(zo === '0') zl = Math.max(tmp, zl)\n stack.push(e)\n } \n if(stack.length) {\n let zo = stack[stack.length - 1]\n if(zo === '1') ol = Math.max(stack.length, ol)\n if(zo === '0') zl = Math.max(stack.length, zl)\n }\n return ol > zl\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720e79", + "questionid": 942, + "title": "Minimum Speed to Arrive on Time", + "slug": "minimum-speed-to-arrive-on-time", + "description": "You are given a floating-point number hour, representing the amount of time you have to reach the office. To commute to the office, you must take n trains in sequential order. You are also given an integer array dist of length n, where dist[i] describes the distance (in kilometers) of the ith train ride. Each train can only depart at an integer hour, so you may need to wait in between each train ride. Return the minimum positive integer speed (in kilometers per hour) that all the trains must travel at for you to reach the office on time, or -1 if it is impossible to be on time. Tests are generated such that the answer will not exceed 107 and hour will have at most two digits after the decimal point. ", + "category": [ + "Array", + "Binary Search" + ], + "complexity": "Medium", + "successrate": 35.6, + "totalsubmissions": 49620, + "totalaccepted": 17647, + "likes": 459, + "dislikes": 76, + "hints": "Given the speed the trains are traveling at, can you find the total time it takes for you to arrive? Is there a cutoff where any speeds larger will always allow you to arrive on time?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "dist = [1,3,2], hour = 6", + "expected_output": "1\nExplanation: At speed 1:\n- The first train ride takes 1/1 = 1 hour.\n- Since we are already at an integer hour, we depart immediately at the 1 hour mark. The second train takes 3/1 = 3 hours.\n- Since we are already at an integer hour, we depart immediately at the 4 hour mark. The third train takes 2/1 = 2 hours.\n- You will arrive at exactly the 6 hour mark.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "dist = [1,3,2], hour = 2.7", + "expected_output": "3\nExplanation: At speed 3:\n- The first train ride takes 1/3 = 0.33333 hours.\n- Since we are not at an integer hour, we wait until the 1 hour mark to depart. The second train ride takes 3/3 = 1 hour.\n- Since we are already at an integer hour, we depart immediately at the 2 hour mark. The third train takes 2/3 = 0.66667 hours.\n- You will arrive at the 2.66667 hour mark.", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "dist = [1,3,2], hour = 1.9", + "expected_output": "-1", + "explanation": "It is impossible because the earliest the third train can depart is at the 2 hour mark." + } + ], + "solution": "/**\n * @param {number[]} dist\n * @param {number} hour\n * @return {number}\n */\nconst minSpeedOnTime = function(dist, hour) {\n let n = dist.length, l = 1, r = 1e7 + 1\n while(l < r) {\n const mid = l + ((r - l) >> 1)\n let time = 0\n for(let i = 0; i < n - 1; i++) time += Math.ceil(dist[i] / mid)\n time += dist[dist.length - 1] / mid\n if(time > hour) l = mid + 1\n else r = mid\n }\n return l > 1e7 ? -1 : l\n};\n\n// another\n\n/**\n * @param {number[]} dist\n * @param {number} hour\n * @return {number}\n */\nconst minSpeedOnTime = function(dist, hour) {\n let l = 1, r = 1e7\n while(l <= r) {\n let mid = (l + r) >> 1\n if(valid(mid)) r = mid -1\n else l = mid + 1\n }\n return l > 1e7 ? -1 : l\n \n function valid(speed) {\n let sum = 0\n for(let e of dist) {\n sum = Math.ceil(sum)\n sum += e / speed\n if(sum > hour) return \n }\n \n return true\n }\n};\n\n// another\n\n/**\n * @param {number[]} dist\n * @param {number} hour\n * @return {number}\n */\nconst minSpeedOnTime = function(dist, hour) {\n const sum = dist.reduce((ac, e) => ac + e, 0)\n let l = 1, r = 10 ** 7\n while(l < r) {\n let mid = l + ((r - l) >> 1)\n if(chk(mid)) r = mid\n else l = mid + 1\n }\n\n return chk(l) ? l : -1\n \n function chk(speed) {\n let res = 0\n for(let i = 0, len = dist.length; i < len - 1; i++) {\n res += Math.ceil(dist[i] / speed)\n }\n if (dist.length) res += dist[dist.length - 1] / speed \n return res <= hour\n }\n \n};\n\n// another\n\n/**\n * @param {number[]} dist\n * @param {number} hour\n * @return {number}\n */\nconst minSpeedOnTime = function(dist, hour) {\n let l = 1, r = 1e7\n while(l < r) {\n const mid = l + Math.floor((r - l) / 2)\n if(!valid(mid)) l = mid + 1\n else r = mid\n }\n // console.log(l)\n return valid(l) ? l : -1\n \n function valid(mid) {\n let res = 0\n for(let i = 0, n = dist.length; i < n; i++) {\n const d = dist[i] \n res += (i === n - 1 ? d / mid : Math.ceil(d / mid))\n }\n return res <= hour\n }\n};\n\n" + }, + { + "_id": "66f925ddfdfb8e1665720e7a", + "questionid": 943, + "title": "Check if All the Integers in a Range Are Covered", + "slug": "check-if-all-the-integers-in-a-range-are-covered", + "description": "You are given a 2D integer array ranges and two integers left and right. Each ranges[i] = [starti, endi] represents an inclusive interval between starti and endi. Return true if each integer in the inclusive range [left, right] is covered by at least one interval in ranges. Return false otherwise. An integer x is covered by an interval ranges[i] = [starti, endi] if starti <= x <= endi. ", + "category": [ + "Array", + "Hash Table", + "Prefix Sum" + ], + "complexity": "Easy", + "successrate": 50.7, + "totalsubmissions": 40622, + "totalaccepted": 20609, + "likes": 252, + "dislikes": 56, + "hints": "Iterate over every integer point in the range [left, right]. For each of these points check if it is included in one of the ranges.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "ranges = [[1,2],[3,4],[5,6]], left = 2, right = 5", + "expected_output": "true", + "explanation": "Every integer between 2 and 5 is covered:\n- 2 is covered by the first range.\n- 3 and 4 are covered by the second range.\n- 5 is covered by the third range." + }, + { + "example_num": 2, + "expected_input": "ranges = [[1,10],[10,20]], left = 21, right = 21", + "expected_output": "false", + "explanation": "21 is not covered by any range." + } + ], + "solution": "/**\n * @param {number[][]} ranges\n * @param {number} left\n * @param {number} right\n * @return {boolean}\n */\nconst isCovered = function(ranges, left, right) {\n const arr = Array(52).fill(0)\n for(let [s, e] of ranges) {\n arr[s]++\n arr[e + 1]--\n }\n for(let i = 1; i < 52; i++) {\n arr[i] += arr[i - 1]\n }\n for(let i = left; i <= right; i++) {\n if(arr[i] === 0) return false\n }\n \n return true\n};\n\n// another\n\n/**\n * @param {number[][]} ranges\n * @param {number} left\n * @param {number} right\n * @return {boolean}\n */\nconst isCovered = function(ranges, left, right) {\n\tfor(let i = left; i <= right; i++) {\n\t\tlet seen = false;\n\t\tfor(let j = 0; j < ranges.length && !seen; j++) \n\t\t\tif(i >= ranges[j][0] && i <= ranges[j][1]) \n\t\t\t\tseen = true;\n\t\tif(!seen) return false;\n\t}\n\treturn true;\n};\n\n// another\n\n/**\n * @param {number[][]} ranges\n * @param {number} left\n * @param {number} right\n * @return {boolean}\n */\nconst isCovered = function(ranges, left, right) {\n const arr = Array(52).fill(0)\n for(let [s, e] of ranges) {\n arr[s]++\n arr[e + 1]--\n }\n\n let overlaps = 0\n for(let i = 1; i <= right; i++) {\n overlaps += arr[i];\n if (i >= left && overlaps == 0) return false;\n }\n \n return true\n};\n\n" + }, + { + "_id": "66f925ddfdfb8e1665720e7b", + "questionid": 944, + "title": "Find the Student that Will Replace the Chalk", + "slug": "find-the-student-that-will-replace-the-chalk", + "description": "There are n students in a class numbered from 0 to n - 1. The teacher will give each student a problem starting with the student number 0, then the student number 1, and so on until the teacher reaches the student number n - 1. After that, the teacher will restart the process, starting with the student number 0 again. You are given a 0-indexed integer array chalk and an integer k. There are initially k pieces of chalk. When the student number i is given a problem to solve, they will use chalk[i] pieces of chalk to solve that problem. However, if the current number of chalk pieces is strictly less than chalk[i], then the student number i will be asked to replace the chalk. Return the index of the student that will replace the chalk. ", + "category": [ + "Array", + "Binary Search", + "Simulation", + "Prefix Sum" + ], + "complexity": "Medium", + "successrate": 41.3, + "totalsubmissions": 40798, + "totalaccepted": 16834, + "likes": 248, + "dislikes": 36, + "hints": "Subtract the sum of chalk[i] from k until k is less than that sum Now just iterate over the array if chalk[i] is less thank k this is your answer otherwise this i is the answer", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "chalk = [5,1,5], k = 22", + "expected_output": "0\nExplanation: The students go in turns as follows:\n- Student number 0 uses 5 chalk, so k = 17.\n- Student number 1 uses 1 chalk, so k = 16.\n- Student number 2 uses 5 chalk, so k = 11.\n- Student number 0 uses 5 chalk, so k = 6.\n- Student number 1 uses 1 chalk, so k = 5.\n- Student number 2 uses 5 chalk, so k = 0.\nStudent number 0 does not have enough chalk, so they will have to replace it.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "chalk = [3,4,1,2], k = 25", + "expected_output": "1\nExplanation: The students go in turns as follows:\n- Student number 0 uses 3 chalk so k = 22.\n- Student number 1 uses 4 chalk so k = 18.\n- Student number 2 uses 1 chalk so k = 17.\n- Student number 3 uses 2 chalk so k = 15.\n- Student number 0 uses 3 chalk so k = 12.\n- Student number 1 uses 4 chalk so k = 8.\n- Student number 2 uses 1 chalk so k = 7.\n- Student number 3 uses 2 chalk so k = 5.\n- Student number 0 uses 3 chalk so k = 2.\nStudent number 1 does not have enough chalk, so they will have to replace it.", + "explanation": "" + } + ], + "solution": null + }, + { + "_id": "66f925ddfdfb8e1665720e7d", + "questionid": 946, + "title": "Maximum Value after Insertion", + "slug": "maximum-value-after-insertion", + "description": "You are given a very large integer n, represented as a string, and an integer digit x. The digits in n and the digit x are in the inclusive range [1, 9], and n may represent a negative number. You want to maximize n's numerical value by inserting x anywhere in the decimal representation of n. You cannot insert x to the left of the negative sign. Return a string representing the maximum value of n after the insertion. ", + "category": [ + "String", + "Greedy" + ], + "complexity": "Medium", + "successrate": 35.8, + "totalsubmissions": 49400, + "totalaccepted": 17697, + "likes": 238, + "dislikes": 41, + "hints": "Note that if the number is negative it's the same as positive but you look for the minimum instead. In the case of maximum, if s[i] < x it's optimal that x is put before s[i]. In the case of minimum, if s[i] > x it's optimal that x is put before s[i].", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = "99", x = 9", + "expected_output": ""999"", + "explanation": "The result is the same regardless of where you insert 9." + }, + { + "example_num": 2, + "expected_input": "n = "-13", x = 2", + "expected_output": ""-123"", + "explanation": "You can make n one of {-213, -123, -132}, and the largest of those three is -123." + } + ], + "solution": "/**\n * @param {string} n\n * @param {number} x\n * @return {string}\n */\nconst maxValue = function(n, x) {\n const neg = n[0] === '-'\n if (neg) {\n for(let i = 1; i < n.length; i++) {\n if(+n[i] > x) {\n return n.slice(0, i) + x + n.slice(i)\n }\n }\n return n + x\n } else {\n for(let i = 0; i < n.length; i++) {\n if(+n[i] < x) {\n \n return n.slice(0, i) + x + n.slice(i)\n }\n }\n return n + x\n }\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720e50", + "questionid": 901, + "title": "Minimum Number of Operations to Move All Balls to Each Box", + "slug": "minimum-number-of-operations-to-move-all-balls-to-each-box", + "description": "You have n boxes. You are given a binary string boxes of length n, where boxes[i] is '0' if the ith box is empty, and '1' if it contains one ball. In one operation, you can move one ball from a box to an adjacent box. Box i is adjacent to box j if abs(i - j) == 1. Note that after doing so, there may be more than one ball in some boxes. Return an array answer of size n, where answer[i] is the minimum number of operations needed to move all the balls to the ith box. Each answer[i] is calculated considering the initial state of the boxes. ", + "category": [ + "Array", + "String" + ], + "complexity": "Medium", + "successrate": 85.7, + "totalsubmissions": 83851, + "totalaccepted": 71875, + "likes": 1341, + "dislikes": 50, + "hints": "If you want to move a ball from box i to box j, you'll need abs(i-j) moves. To move all balls to some box, you can move them one by one. For each box i, iterate on each ball in a box j, and add abs(i-j) to answers[i].", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "boxes = "110"", + "expected_output": "[1,1,3]", + "explanation": "The answer for each box is as follows:\n1) First box: you will have to move one ball from the second box to the first box in one operation.\n2) Second box: you will have to move one ball from the first box to the second box in one operation.\n3) Third box: you will have to move one ball from the first box to the third box in two operations, and move one ball from the second box to the third box in one operation." + }, + { + "example_num": 2, + "expected_input": "boxes = "001011"", + "expected_output": "[11,8,5,4,3,4]", + "explanation": "" + } + ], + "solution": "/**\n * @param {string} boxes\n * @return {number[]}\n */\nconst minOperations = function(boxes) {\n const n = boxes.length\n const res = Array(n).fill(0)\n let cum = 0, sum = 0\n for(let i = 0; i < n; i++) {\n res[i] += sum\n cum += +boxes[i]\n sum += cum\n }\n cum = 0, sum = 0\n for(let i = n - 1; i >= 0; i--) {\n res[i] += sum\n cum += +boxes[i]\n sum += cum\n }\n return res\n};\n\n\n// another\n\n\n/**\n * @param {string} boxes\n * @return {number[]}\n */\nconst minOperations = function(boxes) {\n const res = []\n for(let i = 0, len = boxes.length; i < len; i++) {\n res[i] = helper(boxes, i)\n }\n\n return res\n};\n\nfunction helper(str, idx) {\n let res = 0\n for(let i = 0, len = str.length; i < len; i++) {\n if(i === idx || str[i] === '0') continue\n res += Math.abs(i - idx)\n }\n return res\n}\n\n// another\n\n/**\n * @param {string} boxes\n * @return {number[]}\n */\n const minOperations = function(boxes) {\n const n = boxes.length\n const res = Array(n).fill(0)\n let cnt = 0, sum = 0\n for(let i = 0; i < n; i++) {\n res[i] = sum\n cnt += boxes[i] === '1' ? 1 : 0\n sum += cnt\n }\n cnt = 0, sum = 0\n for(let i = n - 1; i >= 0; i--) {\n res[i] += sum\n cnt += boxes[i] === '1' ? 1 : 0\n sum += cnt\n }\n return res\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720e53", + "questionid": 904, + "title": "Count Pairs With XOR in a Range", + "slug": "count-pairs-with-xor-in-a-range", + "description": "Given a (0-indexed) integer array nums and two integers low and high, return the number of nice pairs. A nice pair is a pair (i, j) where 0 <= i < j < nums.length and low <= (nums[i] XOR nums[j]) <= high. ", + "category": [ + "Array", + "Bit Manipulation", + "Trie" + ], + "complexity": "Hard", + "successrate": 46.3, + "totalsubmissions": 9859, + "totalaccepted": 4565, + "likes": 277, + "dislikes": 11, + "hints": "Let's note that we can count all pairs with XOR \u2030\u00a4 K, so the answer would be to subtract the number of pairs withs XOR < low from the number of pairs with XOR \u2030\u00a4 high. For each value, find out the number of values when you XOR it with the result is \u2030\u00a4 K using a trie.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,4,2,7], low = 2, high = 6", + "expected_output": "6", + "explanation": "All nice pairs (i, j) are as follows:\r\n - (0, 1): nums[0] XOR nums[1] = 5 \r\n - (0, 2): nums[0] XOR nums[2] = 3\r\n - (0, 3): nums[0] XOR nums[3] = 6\r\n - (1, 2): nums[1] XOR nums[2] = 6\r\n - (1, 3): nums[1] XOR nums[3] = 3\r\n - (2, 3): nums[2] XOR nums[3] = 5" + }, + { + "example_num": 2, + "expected_input": "nums = [9,8,4,2,1], low = 5, high = 14", + "expected_output": "8", + "explanation": "All nice pairs (i, j) are as follows:\r\n\u200b\u200b\u200b\u200b\u200b - (0, 2): nums[0] XOR nums[2] = 13\r\n  - (0, 3): nums[0] XOR nums[3] = 11\r\n  - (0, 4): nums[0] XOR nums[4] = 8\r\n  - (1, 2): nums[1] XOR nums[2] = 12\r\n  - (1, 3): nums[1] XOR nums[3] = 10\r\n  - (1, 4): nums[1] XOR nums[4] = 9\r\n  - (2, 3): nums[2] XOR nums[3] = 6\r\n  - (2, 4): nums[2] XOR nums[4] = 5" + } + ], + "solution": "/**\n * @param {number[]} nums\n * @param {number} low\n * @param {number} high\n * @return {number}\n */\nconst countPairs = function (nums, low, high) {\n const trie = new Trie()\n\n let ans = 0\n for (let x of nums) {\n ans += trie.count(x, high + 1) - trie.count(x, low)\n trie.insert(x)\n }\n return ans\n}\n\nclass Trie {\n constructor() {\n this.root = {}\n }\n insert(val) {\n let node = this.root\n for (let i = 14; i >= 0; i--) {\n let bit = (val >> i) & 1\n if (!(bit in node)) node[bit] = { cnt: 1 }\n else node[bit]['cnt'] += 1\n node = node[bit]\n }\n }\n count(val, high) {\n let ans = 0\n let node = this.root\n for (let i = 14; i >= 0; i--) {\n if (!node) break\n const bit = (val >> i) & 1\n const cmp = (high >> i) & 1\n if (cmp) {\n if (node[bit]) ans += node[bit]['cnt']\n node = node[1 ^ bit]\n } else node = node[bit]\n }\n\n return ans\n }\n}\n\n\n// another\n\n/**\n * @param {number[]} nums\n * @param {number} low\n * @param {number} high\n * @return {number}\n */\nconst countPairs = function(nums, low, high) {\n let res = 0, n = nums.length, trie = { cnt: 0 }\n for(const e of nums) {\n res += helper(e, high + 1) - helper(e, low)\n insert(e)\n }\n return res\n \n function helper(e, limit) {\n let res = 0, cur = trie\n for(let i = 14; i >= 0; i--) {\n const a = (e >> i) & 1\n const b = (limit >> i) & 1\n if(cur == null) break\n if(b === 0) {\n cur = cur[a]\n continue\n }\n if(cur[a]) {\n res += cur[a].cnt\n }\n cur = cur[1 - a]\n }\n \n return res\n }\n \n function insert(e) {\n let cur = trie\n for(let i = 14; i >= 0; i--) {\n const tmp = (e >> i) & 1\n if(!(tmp in cur)) cur[tmp] = {cnt:0}\n cur[tmp].cnt++\n cur = cur[tmp]\n }\n }\n \n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720e55", + "questionid": 906, + "title": "Minimum Elements to Add to Form a Given Sum", + "slug": "minimum-elements-to-add-to-form-a-given-sum", + "description": "You are given an integer array nums and two integers limit and goal. The array nums has an interesting property that abs(nums[i]) <= limit. Return the minimum number of elements you need to add to make the sum of the array equal to goal. The array must maintain its property that abs(nums[i]) <= limit. Note that abs(x) equals x if x >= 0, and -x otherwise. ", + "category": [ + "Array", + "Greedy" + ], + "complexity": "Medium", + "successrate": 41.6, + "totalsubmissions": 33964, + "totalaccepted": 14123, + "likes": 150, + "dislikes": 145, + "hints": "Try thinking about the problem as if the array is empty. Then you only need to form goal using elements whose absolute value is <= limit. You can greedily set all of the elements except one to limit or -limit, so the number of elements you need is ceil(abs(goal)/ limit). You can \"normalize\" goal by offsetting it by the sum of the array. For example, if the goal is 5 and the sum is -3, then it's exactly the same as if the goal is 8 and the array is empty. The answer is ceil(abs(goal-sum)/limit) = (abs(goal-sum)+limit-1) / limit.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,-1,1], limit = 3, goal = -4", + "expected_output": "2", + "explanation": "You can add -2 and -3, then the sum of the array will be 1 - 1 + 1 - 2 - 3 = -4." + }, + { + "example_num": 2, + "expected_input": "nums = [1,-10,9,1], limit = 100, goal = 0", + "expected_output": "1", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} nums\n * @param {number} limit\n * @param {number} goal\n * @return {number}\n */\nconst minElements = function(nums, limit, goal) {\n const sum = nums.reduce((ac, e) => ac + e, 0)\n let delta = goal - sum\n if(delta === 0) return 0\n const op = delta > 0 ? '+' : '-'\n let res = 0\n delta = Math.abs(delta)\n return Math.floor(delta / limit) + (delta % limit > 0 ? 1 : 0)\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720e58", + "questionid": 909, + "title": "Find Center of Star Graph", + "slug": "find-center-of-star-graph", + "description": "There is an undirected star graph consisting of n nodes labeled from 1 to n. A star graph is a graph where there is one center node and exactly n - 1 edges that connect the center node with every other node. You are given a 2D integer array edges where each edges[i] = [ui, vi] indicates that there is an edge between the nodes ui and vi. Return the center of the given star graph. ", + "category": [ + "Graph" + ], + "complexity": "Easy", + "successrate": 83.6, + "totalsubmissions": 93407, + "totalaccepted": 78108, + "likes": 530, + "dislikes": 70, + "hints": "The center is the only node that has more than one edge. The center is also connected to all other nodes. Any two edges must have a common node, which is the center.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "edges = [[1,2],[2,3],[4,2]]", + "expected_output": "2", + "explanation": "As shown in the figure above, node 2 is connected to every other node, so 2 is the center." + }, + { + "example_num": 2, + "expected_input": "edges = [[1,2],[5,1],[1,3],[1,4]]", + "expected_output": "1", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[][]} edges\n * @return {number}\n */\nconst findCenter = function(edges) {\n return edges[0][0] === edges[1][0] || edges[0][0] === edges[1][1] ? edges[0][0] : edges[0][1]\n};\n\n// another\n\n/**\n * @param {number[][]} edges\n * @return {number}\n */\nconst findCenter = function(edges) {\n const map = {}\n for(let e of edges) {\n const [u, v] = e\n if(map[u] == null) map[u] = []\n if(map[v] == null) map[v] = []\n map[u].push(v)\n map[v].push(u)\n }\n \n const keys = Object.keys(map)\n let res, max = -Infinity\n keys.forEach(e => {\n if(map[e].length > max) {\n res = e\n max = map[e].length\n }\n })\n \n return res\n \n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720e5b", + "questionid": 912, + "title": "Determine Color of a Chessboard Square", + "slug": "determine-color-of-a-chessboard-square", + "description": "You are given coordinates, a string that represents the coordinates of a square of the chessboard. Below is a chessboard for your reference. Return true if the square is white, and false if the square is black. The coordinate will always represent a valid chessboard square. The coordinate will always have the letter first, and the number second. ", + "category": [ + "Math", + "String" + ], + "complexity": "Easy", + "successrate": 77.7, + "totalsubmissions": 45757, + "totalaccepted": 35535, + "likes": 403, + "dislikes": 13, + "hints": "Convert the coordinates to (x, y) - that is, \"a1\" is (1, 1), \"d7\" is (4, 7). Try add the numbers together and look for a pattern.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "coordinates = "a1"", + "expected_output": "false", + "explanation": "From the chessboard above, the square with coordinates "a1" is black, so return false." + }, + { + "example_num": 2, + "expected_input": "coordinates = "h3"", + "expected_output": "true", + "explanation": "From the chessboard above, the square with coordinates "h3" is white, so return true." + }, + { + "example_num": 3, + "expected_input": "coordinates = "c7"", + "expected_output": "false", + "explanation": "" + } + ], + "solution": null + }, + { + "_id": "66f925ddfdfb8e1665720e61", + "questionid": 918, + "title": "Queries on Number of Points Inside a Circle", + "slug": "queries-on-number-of-points-inside-a-circle", + "description": "You are given an array points where points[i] = [xi, yi] is the coordinates of the ith point on a 2D plane. Multiple points can have the same coordinates. You are also given an array queries where queries[j] = [xj, yj, rj] describes a circle centered at (xj, yj) with a radius of rj. For each query queries[j], compute the number of points inside the jth circle. Points on the border of the circle are considered inside. Return an array answer, where answer[j] is the answer to the jth query. ", + "category": [ + "Array", + "Math", + "Geometry" + ], + "complexity": "Medium", + "successrate": 86.6, + "totalsubmissions": 43513, + "totalaccepted": 37679, + "likes": 533, + "dislikes": 53, + "hints": "For a point to be inside a circle, the euclidean distance between it and the circle's center needs to be less than or equal to the radius. Brute force for each circle and iterate overall points and find those inside it.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "points = [[1,3],[3,3],[5,3],[2,2]], queries = [[2,3,1],[4,3,1],[1,1,2]]", + "expected_output": "[3,2,2]\nExplanation: The points and circles are shown above.\nqueries[0] is the green circle, queries[1] is the red circle, and queries[2] is the blue circle.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "points = [[1,1],[2,2],[3,3],[4,4],[5,5]], queries = [[1,2,2],[2,2,2],[4,3,2],[4,3,3]]", + "expected_output": "[2,3,2,4]\nExplanation: The points and circles are shown above.\nqueries[0] is green, queries[1] is red, queries[2] is blue, and queries[3] is purple.", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[][]} points\n * @param {number[][]} queries\n * @return {number[]}\n */\nvar countPoints = function(points, queries) {\n const res = []\n \n for(const [x, y, r] of queries) {\n const square = r ** 2\n const center = [x, y]\n let cnt = 0\n for(const d of points) {\n if(disSquare(d, center) <= square) {\n cnt++\n } \n }\n res.push(cnt)\n }\n \n return res\n \n function disSquare(a, b) {\n return (a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2\n }\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720e62", + "questionid": 919, + "title": "Truncate Sentence", + "slug": "truncate-sentence", + "description": "A sentence is a list of words that are separated by a single space with no leading or trailing spaces. Each of the words consists of only uppercase and lowercase English letters (no punctuation). You are given a sentence s and an integer k. You want to truncate s such that it contains only the first k words. Return s after truncating it. ", + "category": [ + "Array", + "String" + ], + "complexity": "Easy", + "successrate": 81.3, + "totalsubmissions": 72039, + "totalaccepted": 58571, + "likes": 475, + "dislikes": 15, + "hints": "It's easier to solve this problem on an array of strings so parse the string to an array of words After return the first k words as a sentence", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "Hello how are you Contestant", k = 4", + "expected_output": ""Hello how are you"", + "explanation": "The words in s are ["Hello", "how" "are", "you", "Contestant"].\nThe first 4 words are ["Hello", "how", "are", "you"].\nHence, you should return "Hello how are you"." + }, + { + "example_num": 2, + "expected_input": "s = "What is the solution to this problem", k = 4", + "expected_output": ""What is the solution"", + "explanation": "The words in s are ["What", "is" "the", "solution", "to", "this", "problem"].\nThe first 4 words are ["What", "is", "the", "solution"].\nHence, you should return "What is the solution"." + }, + { + "example_num": 3, + "expected_input": "s = "chopper is not a tanuki", k = 5", + "expected_output": ""chopper is not a tanuki"", + "explanation": "" + } + ], + "solution": "/**\n * @param {string} s\n * @param {number} k\n * @return {string}\n */\nconst truncateSentence = function(s, k) {\n const arr = s.split(' ')\n const sli = arr.slice(0, k)\n return sli.join(' ')\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720e6b", + "questionid": 928, + "title": "Incremental Memory Leak", + "slug": "incremental-memory-leak", + "description": "You are given two integers memory1 and memory2 representing the available memory in bits on two memory sticks. There is currently a faulty program running that consumes an increasing amount of memory every second. At the ith second (starting from 1), i bits of memory are allocated to the stick with more available memory (or from the first memory stick if both have the same available memory). If neither stick has at least i bits of available memory, the program crashes. Return an array containing [crashTime, memory1crash, memory2crash], where crashTime is the time (in seconds) when the program crashed and memory1crash and memory2crash are the available bits of memory in the first and second sticks respectively. ", + "category": [ + "Simulation" + ], + "complexity": "Medium", + "successrate": 71, + "totalsubmissions": 17187, + "totalaccepted": 12204, + "likes": 133, + "dislikes": 58, + "hints": "What is the upper bound for the number of seconds? Simulate the process of allocating memory.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "memory1 = 2, memory2 = 2", + "expected_output": "[3,1,0]", + "explanation": "The memory is allocated as follows:\n- At the 1st second, 1 bit of memory is allocated to stick 1. The first stick now has 1 bit of available memory.\n- At the 2nd second, 2 bits of memory are allocated to stick 2. The second stick now has 0 bits of available memory.\n- At the 3rd second, the program crashes. The sticks have 1 and 0 bits available respectively." + }, + { + "example_num": 2, + "expected_input": "memory1 = 8, memory2 = 11", + "expected_output": "[6,0,4]", + "explanation": "The memory is allocated as follows:\n- At the 1st second, 1 bit of memory is allocated to stick 2. The second stick now has 10 bit of available memory.\n- At the 2nd second, 2 bits of memory are allocated to stick 2. The second stick now has 8 bits of available memory.\n- At the 3rd second, 3 bits of memory are allocated to stick 1. The first stick now has 5 bits of available memory.\n- At the 4th second, 4 bits of memory are allocated to stick 2. The second stick now has 4 bits of available memory.\n- At the 5th second, 5 bits of memory are allocated to stick 1. The first stick now has 0 bits of available memory.\n- At the 6th second, the program crashes. The sticks have 0 and 4 bits available respectively." + } + ], + "solution": "/**\n * @param {number} memory1\n * @param {number} memory2\n * @return {number[]}\n */\nconst memLeak = function(memory1, memory2) {\n let i = 1\n const res = Array(3).fill(0)\n res[0] = 1\n res[1] = memory1\n res[2] = memory2\n while(true) {\n if(res[1] >= i || res[2] >= i) {\n if(res[1] >= i && res[2] >= i) {\n if(res[1] === res[2]) {\n res[1] -= i\n } else if(res[1] > res[2]) {\n res[1] -= i\n } else {\n res[2] -= i\n }\n } else if(res[1] >= i) {\n res[1] -= i\n } else if(res[2] >= i){\n res[2] -= i\n }\n } else {\n res[0] = i\n return res\n }\n \n i++\n }\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720e6e", + "questionid": 931, + "title": "Minimum Interval to Include Each Query", + "slug": "minimum-interval-to-include-each-query", + "description": "You are given a 2D integer array intervals, where intervals[i] = [lefti, righti] describes the ith interval starting at lefti and ending at righti (inclusive). The size of an interval is defined as the number of integers it contains, or more formally righti - lefti + 1. You are also given an integer array queries. The answer to the jth query is the size of the smallest interval i such that lefti <= queries[j] <= righti. If no such interval exists, the answer is -1. Return an array containing the answers to the queries. ", + "category": [ + "Array", + "Binary Search", + "Line Sweep", + "Sorting", + "Heap (Priority Queue)" + ], + "complexity": "Hard", + "successrate": 45.5, + "totalsubmissions": 14492, + "totalaccepted": 6599, + "likes": 336, + "dislikes": 6, + "hints": "Is there a way to order the intervals and queries such that it takes less time to query? Is there a way to add and remove intervals by going from the smallest query to the largest query to find the minimum size?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "intervals = [[1,4],[2,4],[3,6],[4,4]], queries = [2,3,4,5]", + "expected_output": "[3,3,1,4]", + "explanation": "The queries are processed as follows:\n- Query = 2: The interval [2,4] is the smallest interval containing 2. The answer is 4 - 2 + 1 = 3.\n- Query = 3: The interval [2,4] is the smallest interval containing 3. The answer is 4 - 2 + 1 = 3.\n- Query = 4: The interval [4,4] is the smallest interval containing 4. The answer is 4 - 4 + 1 = 1.\n- Query = 5: The interval [3,6] is the smallest interval containing 5. The answer is 6 - 3 + 1 = 4." + }, + { + "example_num": 2, + "expected_input": "intervals = [[2,3],[2,5],[1,8],[20,25]], queries = [2,19,5,22]", + "expected_output": "[2,-1,4,6]", + "explanation": "The queries are processed as follows:\n- Query = 2: The interval [2,3] is the smallest interval containing 2. The answer is 3 - 2 + 1 = 2.\n- Query = 19: None of the intervals contain 19. The answer is -1.\n- Query = 5: The interval [2,5] is the smallest interval containing 5. The answer is 5 - 2 + 1 = 4.\n- Query = 22: The interval [20,25] is the smallest interval containing 22. The answer is 25 - 20 + 1 = 6." + } + ], + "solution": "/**\n * @param {number[][]} intervals\n * @param {number[]} queries\n * @return {number[]}\n */\nconst minInterval = function (intervals, queries) {\n const n = intervals.length\n const m = queries.length\n const sortedQueryIdx = [...Array(m).keys()].sort(\n (a, b) => queries[a] - queries[b]\n )\n intervals.sort((a, b) => a[0] - b[0]) // sort by start & ascending\n const minHeap = new BinaryHeap((c, p) => c.size >= p.size)\n const res = Array(m).fill(0)\n let i = 0\n for (const idx of sortedQueryIdx) {\n const query = queries[idx]\n while (i < n && intervals[i][0] <= query) {\n minHeap.push({\n size: intervals[i][1] - intervals[i][0] + 1,\n start: intervals[i][0],\n end: intervals[i][1],\n })\n i++\n }\n while (!minHeap.isEmpty() && minHeap.peek().end < query) {\n minHeap.pop()\n }\n res[idx] = minHeap.isEmpty() ? -1 : minHeap.peek().size\n }\n return res\n}\n\nclass BinaryHeap {\n /**\n * @param {compareFunction} compareFn\n */\n constructor(compareFn) {\n this.content = []\n this.compareFn = compareFn // Min-Heap: (c, p) => c > p\n }\n\n /**\n * @return {number} - Current heap size.\n */\n size() {\n return this.content.length\n }\n\n /**\n * @return {boolean} - True if heap size is empty.\n */\n isEmpty() {\n return this.size() === 0\n }\n\n /**\n * @return {*} - Root node of the heap.\n */\n peek() {\n return this.size() > 0 ? this.content[0] : null\n }\n\n /**\n * @param {*} node - New node to add.\n */\n push(node) {\n this.content.push(node)\n this._bubbleUp(this.content.length - 1)\n }\n\n /**\n * @return {*} - Root node of the heap.\n */\n pop() {\n if (this.content.length === 0) return null\n const root = this.content[0]\n const last = this.content.pop()\n if (this.content.length > 0) {\n this.content[0] = last\n this._sinkDown(0)\n }\n return root\n }\n\n /**\n * @param {*} node - Node to delete.\n */\n remove(node) {\n const length = this.content.length\n for (let i = 0; i < length; i++) {\n if (this.content[i] !== node) continue\n const last = this.content.pop()\n if (i === length - 1) break\n this.content[i] = last\n this._bubbleUp(i)\n this._sinkDown(i)\n break\n }\n }\n\n /**\n * @param {number} idx - Index of the node to bubble up\n */\n _bubbleUp(idx) {\n const node = this.content[idx]\n while (idx > 0) {\n const parentIdx = Math.floor((idx + 1) / 2) - 1\n const parent = this.content[parentIdx]\n if (this.compareFn(node, parent)) break\n this.content[parentIdx] = node\n this.content[idx] = parent\n idx = parentIdx\n }\n }\n\n /**\n * @param {number} idx - Index of the node to sink down\n */\n _sinkDown(idx) {\n const node = this.content[idx]\n while (true) {\n const child2Idx = (idx + 1) * 2\n const child1Idx = child2Idx - 1\n let swapIdx = -1\n if (child1Idx < this.content.length) {\n const child1 = this.content[child1Idx]\n if (!this.compareFn(child1, node)) swapIdx = child1Idx\n }\n if (child2Idx < this.content.length) {\n const child2 = this.content[child2Idx]\n const compareNode = swapIdx === -1 ? node : this.content[child1Idx]\n if (!this.compareFn(child2, compareNode)) swapIdx = child2Idx\n }\n if (swapIdx === -1) break\n this.content[idx] = this.content[swapIdx]\n this.content[swapIdx] = node\n idx = swapIdx\n }\n }\n}\n\n\n// another\n\n/**\n * @param {number[][]} intervals\n * @param {number[]} queries\n * @return {number[]}\n */\nconst minInterval = function (A, Q) {\n const QQ = []\n for (let idx = 0; idx < Q.length; idx++) QQ.push([Q[idx], idx])\n QQ.sort((a, b) => a[0] - b[0])\n A.sort((a, b) => a[0] - b[0])\n let i = 0,\n N = A.length\n const ans = Array(Q.length).fill(-1)\n const m = new TreeMap()\n const pq = new PriorityQueue((a, b) => a[0] < b[0])\n for (let [q, index] of QQ) {\n for (; i < N && A[i][0] <= q; i++) {\n let len = A[i][1] - A[i][0] + 1\n if (m.get(len) == null) m.set(len, 0)\n m.set(len, m.get(len) + 1)\n pq.push([A[i][1], len])\n }\n while (pq.size() > 0 && pq.peek()[0] < q) {\n let [right, len] = pq.peek()\n m.set(len, m.get(len) - 1)\n if (m.get(len) === 0) m.remove(len)\n pq.pop()\n }\n const first = m.getMinKey()\n if (m.getLength()) ans[index] = first\n }\n return ans\n}\n\nclass PriorityQueue {\n constructor(comparator = (a, b) => a > b) {\n this.heap = []\n this.top = 0\n this.comparator = comparator\n }\n size() {\n return this.heap.length\n }\n isEmpty() {\n return this.size() === 0\n }\n peek() {\n return this.heap[this.top]\n }\n push(...values) {\n values.forEach((value) => {\n this.heap.push(value)\n this.siftUp()\n })\n return this.size()\n }\n pop() {\n const poppedValue = this.peek()\n const bottom = this.size() - 1\n if (bottom > this.top) {\n this.swap(this.top, bottom)\n }\n this.heap.pop()\n this.siftDown()\n return poppedValue\n }\n replace(value) {\n const replacedValue = this.peek()\n this.heap[this.top] = value\n this.siftDown()\n return replacedValue\n }\n\n parent = (i) => ((i + 1) >>> 1) - 1\n left = (i) => (i << 1) + 1\n right = (i) => (i + 1) << 1\n greater = (i, j) => this.comparator(this.heap[i], this.heap[j])\n swap = (i, j) => ([this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]])\n siftUp = () => {\n let node = this.size() - 1\n while (node > this.top && this.greater(node, this.parent(node))) {\n this.swap(node, this.parent(node))\n node = this.parent(node)\n }\n }\n siftDown = () => {\n let node = this.top\n while (\n (this.left(node) < this.size() && this.greater(this.left(node), node)) ||\n (this.right(node) < this.size() && this.greater(this.right(node), node))\n ) {\n let maxChild =\n this.right(node) < this.size() &&\n this.greater(this.right(node), this.left(node))\n ? this.right(node)\n : this.left(node)\n this.swap(node, maxChild)\n node = maxChild\n }\n }\n}\n\nfunction TreeMap() {\n var root = null\n var keyType = void 0\n var length = 0\n\n return {\n each: each,\n set: set,\n get: get,\n getTree: getTree,\n getLength: getLength,\n getMaxKey: getMaxKey,\n getMinKey: getMinKey,\n remove: remove,\n }\n\n function checkKey(key, checkKeyType) {\n var localKeyType = typeof key\n\n if (\n localKeyType !== 'number' &&\n localKeyType !== 'string' &&\n localKeyType !== 'boolean'\n ) {\n throw new Error(\"'key' must be a number, a string or a boolean\")\n }\n\n if (checkKeyType === true && localKeyType !== keyType) {\n throw new Error('All keys must be of the same type')\n }\n\n return localKeyType\n }\n\n function call(callback) {\n var args = Array.prototype.slice.call(arguments, 1)\n\n if (typeof callback === 'function') {\n callback.apply(void 0, args)\n }\n }\n\n function getTree() {\n return root\n }\n\n function getLength() {\n return length\n }\n\n function each(callback) {\n internalEach(root, callback)\n }\n\n function internalEach(node, callback, internalCallback) {\n if (node === null) {\n return call(internalCallback)\n }\n\n internalEach(node.left, callback, function () {\n call(callback, node.value, node.key)\n\n internalEach(node.right, callback, function () {\n call(internalCallback)\n })\n })\n }\n\n function get(key) {\n checkKey(key)\n\n return internalGet(key, root)\n }\n\n function internalGet(key, node) {\n if (node === null) {\n return void 0\n }\n\n if (key < node.key) {\n return internalGet(key, node.left)\n } else if (key > node.key) {\n return internalGet(key, node.right)\n } else {\n return node.value\n }\n }\n\n function set(key, value) {\n if (root === null) {\n keyType = checkKey(key)\n } else {\n checkKey(key, true)\n }\n\n root = internalSet(key, value, root)\n }\n\n function internalSet(key, value, node) {\n if (node === null) {\n length++\n\n return {\n key: key,\n value: value,\n left: null,\n right: null,\n }\n }\n\n if (key < node.key) {\n node.left = internalSet(key, value, node.left)\n } else if (key > node.key) {\n node.right = internalSet(key, value, node.right)\n } else {\n node.value = value\n }\n\n return node\n }\n\n function getMaxKey() {\n var maxNode = getMaxNode(root)\n\n if (maxNode !== null) {\n return maxNode.key\n }\n\n return maxNode\n }\n\n function getMinKey() {\n var minNode = getMinNode(root)\n\n if (minNode !== null) {\n return minNode.key\n }\n\n return minNode\n }\n\n function getMaxNode(node) {\n while (node !== null && node.right !== null) {\n node = node.right\n }\n\n return node\n }\n\n function getMinNode(node) {\n while (node !== null && node.left !== null) {\n node = node.left\n }\n\n return node\n }\n\n function remove(key) {\n checkKey(key)\n\n root = internalRemove(key, root)\n }\n\n function internalRemove(key, node) {\n if (node === null) {\n return null\n }\n\n if (key < node.key) {\n node.left = internalRemove(key, node.left)\n } else if (key > node.key) {\n node.right = internalRemove(key, node.right)\n } else {\n if (node.left !== null && node.right !== null) {\n var maxNode = getMaxNode(node.left)\n\n var maxNodeKey = maxNode.key\n var maxNodeValue = maxNode.value\n\n maxNode.key = node.key\n maxNode.value = node.value\n node.key = maxNodeKey\n node.value = maxNodeValue\n\n node.left = internalRemove(key, node.left)\n } else if (node.left !== null) {\n length--\n return node.left\n } else if (node.right !== null) {\n length--\n return node.right\n } else {\n length--\n return null\n }\n }\n\n return node\n }\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720e7c", + "questionid": 945, + "title": "Check if Word Equals Summation of Two Words", + "slug": "check-if-word-equals-summation-of-two-words", + "description": "The letter value of a letter is its position in the alphabet starting from 0 (i.e. 'a' -> 0, 'b' -> 1, 'c' -> 2, etc.). The numerical value of some string of lowercase English letters s is the concatenation of the letter values of each letter in s, which is then converted into an integer. You are given three strings firstWord, secondWord, and targetWord, each consisting of lowercase English letters 'a' through 'j' inclusive. Return true if the summation of the numerical values of firstWord and secondWord equals the numerical value of targetWord, or false otherwise. ", + "category": [ + "String" + ], + "complexity": "Easy", + "successrate": 73.2, + "totalsubmissions": 53107, + "totalaccepted": 38861, + "likes": 321, + "dislikes": 20, + "hints": "Convert each character of each word to its numerical value. Check if the numerical values satisfies the condition.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "firstWord = "acb", secondWord = "cba", targetWord = "cdb"", + "expected_output": "true", + "explanation": "The numerical value of firstWord is "acb" -> "021" -> 21.\nThe numerical value of secondWord is "cba" -> "210" -> 210.\nThe numerical value of targetWord is "cdb" -> "231" -> 231.\nWe return true because 21 + 210 == 231." + }, + { + "example_num": 2, + "expected_input": "firstWord = "aaa", secondWord = "a", targetWord = "aab"", + "expected_output": "false", + "explanation": "The numerical value of firstWord is "aaa" -> "000" -> 0.\nThe numerical value of secondWord is "a" -> "0" -> 0.\nThe numerical value of targetWord is "aab" -> "001" -> 1.\nWe return false because 0 + 0 != 1." + }, + { + "example_num": 3, + "expected_input": "firstWord = "aaa", secondWord = "a", targetWord = "aaaa"", + "expected_output": "true", + "explanation": "The numerical value of firstWord is "aaa" -> "000" -> 0.\nThe numerical value of secondWord is "a" -> "0" -> 0.\nThe numerical value of targetWord is "aaaa" -> "0000" -> 0.\nWe return true because 0 + 0 == 0." + } + ], + "solution": "/**\n * @param {string} firstWord\n * @param {string} secondWord\n * @param {string} targetWord\n * @return {boolean}\n */\nconst isSumEqual = function(firstWord, secondWord, targetWord) {\n let str = 'abcdefghij'\n const hash = {}, reverse = {}\n for(let i = 0; i < str.length; i++) {\n hash[str[i]] = i\n reverse[i] = str[i]\n }\n let len1 = firstWord.length, len2 = secondWord.length\n if (len1 < len2) return isSumEqual(secondWord, firstWord, targetWord)\n // len1 >= len2\n if (len1 > len2) {\n for(let i = len1 - len2; i > 0; i--) {\n secondWord = 'a' + secondWord\n }\n }\n let res = '', inc = 0\n for(let i = len1 - 1; i >= 0; i--) {\n const tmp = hash[firstWord[i]] + hash[secondWord[i]] + inc\n if (tmp > 9) {\n inc = 1\n } else {\n inc = 0\n }\n const cur = tmp % 10\n res = reverse[cur] + res\n }\n \n if(inc) res = 'b' + res\n // console.log(res)\n let r1 = '', r2 = ''\n for(let i = 0; i < targetWord.length; i++) {\n r1 = r1 + hash[targetWord[i]]\n }\n for(let i = 0; i < res.length; i++) {\n r2 = r2 + hash[res[i]]\n }\n return (+r1) === (+r2)\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720e7e", + "questionid": 947, + "title": "Process Tasks Using Servers", + "slug": "process-tasks-using-servers", + "description": "You are given two 0-indexed integer arrays servers and tasks of lengths n and m respectively. servers[i] is the weight of the i server, and tasks[j] is the time needed to process the j task in seconds. Tasks are assigned to the servers using a task queue. Initially, all servers are free, and the queue is empty. At second j, the jth task is inserted into the queue (starting with the 0th task being inserted at second 0). As long as there are free servers and the queue is not empty, the task in the front of the queue will be assigned to a free server with the smallest weight, and in case of a tie, it is assigned to a free server with the smallest index. If there are no free servers and the queue is not empty, we wait until a server becomes free and immediately assign the next task. If multiple servers become free at the same time, then multiple tasks from the queue will be assigned in order of insertion following the weight and index priorities above. A server that is assigned task j at second t will be free again at second t + tasks[j]. Build an array ans of length m, where ans[j] is the index of the server the jth task will be assigned to. Return the array ans. ", + "category": [ + "Array", + "Heap (Priority Queue)" + ], + "complexity": "Medium", + "successrate": 37.4, + "totalsubmissions": 44636, + "totalaccepted": 16674, + "likes": 551, + "dislikes": 165, + "hints": "You can maintain a Heap of available Servers and a Heap of unavailable servers Note that the tasks will be processed in the input order so you just need to find the x-th server that will be available according to the rules", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "servers = [3,3,2], tasks = [1,2,3,2,1,2]", + "expected_output": "[2,2,0,2,1,2]\nExplanation: Events in chronological order go as follows:\n- At second 0, task 0 is added and processed using server 2 until second 1.\n- At second 1, server 2 becomes free. Task 1 is added and processed using server 2 until second 3.\n- At second 2, task 2 is added and processed using server 0 until second 5.\n- At second 3, server 2 becomes free. Task 3 is added and processed using server 2 until second 5.\n- At second 4, task 4 is added and processed using server 1 until second 5.\n- At second 5, all servers become free. Task 5 is added and processed using server 2 until second 7.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "servers = [5,1,4,3,2], tasks = [2,1,2,4,5,2,1]", + "expected_output": "[1,4,1,4,1,3,2]\nExplanation: Events in chronological order go as follows: \n- At second 0, task 0 is added and processed using server 1 until second 2.\n- At second 1, task 1 is added and processed using server 4 until second 2.\n- At second 2, servers 1 and 4 become free. Task 2 is added and processed using server 1 until second 4. \n- At second 3, task 3 is added and processed using server 4 until second 7.\n- At second 4, server 1 becomes free. Task 4 is added and processed using server 1 until second 9. \n- At second 5, task 5 is added and processed using server 3 until second 7.\n- At second 6, task 6 is added and processed using server 2 until second 7.", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} servers\n * @param {number[]} tasks\n * @return {number[]}\n */\nconst assignTasks = function(servers, tasks) {\n const avail = new PQ((a, b) => a[0] === b[0] ? a[1] < b[1] : a[0] < b[0])\n const busy = new PQ((a, b) => a[2] < b[2])\n const res = []\n const { max } = Math\n // init\n for(let i = 0, len = servers.length; i < len; i++) {\n avail.push([servers[i], i, 0])\n }\n \n for(let i = 0, len = tasks.length; i < len; i++) {\n while(!busy.isEmpty() && busy.peek()[2] <= i) {\n const s = busy.pop()\n s[2] = i\n avail.push(s)\n }\n if(!avail.isEmpty()) {\n const s = avail.pop()\n res.push(s[1])\n busy.push([s[0], s[1], max(i, s[2]) + tasks[i]])\n } else {\n const tmp = busy.peek()\n while(!busy.isEmpty() && busy.peek()[2] === tmp[2]) {\n avail.push(busy.pop())\n }\n const s = avail.pop()\n res.push(s[1])\n busy.push([s[0], s[1], max(i, s[2]) + tasks[i]])\n }\n }\n \n return res\n};\n\nclass PQ {\n constructor(comparator = (a, b) => a > b) {\n this.heap = []\n this.top = 0\n this.comparator = comparator\n }\n size() {\n return this.heap.length\n }\n isEmpty() {\n return this.size() === 0\n }\n peek() {\n return this.heap[this.top]\n }\n push(...values) {\n values.forEach((value) => {\n this.heap.push(value)\n this.siftUp()\n })\n return this.size()\n }\n pop() {\n const poppedValue = this.peek()\n const bottom = this.size() - 1\n if (bottom > this.top) {\n this.swap(this.top, bottom)\n }\n this.heap.pop()\n this.siftDown()\n return poppedValue\n }\n replace(value) {\n const replacedValue = this.peek()\n this.heap[this.top] = value\n this.siftDown()\n return replacedValue\n }\n\n parent = (i) => ((i + 1) >>> 1) - 1\n left = (i) => (i << 1) + 1\n right = (i) => (i + 1) << 1\n greater = (i, j) => this.comparator(this.heap[i], this.heap[j])\n swap = (i, j) => ([this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]])\n siftUp = () => {\n let node = this.size() - 1\n while (node > this.top && this.greater(node, this.parent(node))) {\n this.swap(node, this.parent(node))\n node = this.parent(node)\n }\n }\n siftDown = () => {\n let node = this.top\n while (\n (this.left(node) < this.size() && this.greater(this.left(node), node)) ||\n (this.right(node) < this.size() && this.greater(this.right(node), node))\n ) {\n let maxChild =\n this.right(node) < this.size() &&\n this.greater(this.right(node), this.left(node))\n ? this.right(node)\n : this.left(node)\n this.swap(node, maxChild)\n node = maxChild\n }\n }\n}\n\n// another\n\n/**\n * @param {number[]} servers\n * @param {number[]} tasks\n * @return {number[]}\n */\nconst assignTasks = function (servers, tasks) {\n const available = new PriorityQueue((a, b) =>\n a[0] === b[0] ? a[1] < b[1] : a[0] < b[0]\n )\n const occupied = new PriorityQueue((a, b) =>\n a[0] === b[0] ? (a[1] === b[1] ? a[2] < b[2] : a[1] < b[1]) : a[0] < b[0]\n )\n\n const res = [],\n m = tasks.length,\n n = servers.length\n for (let i = 0; i < n; i++) {\n const w = servers[i]\n available.push([w, i])\n }\n let now = 0\n for (let i = 0; i < m; i++) {\n const t = tasks[i]\n\n while (!occupied.isEmpty() && occupied.peek()[0] <= now) {\n const [end, weight, index] = occupied.pop()\n available.push([weight, index])\n }\n\n let idx\n if (!available.isEmpty()) {\n const [weight, index] = available.pop()\n idx = index\n occupied.push([now + t, weight, index])\n if(i >= now) now++\n } else {\n let [endTime, weight, index] = occupied.pop()\n idx = index\n occupied.push([endTime + t, weight, index])\n now = endTime\n }\n\n res.push(idx)\n }\n\n return res\n}\n\nclass PriorityQueue {\n constructor(comparator = (a, b) => a > b) {\n this.heap = []\n this.top = 0\n this.comparator = comparator\n }\n size() {\n return this.heap.length\n }\n isEmpty() {\n return this.size() === 0\n }\n peek() {\n return this.heap[this.top]\n }\n push(...values) {\n values.forEach((value) => {\n this.heap.push(value)\n this.siftUp()\n })\n return this.size()\n }\n pop() {\n const poppedValue = this.peek()\n const bottom = this.size() - 1\n if (bottom > this.top) {\n this.swap(this.top, bottom)\n }\n this.heap.pop()\n this.siftDown()\n return poppedValue\n }\n replace(value) {\n const replacedValue = this.peek()\n this.heap[this.top] = value\n this.siftDown()\n return replacedValue\n }\n\n parent = (i) => ((i + 1) >>> 1) - 1\n left = (i) => (i << 1) + 1\n right = (i) => (i + 1) << 1\n greater = (i, j) => this.comparator(this.heap[i], this.heap[j])\n swap = (i, j) => ([this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]])\n siftUp = () => {\n let node = this.size() - 1\n while (node > this.top && this.greater(node, this.parent(node))) {\n this.swap(node, this.parent(node))\n node = this.parent(node)\n }\n }\n siftDown = () => {\n let node = this.top\n while (\n (this.left(node) < this.size() && this.greater(this.left(node), node)) ||\n (this.right(node) < this.size() && this.greater(this.right(node), node))\n ) {\n let maxChild =\n this.right(node) < this.size() &&\n this.greater(this.right(node), this.left(node))\n ? this.right(node)\n : this.left(node)\n this.swap(node, maxChild)\n node = maxChild\n }\n }\n}\n\n// another\n\n\n/**\n * @param {number[]} servers\n * @param {number[]} tasks\n * @return {number[]}\n */\nconst assignTasks = function(servers, tasks) {\n const freePQ = new PriorityQueue((a, b) => a.w === b.w ? a.i < b.i : a.w < b.w)\n const runningPQ = new PriorityQueue((a, b) => a.e === b.e ? (a.w === b.w ? a.i < b.i : a.w < b.w) : a.e < b.e)\n const m = servers.length, n = tasks.length\n for(let i = 0; i < m; i++) freePQ.push({w: servers[i], i, e: 0})\n const res = []\n for(let i = 0; i < n; i++) {\n const cur = tasks[i]\n while(!runningPQ.isEmpty() && runningPQ.peek().e <= i) {\n const tmp = runningPQ.pop()\n tmp.e = i\n freePQ.push(tmp)\n }\n if(freePQ.isEmpty()) {\n const tmp = runningPQ.pop()\n res[i] = tmp.i\n tmp.e += cur\n runningPQ.push(tmp)\n } else {\n const tmp = freePQ.pop()\n res[i] = tmp.i\n tmp.e = i + cur\n runningPQ.push(tmp)\n }\n }\n return res\n};\n\n// another\n\n/**\n * @param {number[]} servers\n * @param {number[]} tasks\n * @return {number[]}\n */\nconst assignTasks = function(servers, tasks) {\n let i = 0\n const freePQ = new PriorityQueue((a, b) => {\n if(a.w < b.w) return true\n else if(a.w > b.w) return false\n else {\n if(a.idx < b.idx) return true\n return false\n }\n })\n const runningPQ = new PriorityQueue((a, b) => {\n return a.end < b.end\n })\n const res = []\n for(let i = 0; i < servers.length; i++) {\n freePQ.push({\n w: servers[i],\n idx: i\n })\n }\n let taskIdx = 0\n while(taskIdx < tasks.length) {\n while(!runningPQ.isEmpty() && runningPQ.peek().end <= i) {\n let server = runningPQ.pop()\n freePQ.push({\n w: server.w,\n idx: server.idx\n })\n }\n \n while(taskIdx <= i && !freePQ.isEmpty() && taskIdx < tasks.length) {\n const server = freePQ.pop()\n res[taskIdx] = server.idx\n runningPQ.push({\n end: i + tasks[taskIdx],\n w: server.w,\n idx: server.idx\n })\n taskIdx++\n }\n if(i < tasks.length || !freePQ.isEmpty()) i++\n else i = Math.max(i + 1, runningPQ.peek().end)\n }\n return res\n};\n\nclass PriorityQueue {\n constructor(comparator = (a, b) => a > b) {\n this.heap = []\n this.top = 0\n this.comparator = comparator\n }\n size() {\n return this.heap.length\n }\n isEmpty() {\n return this.size() === 0\n }\n peek() {\n return this.heap[this.top]\n }\n push(...values) {\n values.forEach((value) => {\n this.heap.push(value)\n this.siftUp()\n })\n return this.size()\n }\n pop() {\n const poppedValue = this.peek()\n const bottom = this.size() - 1\n if (bottom > this.top) {\n this.swap(this.top, bottom)\n }\n this.heap.pop()\n this.siftDown()\n return poppedValue\n }\n replace(value) {\n const replacedValue = this.peek()\n this.heap[this.top] = value\n this.siftDown()\n return replacedValue\n }\n\n parent = (i) => ((i + 1) >>> 1) - 1\n left = (i) => (i << 1) + 1\n right = (i) => (i + 1) << 1\n greater = (i, j) => this.comparator(this.heap[i], this.heap[j])\n swap = (i, j) => ([this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]])\n siftUp = () => {\n let node = this.size() - 1\n while (node > this.top && this.greater(node, this.parent(node))) {\n this.swap(node, this.parent(node))\n node = this.parent(node)\n }\n }\n siftDown = () => {\n let node = this.top\n while (\n (this.left(node) < this.size() && this.greater(this.left(node), node)) ||\n (this.right(node) < this.size() && this.greater(this.right(node), node))\n ) {\n let maxChild =\n this.right(node) < this.size() &&\n this.greater(this.right(node), this.left(node))\n ? this.right(node)\n : this.left(node)\n this.swap(node, maxChild)\n node = maxChild\n }\n }\n}\n\n// another\n\n/**\n * @param {number[]} servers\n * @param {number[]} tasks\n * @return {number[]}\n */\nconst assignTasks = function(servers, tasks) {\n const freePQ = new PriorityQueue((a, b) => {\n if(a.w < b.w) return true\n else if(a.w > b.w) return false\n else {\n if(a.idx < b.idx) return true\n return false\n }\n })\n const runningPQ = new PriorityQueue((a, b) => {\n return a.end === b.end ? (a.w === b.w ? a.idx < b.idx : a.w < b.w) : a.end < b.end\n })\n const res = []\n for(let i = 0; i < servers.length; i++) {\n freePQ.push({\n w: servers[i],\n idx: i\n })\n }\n for(let i = 0, n = tasks.length; i < n; i++) {\n const cur = tasks[i]\n while(runningPQ.size() && runningPQ.peek().end <= i) {\n const el = runningPQ.pop()\n freePQ.push({\n w: el.w,\n idx: el.idx,\n })\n }\n \n if(freePQ.isEmpty()) {\n const el = runningPQ.pop()\n res[i] = el.idx\n el.end += cur\n runningPQ.push(el)\n } else {\n const el = freePQ.pop()\n res[i] = el.idx\n el.end = i + cur\n runningPQ.push(el)\n }\n }\n\n return res\n};\n\n" + }, + { + "_id": "66f925ddfdfb8e1665720e7f", + "questionid": 948, + "title": "Minimum Skips to Arrive at Meeting On Time", + "slug": "minimum-skips-to-arrive-at-meeting-on-time", + "description": "You are given an integer hoursBefore, the number of hours you have to travel to your meeting. To arrive at your meeting, you have to travel through n roads. The road lengths are given as an integer array dist of length n, where dist[i] describes the length of the ith road in kilometers. In addition, you are given an integer speed, which is the speed (in km/h) you will travel at. After you travel road i, you must rest and wait for the next integer hour before you can begin traveling on the next road. Note that you do not have to rest after traveling the last road because you are already at the meeting. However, you are allowed to skip some rests to be able to arrive on time, meaning you do not need to wait for the next integer hour. Note that this means you may finish traveling future roads at different hour marks. Return the minimum number of skips required to arrive at the meeting on time, or -1 if it is impossible. ", + "category": [ + "Array", + "Dynamic Programming" + ], + "complexity": "Hard", + "successrate": 38.6, + "totalsubmissions": 11818, + "totalaccepted": 4559, + "likes": 210, + "dislikes": 39, + "hints": "Is there something you can keep track of from one road to another? How would knowing the start time for each state help us solve the problem?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "dist = [1,3,2], speed = 4, hoursBefore = 2", + "expected_output": "1", + "explanation": "Without skipping any rests, you will arrive in (1/4 + 3/4) + (3/4 + 1/4) + (2/4) = 2.5 hours.\nYou can skip the first rest to arrive in ((1/4 + 0) + (3/4 + 0)) + (2/4) = 1.5 hours.\nNote that the second rest is shortened because you finish traveling the second road at an integer hour due to skipping the first rest." + }, + { + "example_num": 2, + "expected_input": "dist = [7,3,5,5], speed = 2, hoursBefore = 10", + "expected_output": "2", + "explanation": "Without skipping any rests, you will arrive in (7/2 + 1/2) + (3/2 + 1/2) + (5/2 + 1/2) + (5/2) = 11.5 hours.\nYou can skip the first and third rest to arrive in ((7/2 + 0) + (3/2 + 0)) + ((5/2 + 0) + (5/2)) = 10 hours." + }, + { + "example_num": 3, + "expected_input": "dist = [7,3,5,5], speed = 1, hoursBefore = 10", + "expected_output": "-1", + "explanation": "It is impossible to arrive at the meeting on time even if you skip all the rests." + } + ], + "solution": "/**\n * @param {number[]} dist\n * @param {number} speed\n * @param {number} hoursBefore\n * @return {number}\n */\nconst minSkips = function (dist, speed, hoursBefore) {\n let left = 0\n let right = dist.length\n\n while (left < right) {\n let mid = ~~(left + (right - left) / 2)\n if (dfs(dist, speed, mid) > 1.0 * hoursBefore) {\n left = mid + 1\n } else {\n right = mid\n }\n }\n return dfs(dist, speed, left) <= 1.0 * hoursBefore ? left : -1\n function dfs(dist, speed, skips) {\n const dp = Array.from({ length: dist.length }, () =>\n Array(skips + 1).fill(0)\n )\n let eps = 1e-9\n for (let i = 0; i <= skips; i++) {\n dp[0][i] = (dist[0] * 1.0) / speed - eps\n }\n\n for (let i = 1; i < dist.length; i++) {\n dp[i][0] = Math.ceil(dp[i - 1][0]) + (dist[i] * 1.0) / speed - eps\n for (let j = 1; j <= skips; j++) {\n let time = dp[i - 1][j - 1] + (dist[i] * 1.0) / speed - eps\n dp[i][j] = Math.min(\n time,\n Math.ceil(dp[i - 1][j]) + (dist[i] * 1.0) / speed - eps\n )\n }\n }\n return dp[dist.length - 1][skips]\n }\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720e81", + "questionid": 950, + "title": "Minimum Space Wasted From Packaging", + "slug": "minimum-space-wasted-from-packaging", + "description": "You have n packages that you are trying to place in boxes, one package in each box. There are m suppliers that each produce boxes of different sizes (with infinite supply). A package can be placed in a box if the size of the package is less than or equal to the size of the box. The package sizes are given as an integer array packages, where packages[i] is the size of the ith package. The suppliers are given as a 2D integer array boxes, where boxes[j] is an array of box sizes that the jth supplier produces. You want to choose a single supplier and use boxes from them such that the total wasted space is minimized. For each package in a box, we define the space wasted to be size of the box - size of the package. The total wasted space is the sum of the space wasted in all the boxes. Return the minimum total wasted space by choosing the box supplier optimally, or -1 if it is impossible to fit all the packages inside boxes. Since the answer may be large, return it modulo 109 + 7. ", + "category": [ + "Array", + "Binary Search", + "Sorting", + "Prefix Sum" + ], + "complexity": "Hard", + "successrate": 30, + "totalsubmissions": 25170, + "totalaccepted": 7560, + "likes": 239, + "dislikes": 27, + "hints": "Given a fixed size box, is there a way to quickly query which packages (i.e., count and sizes) should end up in that box size? Do we have to order the boxes a certain way to allow us to answer the query quickly?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "packages = [2,3,5], boxes = [[4,8],[2,8]]", + "expected_output": "6\nExplanation: It is optimal to choose the first supplier, using two size-4 boxes and one size-8 box.\nThe total waste is (4-2) + (4-3) + (8-5) = 6.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "packages = [2,3,5], boxes = [[1,4],[2,3],[3,4]]", + "expected_output": "-1", + "explanation": "There is no box that the package of size 5 can fit in." + }, + { + "example_num": 3, + "expected_input": "packages = [3,5,8,10,11,12], boxes = [[12],[11,9],[10,5,14]]", + "expected_output": "9", + "explanation": "It is optimal to choose the third supplier, using two size-5 boxes, two size-10 boxes, and two size-14 boxes.\nThe total waste is (5-3) + (5-5) + (10-8) + (10-10) + (14-11) + (14-12) = 9." + } + ], + "solution": "/**\n * @param {number[]} packages\n * @param {number[][]} boxes\n * @return {number}\n */\nconst minWastedSpace = function (packages, boxes) {\n const mod = 1e9 + 7\n const n = packages.length\n packages.sort((a, b) => a - b)\n const preSum = packages.reduce(\n (acc, cur) => {\n acc.push(acc[acc.length - 1] + cur)\n return acc\n },\n [0]\n )\n\n const upperBound = (target) => {\n let lo = 0,\n hi = n\n while (lo < hi) {\n const mi = (lo + hi) >> 1\n const val = packages[mi]\n if (val <= target) {\n lo = mi + 1\n } else {\n hi = mi\n }\n }\n return lo\n }\n\n let res = Infinity\n for (const bs of boxes) {\n bs.sort((a, b) => b - a)\n if (bs[0] < packages[n - 1]) continue\n let wastes = bs[0] * n - preSum[n]\n let last = bs[0]\n for (let i = 1; i < bs.length; i++) {\n const b = bs[i]\n const j = upperBound(b)\n if (j <= 0) {\n break\n }\n wastes -= (last - b) * j\n last = b\n }\n res = Math.min(res, wastes)\n }\n return res === Infinity ? -1 : res % mod\n}\n\n// another\n\n/**\n * @param {number[]} packages\n * @param {number[][]} boxes\n * @return {number}\n */\nvar minWastedSpace = function (packages, boxes) {\n packages.sort(function (a, b) {\n return a - b\n })\n let count = 0,\n b,\n wastage,\n minWastage = Number.MAX_SAFE_INTEGER,\n flag = false\n for (let i = 0; i < boxes.length; i++) {\n boxes[i].sort(function (a, b) {\n return a - b\n })\n b = 0\n wastage = 0\n count = 0\n if (boxes[i][boxes[i].length - 1] < packages[packages.length - 1]) {\n //This supplier's largest box is smaller than our larget package, this supplier can't be used\n continue\n }\n while (count < packages.length && b < boxes[i].length) {\n if (packages[count] <= boxes[i][b]) {\n wastage += boxes[i][b] - packages[count]\n if (wastage > minWastage) {\n //Need not to porcess this supplier if wastage has already been more than minWastage\n break\n }\n count++\n } else {\n b++\n }\n }\n if (count === packages.length) {\n flag = true //We have found atleas 1 answer\n if (wastage < minWastage) {\n minWastage = wastage\n }\n }\n }\n if (flag === false) {\n return -1\n }\n return minWastage % 1000000007\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720e83", + "questionid": 952, + "title": "Maximum Alternating Subsequence Sum", + "slug": "maximum-alternating-subsequence-sum", + "description": "The alternating sum of a 0-indexed array is defined as the sum of the elements at even indices minus the sum of the elements at odd indices. Given an array nums, return the maximum alternating sum of any subsequence of nums (after reindexing the elements of the subsequence). A subsequence of an array is a new array generated from the original array by deleting some elements (possibly none) without changing the remaining elements' relative order. For example, [2,7,4] is a subsequence of [4,2,3,7,2,1,4] (the underlined elements), while [2,4,2] is not. ", + "category": [ + "Array", + "Dynamic Programming" + ], + "complexity": "Medium", + "successrate": 59.1, + "totalsubmissions": 25840, + "totalaccepted": 15277, + "likes": 635, + "dislikes": 11, + "hints": "Is only tracking a single sum enough to solve the problem? How does tracking an odd sum and an even sum reduce the number of states?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [4,2,5,3]", + "expected_output": "7", + "explanation": "It is optimal to choose the subsequence [4,2,5] with alternating sum (4 + 5) - 2 = 7." + }, + { + "example_num": 2, + "expected_input": "nums = [5,6,7,8]", + "expected_output": "8", + "explanation": "It is optimal to choose the subsequence [8] with alternating sum 8." + }, + { + "example_num": 3, + "expected_input": "nums = [6,2,1,2,4,5]", + "expected_output": "10", + "explanation": "It is optimal to choose the subsequence [6,1,5] with alternating sum (6 + 5) - 1 = 10." + } + ], + "solution": "/**\n * @param {number[]} nums\n * @return {number}\n */\nconst maxAlternatingSum = function(nums) {\n let odd = 0, even = 0;\n for (let a of nums) {\n even = Math.max(even, odd + a);\n odd = even - a;\n }\n return even;\n};\n\n// another\n\n/**\n * @param {number[]} nums\n * @return {number}\n */\nconst maxAlternatingSum = function(nums) {\n let res = nums[0]\n for(let i = 1; i < nums.length; i++) {\n res += Math.max(nums[i] - nums[i - 1], 0)\n }\n return res\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720e8d", + "questionid": 962, + "title": "Maximum Product Difference Between Two Pairs", + "slug": "maximum-product-difference-between-two-pairs", + "description": "The product difference between two pairs (a, b) and (c, d) is defined as (a * b) - (c * d). Given an integer array nums, choose four distinct indices w, x, y, and z such that the product difference between pairs (nums[w], nums[x]) and (nums[y], nums[z]) is maximized. Return the maximum such product difference. ", + "category": [ + "Array", + "Sorting" + ], + "complexity": "Easy", + "successrate": 81.3, + "totalsubmissions": 58929, + "totalaccepted": 47905, + "likes": 401, + "dislikes": 20, + "hints": "If you only had to find the maximum product of 2 numbers in an array, which 2 numbers should you choose? We only need to worry about 4 numbers in the array.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [5,6,2,7,4]", + "expected_output": "34", + "explanation": "We can choose indices 1 and 3 for the first pair (6, 7) and indices 2 and 4 for the second pair (2, 4).\r\nThe product difference is (6 * 7) - (2 * 4) = 34." + }, + { + "example_num": 2, + "expected_input": "nums = [4,2,5,9,7,4,8]", + "expected_output": "64", + "explanation": "We can choose indices 3 and 6 for the first pair (9, 8) and indices 1 and 5 for the second pair (2, 4).\r\nThe product difference is (9 * 8) - (2 * 4) = 64." + } + ], + "solution": "/**\n * @param {number[]} nums\n * @return {number}\n */\nconst maxProductDifference = function(nums) {\n nums.sort((a, b) => a - b)\n const n = nums.length\n return nums[n - 1] * nums[n - 2] - nums[0] * nums[1]\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720e91", + "questionid": 966, + "title": "Eliminate Maximum Number of Monsters", + "slug": "eliminate-maximum-number-of-monsters", + "description": "You are playing a video game where you are defending your city from a group of n monsters. You are given a 0-indexed integer array dist of size n, where dist[i] is the initial distance in kilometers of the ith monster from the city. The monsters walk toward the city at a constant speed. The speed of each monster is given to you in an integer array speed of size n, where speed[i] is the speed of the ith monster in kilometers per minute. You have a weapon that, once fully charged, can eliminate a single monster. However, the weapon takes one minute to charge.The weapon is fully charged at the very start. You lose when any monster reaches your city. If a monster reaches the city at the exact moment the weapon is fully charged, it counts as a loss, and the game ends before you can use your weapon. Return the maximum number of monsters that you can eliminate before you lose, or n if you can eliminate all the monsters before they reach the city. ", + "category": [ + "Array", + "Greedy", + "Sorting" + ], + "complexity": "Medium", + "successrate": 37.6, + "totalsubmissions": 42275, + "totalaccepted": 15880, + "likes": 306, + "dislikes": 48, + "hints": "Find the amount of time it takes each monster to arrive. Find the order in which the monsters will arrive.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "dist = [1,3,4], speed = [1,1,1]", + "expected_output": "3", + "explanation": "In the beginning, the distances of the monsters are [1,3,4]. You eliminate the first monster.\nAfter a minute, the distances of the monsters are [X,2,3]. You eliminate the second monster.\nAfter a minute, the distances of the monsters are [X,X,2]. You eliminate the third monster.\nAll 3 monsters can be eliminated." + }, + { + "example_num": 2, + "expected_input": "dist = [1,1,2,3], speed = [1,1,1,1]", + "expected_output": "1", + "explanation": "In the beginning, the distances of the monsters are [1,1,2,3]. You eliminate the first monster.\nAfter a minute, the distances of the monsters are [X,0,1,2], so you lose.\nYou can only eliminate 1 monster." + }, + { + "example_num": 3, + "expected_input": "dist = [3,2,4], speed = [5,3,2]", + "expected_output": "1", + "explanation": "In the beginning, the distances of the monsters are [3,2,4]. You eliminate the first monster.\nAfter a minute, the distances of the monsters are [X,0,2], so you lose.\nYou can only eliminate 1 monster." + } + ], + "solution": "/**\n * @param {number[]} dist\n * @param {number[]} speed\n * @return {number}\n */\nconst eliminateMaximum = function(dist, speed) {\n const pq = new PriorityQueue((a, b) => a[0] / a[1] < b[0] / b[1])\n const n = dist.length\n for(let i = 0; i < n; i++) {\n pq.push([dist[i], speed[i]])\n }\n let res = 0\n while(true) {\n if(pq.isEmpty()) break\n if(pq.peek()[0] < 0) break\n const tmp = pq.pop()\n if(tmp[0] <= res * tmp[1]) break\n res++\n }\n \n return res\n};\n\nclass PriorityQueue {\n constructor(comparator = (a, b) => a > b) {\n this.heap = []\n this.top = 0\n this.comparator = comparator\n }\n size() {\n return this.heap.length\n }\n isEmpty() {\n return this.size() === 0\n }\n peek() {\n return this.heap[this.top]\n }\n push(...values) {\n values.forEach((value) => {\n this.heap.push(value)\n this.siftUp()\n })\n return this.size()\n }\n pop() {\n const poppedValue = this.peek()\n const bottom = this.size() - 1\n if (bottom > this.top) {\n this.swap(this.top, bottom)\n }\n this.heap.pop()\n this.siftDown()\n return poppedValue\n }\n replace(value) {\n const replacedValue = this.peek()\n this.heap[this.top] = value\n this.siftDown()\n return replacedValue\n }\n\n parent = (i) => ((i + 1) >>> 1) - 1\n left = (i) => (i << 1) + 1\n right = (i) => (i + 1) << 1\n greater = (i, j) => this.comparator(this.heap[i], this.heap[j])\n swap = (i, j) => ([this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]])\n siftUp = () => {\n let node = this.size() - 1\n while (node > this.top && this.greater(node, this.parent(node))) {\n this.swap(node, this.parent(node))\n node = this.parent(node)\n }\n }\n siftDown = () => {\n let node = this.top\n while (\n (this.left(node) < this.size() && this.greater(this.left(node), node)) ||\n (this.right(node) < this.size() && this.greater(this.right(node), node))\n ) {\n let maxChild =\n this.right(node) < this.size() &&\n this.greater(this.right(node), this.left(node))\n ? this.right(node)\n : this.left(node)\n this.swap(node, maxChild)\n node = maxChild\n }\n }\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720e93", + "questionid": 968, + "title": "Longest Common Subpath", + "slug": "longest-common-subpath", + "description": "There is a country of n cities numbered from 0 to n - 1. In this country, there is a road connecting every pair of cities. There are m friends numbered from 0 to m - 1 who are traveling through the country. Each one of them will take a path consisting of some cities. Each path is represented by an integer array that contains the visited cities in order. The path may contain a city more than once, but the same city will not be listed consecutively. Given an integer n and a 2D integer array paths where paths[i] is an integer array representing the path of the ith friend, return the length of the longest common subpath that is shared by every friend's path, or 0 if there is no common subpath at all. A subpath of a path is a contiguous sequence of cities within that path. ", + "category": [ + "Array", + "Binary Search", + "Rolling Hash", + "Suffix Array", + "Hash Function" + ], + "complexity": "Hard", + "successrate": 28.3, + "totalsubmissions": 16630, + "totalaccepted": 4707, + "likes": 267, + "dislikes": 24, + "hints": "If there is a common path with length x, there is for sure a common path of length y where y < x. We can use binary search over the answer with the range [0, min(path[i].length)]. Using binary search, we want to verify if we have a common path of length m. We can achieve this using hashing.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 5, paths = [[0,1,2,3,4],\n [2,3,4],\n [4,0,1,2,3]]", + "expected_output": "2", + "explanation": "The longest common subpath is [2,3]." + }, + { + "example_num": 2, + "expected_input": "n = 3, paths = [[0],[1],[2]]", + "expected_output": "0", + "explanation": "There is no common subpath shared by the three paths." + }, + { + "example_num": 3, + "expected_input": "n = 5, paths = [[0,1,2,3,4],\n [4,3,2,1,0]]", + "expected_output": "1", + "explanation": "The possible longest common subpaths are [0], [1], [2], [3], and [4]. All have a length of 1." + } + ], + "solution": "/**\n * @param {number} n\n * @param {number[][]} paths\n * @return {number}\n */\nconst longestCommonSubpath = function(n, paths) {\n if (!paths.length) return 0\n let arr = paths[0]\n for (const path of paths) if (path.length < arr.length) arr = path\n return new Sam(arr).longestCommonSubpath(paths) \n};\n\nclass State {\n constructor(len, link, next) {\n this.len = len\n this.link = link\n this.next = new Map(next)\n this.ans = len\n this.revLink = []\n this.max = 0\n }\n}\n\n/**\n * @param p {State}\n * @return boolean\n */\nfunction dfs(p) {\n let hasNext = false\n for (const q of p.revLink) {\n hasNext = dfs(q) || hasNext\n }\n if (hasNext) p.max = p.len\n return p.max > 0\n}\n\nclass Sam {\n newState(len, link, next) {\n const state = new State(len, link, next)\n this.container.push(state)\n return state\n }\n\n constructor(path) {\n this.container = []\n const root = this.newState(0, null)\n let last = root\n for (const x of path) {\n const cur = this.newState(last.len + 1, root)\n for (let p = last; p; p = p.link) {\n const q = p.next.get(x)\n if (!q) {\n p.next.set(x, cur)\n continue\n }\n if (q.len === p.len + 1) {\n cur.link = q\n } else {\n const clone = this.newState(p.len + 1, q.link, q.next)\n for (; p && p.next.get(x) === q; p = p.link) p.next.set(x, clone)\n cur.link = q.link = clone\n }\n break\n }\n last = cur\n }\n for (const state of this.container)\n if (state.link) state.link.revLink.push(state)\n }\n\n visit(path) {\n for (const state of this.container) state.max = 0\n const root = this.container[0]\n let p = root\n let len = 0\n for (const x of path) {\n for (; ; p = p.link, len = p.len) {\n const q = p.next.get(x)\n if (q) {\n p = q\n p.max = Math.max(p.max, ++len)\n break\n }\n if (!p.link) break\n }\n }\n dfs(root)\n for (const state of this.container)\n state.ans = Math.min(state.ans, state.max)\n }\n\n longestCommonSubpath(paths) {\n for (const path of paths) this.visit(path)\n let ans = 0\n for (const state of this.container) ans = Math.max(ans, state.ans)\n return ans\n }\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720e95", + "questionid": 970, + "title": "The Number of the Smallest Unoccupied Chair", + "slug": "the-number-of-the-smallest-unoccupied-chair", + "description": "There is a party where n friends numbered from 0 to n - 1 are attending. There is an infinite number of chairs in this party that are numbered from 0 to infinity. When a friend arrives at the party, they sit on the unoccupied chair with the smallest number. When a friend leaves the party, their chair becomes unoccupied at the moment they leave. If another friend arrives at that same moment, they can sit in that chair. You are given a 0-indexed 2D integer array times where times[i] = [arrivali, leavingi], indicating the arrival and leaving times of the ith friend respectively, and an integer targetFriend. All arrival times are distinct. Return the chair number that the friend numbered targetFriend will sit on. ", + "category": [ + "Array", + "Heap (Priority Queue)", + "Ordered Set" + ], + "complexity": "Medium", + "successrate": 38.9, + "totalsubmissions": 27895, + "totalaccepted": 10846, + "likes": 371, + "dislikes": 18, + "hints": "Sort times by arrival time. for each arrival_i find the smallest unoccupied chair and mark it as occupied until leaving_i.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "times = [[1,4],[2,3],[4,6]], targetFriend = 1", + "expected_output": "1", + "explanation": "- Friend 0 arrives at time 1 and sits on chair 0.\n- Friend 1 arrives at time 2 and sits on chair 1.\n- Friend 1 leaves at time 3 and chair 1 becomes empty.\n- Friend 0 leaves at time 4 and chair 0 becomes empty.\n- Friend 2 arrives at time 4 and sits on chair 0.\nSince friend 1 sat on chair 1, we return 1." + }, + { + "example_num": 2, + "expected_input": "times = [[3,10],[1,5],[2,6]], targetFriend = 0", + "expected_output": "2", + "explanation": "- Friend 1 arrives at time 1 and sits on chair 0.\n- Friend 2 arrives at time 2 and sits on chair 1.\n- Friend 0 arrives at time 3 and sits on chair 2.\n- Friend 1 leaves at time 5 and chair 0 becomes empty.\n- Friend 2 leaves at time 6 and chair 1 becomes empty.\n- Friend 0 leaves at time 10 and chair 2 becomes empty.\nSince friend 0 sat on chair 2, we return 2." + } + ], + "solution": "/**\n * @param {number[][]} times\n * @param {number} targetFriend\n * @return {number}\n */\nconst smallestChair = function(times, targetFriend) {\n times.forEach((e, i) => e[2] = i)\n times.sort((a, b) => a[0] - b[0])\n const pq = new PQ((a, b) => a[1] < b[1])\n const available = new PQ((a, b) => a < b)\n const n = times.length\n for(let i = 0; i < n; i++) {\n available.push(i)\n }\n const seat = available.pop()\n times[0].push(seat)\n pq.push(times[0])\n if(times[0][2] === targetFriend) return seat\n for(let i = 1; i < n; i++) {\n const el = times[i]\n const [s, e, idx] = el\n while(!pq.isEmpty() && pq.peek()[1] <= s) {\n const tmp = pq.pop()\n available.push(tmp[3])\n }\n const seat = available.pop()\n if(targetFriend === idx) return seat\n el.push(seat)\n pq.push(el)\n }\n \n};\n\nclass PQ {\n constructor(comparator = (a, b) => a > b) {\n this.heap = []\n this.top = 0\n this.comparator = comparator\n }\n size() {\n return this.heap.length\n }\n isEmpty() {\n return this.size() === 0\n }\n peek() {\n return this.heap[this.top]\n }\n push(...values) {\n values.forEach((value) => {\n this.heap.push(value)\n this.siftUp()\n })\n return this.size()\n }\n pop() {\n const poppedValue = this.peek()\n const bottom = this.size() - 1\n if (bottom > this.top) {\n this.swap(this.top, bottom)\n }\n this.heap.pop()\n this.siftDown()\n return poppedValue\n }\n replace(value) {\n const replacedValue = this.peek()\n this.heap[this.top] = value\n this.siftDown()\n return replacedValue\n }\n\n parent = (i) => ((i + 1) >>> 1) - 1\n left = (i) => (i << 1) + 1\n right = (i) => (i + 1) << 1\n greater = (i, j) => this.comparator(this.heap[i], this.heap[j])\n swap = (i, j) => ([this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]])\n siftUp = () => {\n let node = this.size() - 1\n while (node > this.top && this.greater(node, this.parent(node))) {\n this.swap(node, this.parent(node))\n node = this.parent(node)\n }\n }\n siftDown = () => {\n let node = this.top\n while (\n (this.left(node) < this.size() && this.greater(this.left(node), node)) ||\n (this.right(node) < this.size() && this.greater(this.right(node), node))\n ) {\n let maxChild =\n this.right(node) < this.size() &&\n this.greater(this.right(node), this.left(node))\n ? this.right(node)\n : this.left(node)\n this.swap(node, maxChild)\n node = maxChild\n }\n }\n}\n\n// another\n\n/**\n * @param {number[][]} times\n * @param {number} targetFriend\n * @return {number}\n */\nconst smallestChair = function(times, targetFriend) {\n const avail = new PQ((a, b) => a[0] < b[0])\n const occupied = new PQ((a, b) => a[1] < b[1])\n const n = times.length\n for(let i = 0; i < n; i++) {\n avail.push([i, 0])\n }\n times.forEach((e, i) => e.push(i))\n times.sort((a, b) => a[0] === b[0] ? a[1] - b[1] : a[0] - b[0])\n \n for(let i = 0; i < n; i++) {\n let res = -1\n const [s, e, idx] = times[i]\n while(!occupied.isEmpty() && occupied.peek()[1] <= s) {\n avail.push(occupied.pop())\n }\n \n const c = avail.pop()\n res = c[0]\n c[1] = e\n occupied.push(c)\n \n if(idx === targetFriend) {\n return res\n }\n }\n};\n\nclass PQ {\n constructor(comparator = (a, b) => a > b) {\n this.heap = []\n this.top = 0\n this.comparator = comparator\n }\n size() {\n return this.heap.length\n }\n isEmpty() {\n return this.size() === 0\n }\n peek() {\n return this.heap[this.top]\n }\n push(...values) {\n values.forEach((value) => {\n this.heap.push(value)\n this.siftUp()\n })\n return this.size()\n }\n pop() {\n const poppedValue = this.peek()\n const bottom = this.size() - 1\n if (bottom > this.top) {\n this.swap(this.top, bottom)\n }\n this.heap.pop()\n this.siftDown()\n return poppedValue\n }\n replace(value) {\n const replacedValue = this.peek()\n this.heap[this.top] = value\n this.siftDown()\n return replacedValue\n }\n\n parent = (i) => ((i + 1) >>> 1) - 1\n left = (i) => (i << 1) + 1\n right = (i) => (i + 1) << 1\n greater = (i, j) => this.comparator(this.heap[i], this.heap[j])\n swap = (i, j) => ([this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]])\n siftUp = () => {\n let node = this.size() - 1\n while (node > this.top && this.greater(node, this.parent(node))) {\n this.swap(node, this.parent(node))\n node = this.parent(node)\n }\n }\n siftDown = () => {\n let node = this.top\n while (\n (this.left(node) < this.size() && this.greater(this.left(node), node)) ||\n (this.right(node) < this.size() && this.greater(this.right(node), node))\n ) {\n let maxChild =\n this.right(node) < this.size() &&\n this.greater(this.right(node), this.left(node))\n ? this.right(node)\n : this.left(node)\n this.swap(node, maxChild)\n node = maxChild\n }\n }\n}\n\n// another\n\n/**\n * @param {number[][]} times\n * @param {number} targetFriend\n * @return {number}\n */\nconst smallestChair = function (times, targetFriend) {\n const targetArrival = times[targetFriend][0]\n let seatNum = 0\n let res = 0\n const n = times.length\n \n times.sort((a, b) => a[0] - b[0])\n \n const occupied = new PriorityQueue((a, b) => a[0] < b[0])\n const available = new PriorityQueue((a, b) => a < b)\n \n for(let i = 0; i < n; i++) {\n const [arrival, leaving] = times[i]\n while(!occupied.isEmpty() && occupied.peek()[0] <= arrival) {\n available.push(occupied.pop()[1]) \n }\n let seat\n if(!available.isEmpty()) {\n seat = available.pop()\n } else {\n seat = seatNum\n seatNum++\n }\n occupied.push([leaving, seat])\n if(arrival === targetArrival) {\n res = seat\n break\n }\n }\n \n return res\n}\nclass PriorityQueue {\n constructor(comparator = (a, b) => a > b) {\n this.heap = []\n this.top = 0\n this.comparator = comparator\n }\n size() {\n return this.heap.length\n }\n isEmpty() {\n return this.size() === 0\n }\n peek() {\n return this.heap[this.top]\n }\n push(...values) {\n values.forEach((value) => {\n this.heap.push(value)\n this.siftUp()\n })\n return this.size()\n }\n pop() {\n const poppedValue = this.peek()\n const bottom = this.size() - 1\n if (bottom > this.top) {\n this.swap(this.top, bottom)\n }\n this.heap.pop()\n this.siftDown()\n return poppedValue\n }\n replace(value) {\n const replacedValue = this.peek()\n this.heap[this.top] = value\n this.siftDown()\n return replacedValue\n }\n\n parent = (i) => ((i + 1) >>> 1) - 1\n left = (i) => (i << 1) + 1\n right = (i) => (i + 1) << 1\n greater = (i, j) => this.comparator(this.heap[i], this.heap[j])\n swap = (i, j) => ([this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]])\n siftUp = () => {\n let node = this.size() - 1\n while (node > this.top && this.greater(node, this.parent(node))) {\n this.swap(node, this.parent(node))\n node = this.parent(node)\n }\n }\n siftDown = () => {\n let node = this.top\n while (\n (this.left(node) < this.size() && this.greater(this.left(node), node)) ||\n (this.right(node) < this.size() && this.greater(this.right(node), node))\n ) {\n let maxChild =\n this.right(node) < this.size() &&\n this.greater(this.right(node), this.left(node))\n ? this.right(node)\n : this.left(node)\n this.swap(node, maxChild)\n node = maxChild\n }\n }\n}\n\n// another\n\n\n/**\n * @param {number[][]} times\n * @param {number} targetFriend\n * @return {number}\n */\nvar smallestChair = function (times, targetFriend) {\n const [targetArrival] = times[targetFriend]\n const arrivalQueue = times\n const leavingQueue = [...times]\n arrivalQueue.sort((a, b) => a[0] - b[0])\n leavingQueue.sort((a, b) => a[1] - b[1] || a[0] - b[0])\n const chairsByLeaveTime = new Map()\n let chairsCount = 0\n let arriving = 0,\n leaving = 0\n\n while (arriving < arrivalQueue.length) {\n let chairIdx\n const arrival = arrivalQueue[arriving][0]\n const leave = leavingQueue[leaving][1]\n if (arrival < leave) {\n chairIdx = chairsCount++\n } else {\n let freeChairIdx = leaving\n chairIdx = chairsByLeaveTime.get(leavingQueue[freeChairIdx++][0])\n while (arrival >= leavingQueue[freeChairIdx][1]) {\n const nextChair = chairsByLeaveTime.get(leavingQueue[freeChairIdx][0])\n if (chairIdx > nextChair) {\n ;[leavingQueue[leaving], leavingQueue[freeChairIdx]] = [\n leavingQueue[freeChairIdx],\n leavingQueue[leaving],\n ]\n chairIdx = nextChair\n }\n ++freeChairIdx\n }\n ++leaving\n }\n if (targetArrival === arrival) {\n return chairIdx\n }\n chairsByLeaveTime.set(arrival, chairIdx)\n arriving++\n }\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720e96", + "questionid": 971, + "title": "Describe the Painting", + "slug": "describe-the-painting", + "description": "There is a long and thin painting that can be represented by a number line. The painting was painted with multiple overlapping segments where each segment was painted with a unique color. You are given a 2D integer array segments, where segments[i] = [starti, endi, colori] represents the half-closed segment [starti, endi) with colori as the color. The colors in the overlapping segments of the painting were mixed when it was painted. When two or more colors mix, they form a new color that can be represented as a set of mixed colors. For the sake of simplicity, you should only output the sum of the elements in the set rather than the full set. You want to describe the painting with the minimum number of non-overlapping half-closed segments of these mixed colors. These segments can be represented by the 2D array painting where painting[j] = [leftj, rightj, mixj] describes a half-closed segment [leftj, rightj) with the mixed color sum of mixj. Return the 2D array painting describing the finished painting (excluding any parts that are not painted). You may return the segments in any order. A half-closed segment [a, b) is the section of the number line between points a and b including point a and not including point b. ", + "category": [ + "Array", + "Prefix Sum" + ], + "complexity": "Medium", + "successrate": 46.5, + "totalsubmissions": 15676, + "totalaccepted": 7288, + "likes": 275, + "dislikes": 16, + "hints": "Can we sort the segments in a way to help solve the problem? How can we dynamically keep track of the sum of the current segment(s)?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "segments = [[1,4,5],[4,7,7],[1,7,9]]", + "expected_output": "[[1,4,14],[4,7,16]]\nExplanation: The painting can be described as follows:\n- [1,4) is colored {5,9} (with a sum of 14) from the first and third segments.\n- [4,7) is colored {7,9} (with a sum of 16) from the second and third segments.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "segments = [[1,7,9],[6,8,15],[8,10,7]]", + "expected_output": "[[1,6,9],[6,7,24],[7,8,15],[8,10,7]]\nExplanation: The painting can be described as follows:\n- [1,6) is colored 9 from the first segment.\n- [6,7) is colored {9,15} (with a sum of 24) from the first and second segments.\n- [7,8) is colored 15 from the second segment.\n- [8,10) is colored 7 from the third segment.", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "segments = [[1,4,5],[1,4,7],[4,7,1],[4,7,11]]", + "expected_output": "[[1,4,12],[4,7,12]]\nExplanation: The painting can be described as follows:\n- [1,4) is colored {5,7} (with a sum of 12) from the first and second segments.\n- [4,7) is colored {1,11} (with a sum of 12) from the third and fourth segments.\nNote that returning a single segment [1,7) is incorrect because the mixed color sets are different.", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[][]} segments\n * @return {number[][]}\n */\nconst splitPainting = function(segments) {\n const hash = {}\n for(let [s, e, c] of segments) {\n if(hash[s] == null) hash[s] = 0\n if(hash[e] == null) hash[e] = 0\n hash[s] += c\n hash[e] -= c\n }\n const keys = Object.keys(hash)\n keys.sort((a, b) => a - b)\n let prev, color = 0\n const res = []\n for(let k of keys) {\n if(prev != null && color !== 0) res.push([prev,k,color])\n\n prev = k\n color += hash[k]\n } \n return res\n};\n\n// another\n\n/**\n * @param {number[][]} segments\n * @return {number[][]}\n */\nconst splitPainting = function(segments) {\n const sum = {}\n for(const [s, e, v] of segments) {\n if(sum[s] == null) sum[s] = 0\n if(sum[e] == null) sum[e] = 0\n sum[s] += v\n sum[e] -= v\n }\n const keys = Object.keys(sum).map(e => +e)\n keys.sort((a, b) => a - b)\n const res = []\n let pre = 0, s = 0, n = keys.length\n for(let i = 0; i < n; i++) {\n const k = keys[i]\n \n if(s) {\n res.push([pre, k, s])\n }\n s += sum[k]\n pre = k\n }\n \n return res\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720e99", + "questionid": 974, + "title": "Painting a Grid With Three Different Colors", + "slug": "painting-a-grid-with-three-different-colors", + "description": "You are given two integers m and n. Consider an m x n grid where each cell is initially white. You can paint each cell red, green, or blue. All cells must be painted. Return the number of ways to color the grid with no two adjacent cells having the same color. Since the answer can be very large, return it modulo 109 + 7. ", + "category": [ + "Dynamic Programming" + ], + "complexity": "Hard", + "successrate": 57, + "totalsubmissions": 10825, + "totalaccepted": 6171, + "likes": 297, + "dislikes": 16, + "hints": "Represent each colored column by a bitmask based on each cell color. Use bitmasks DP with state (currentCell, prevColumn).", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "m = 1, n = 1", + "expected_output": "3", + "explanation": "The three possible colorings are shown in the image above." + }, + { + "example_num": 2, + "expected_input": "m = 1, n = 2", + "expected_output": "6", + "explanation": "The six possible colorings are shown in the image above." + }, + { + "example_num": 3, + "expected_input": "m = 5, n = 5", + "expected_output": "580986", + "explanation": "" + } + ], + "solution": "/**\n * @param {number} m\n * @param {number} n\n * @return {number}\n */\nconst colorTheGrid = function(m, n) {\n // Get color of the `mask` at `pos`, 2 bit store 1 color\n function getColor(mask, pos) {\n return (mask >> (2 * pos)) & 3\n }\n // Set `color` to the `mask` at `pos`, 2 bit store 1 color\n function setColor(mask, pos, color) {\n return mask | (color << (2 * pos))\n }\n function dfs(r, curColMask, prevColMask, out) {\n // Filled full color for a row\n if(r === m) {\n out.push(curColMask)\n return\n }\n // Try colors i in [1=RED, 2=GREEN, 3=BLUE]\n for(let i = 1; i <= 3; i++) {\n if(getColor(prevColMask, r) !== i && (r === 0 || getColor(curColMask, r - 1) !== i)) {\n dfs(r + 1, setColor(curColMask, r, i), prevColMask, out)\n }\n }\n }\n // Generate all possible columns we can draw, if the previous col is `prevColMask`\n function neighbor(prevColMask) {\n let out = []\n dfs(0, 0, prevColMask, out)\n return out\n }\n const mod = 10 ** 9 + 7\n const memo = {}\n function dp(c, prevColMask) {\n // Found a valid way\n if(c === n) return 1\n if(memo[`${c},${prevColMask}`] != null) return memo[`${c},${prevColMask}`]\n let res = 0\n const arr = neighbor(prevColMask)\n for(let e of arr) {\n res = (res + dp(c + 1, e)) % mod\n }\n memo[`${c},${prevColMask}`] = res\n return res\n }\n \n return dp(0, 0)\n \n};\n\n// another\n\n/**\n * @param {number} m\n * @param {number} n\n * @return {number}\n */\nconst colorTheGrid = function(m, n) {\n const mod = 10 ** 9 + 7\n const colors = [1, 2, 3]\n const memoDp = {}, memoOpts = {}\n function getColor(pos, preMask) {\n return (preMask >> (pos * 2)) & 3\n }\n function setColor(pos, color, curMask) {\n return curMask | (color << (pos * 2))\n }\n function dfs(pos, curMask, preMask, res) {\n if(pos === m) {\n res.push(curMask)\n return\n }\n for(let c of colors) {\n if(getColor(pos, preMask) !== c && (pos === 0 || getColor(pos - 1, curMask) !== c)) {\n dfs(pos + 1, setColor(pos, c, curMask), preMask, res)\n }\n }\n }\n function curOpts(preMask) {\n if (memoOpts[preMask]) return memoOpts[preMask]\n const res = []\n dfs(0, 0, preMask, res)\n memoOpts[preMask] = res\n return res\n }\n function dp(col, preMask) {\n const k = `${col},${preMask}`\n if(col === n) return 1\n if(memoDp[k]) return memoDp[k]\n let res = 0\n const cur = curOpts(preMask)\n for(let mask of cur) {\n res = (res + dp(col + 1, mask)) % mod\n }\n memoDp[k] = res\n return res\n }\n\n return dp(0, 0)\n};\n\n// another\n\n/**\n * @param {number} m\n * @param {number} n\n * @return {number}\n */\nconst colorTheGrid = function(m, n) {\n const mod = 1e9 + 7\n const limit = 1 << (2 * m)\n const memo = Array.from({ length: n }, () => Array(limit))\n \n return dp(0, 0)\n \n function dp(col, preColMask) {\n if(col === n) return 1\n let res = 0\n \n if(memo[col][preColMask] != null) return memo[col][preColMask]\n const curColMasks = []\n dfs(preColMask, 0, 0, curColMasks)\n for(const colMask of curColMasks) {\n res = (res + dp(col + 1, colMask)) % mod\n }\n return memo[col][preColMask] = res\n }\n \n function dfs(preColMask, curColMask, row, res) {\n if(row === m) {\n res.push(curColMask)\n return\n }\n for(let i = 1; i <= 3; i++) {\n if(getColor(preColMask, row) !== i && (row === 0 || getColor(curColMask, row - 1) !== i)) {\n dfs(preColMask, setColor(curColMask, row, i) ,row + 1, res)\n }\n }\n }\n \n function getColor(mask, row) {\n return (mask >> (2 * row)) & 3 \n }\n function setColor(mask, row, val) {\n return mask | (val << (2 * row)) \n }\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720e9f", + "questionid": 980, + "title": "Three Divisors", + "slug": "three-divisors", + "description": "Given an integer n, return true if n has exactly three positive divisors. Otherwise, return false. An integer m is a divisor of n if there exists an integer k such that n = k * m. ", + "category": [ + "Math" + ], + "complexity": "Easy", + "successrate": 56.5, + "totalsubmissions": 45242, + "totalaccepted": 25550, + "likes": 218, + "dislikes": 15, + "hints": "You can count the number of divisors and just check that they are 3 Beware of the case of n equal 1 as some solutions might fail in it", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 2", + "expected_output": "false\nExplantion: 2 has only two divisors: 1 and 2.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "n = 4", + "expected_output": "true\nExplantion: 4 has three divisors: 1, 2, and 4.", + "explanation": "" + } + ], + "solution": "/**\n * @param {number} n\n * @return {boolean}\n */\nconst isThree = function(n) {\n if(n == 1) return false;\n let a = ~~Math.sqrt(n);\n if(n != a * a) return false;\n for(let i = 2; i < a; i++) {\n if (n % i == 0)\n return false;\n }\n return true;\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720ea1", + "questionid": 982, + "title": "Count Number of Special Subsequences", + "slug": "count-number-of-special-subsequences", + "description": "A sequence is special if it consists of a positive number of 0s, followed by a positive number of 1s, then a positive number of 2s. Given an array nums (consisting of only integers 0, 1, and 2), return the number of different subsequences that are special. Since the answer may be very large, return it modulo 109 + 7. A subsequence of an array is a sequence that can be derived from the array by deleting some or no elements without changing the order of the remaining elements. Two subsequences are different if the set of indices chosen are different. ", + "category": [ + "Array", + "Dynamic Programming" + ], + "complexity": "Hard", + "successrate": 50.9, + "totalsubmissions": 14394, + "totalaccepted": 7326, + "likes": 341, + "dislikes": 6, + "hints": "Can we first solve a simpler problem? Counting the number of subsequences with 1s followed by 0s. How can we keep track of the partially matched subsequences to help us find the answer?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [0,1,2,2]", + "expected_output": "3", + "explanation": "The special subsequences are bolded [0,1,2,2], [0,1,2,2], and [0,1,2,2]." + }, + { + "example_num": 2, + "expected_input": "nums = [2,2,0,0]", + "expected_output": "0", + "explanation": "There are no special subsequences in [2,2,0,0]." + }, + { + "example_num": 3, + "expected_input": "nums = [0,1,2,0,1,2]", + "expected_output": "7", + "explanation": "The special subsequences are bolded:\n- [0,1,2,0,1,2]\n- [0,1,2,0,1,2]\n- [0,1,2,0,1,2]\n- [0,1,2,0,1,2]\n- [0,1,2,0,1,2]\n- [0,1,2,0,1,2]\n- [0,1,2,0,1,2]" + } + ], + "solution": "/*\n * @lc app=leetcode id=1955 lang=javascript\n *\n * [1955] Count Number of Special Subsequences\n */\n\n// @lc code=start\n/**\n * @param {number[]} nums\n * @return {number}\n */\nconst countSpecialSubsequences = function (nums) {\n const dp = Array(3).fill(0),\n mod = 10 ** 9 + 7\n for (let e of nums) {\n dp[e] = (((dp[e] + dp[e]) % mod) + (e > 0 ? dp[e - 1] : 1)) % mod\n }\n return dp[2]\n}\n\n// another\n\n/**\n * @param {number[]} nums\n * @return {number}\n */\nconst countSpecialSubsequences = function(nums) {\n const mod = 10 ** 9 + 7\n const dp = Array.from({length: 10 **5 + 1}, () => Array(4).fill(-1))\n let n = nums.length, a = nums\n return f(0, 0)\n function f(index, firstMandatory) {\n if (index == n && firstMandatory == 3) {\n return 1;\n }\n if (index == n) {\n return 0;\n }\n if (dp[index][firstMandatory] >= 0) {\n return dp[index][firstMandatory];\n }\n let result = 0;\n if (a[index] == firstMandatory) {\n result = (result +\n f(index + 1, firstMandatory) +\n f(index + 1, firstMandatory + 1)\n ) % mod;\n }\n result = (result + f(index + 1, firstMandatory)) % mod;\n\n return dp[index][firstMandatory] = result;\n }\n};\n\n\n\n\n\n" + }, + { + "_id": "66f925ddfdfb8e1665720ea4", + "questionid": 985, + "title": "Check If String Is a Prefix of Array", + "slug": "check-if-string-is-a-prefix-of-array", + "description": "Given a string s and an array of strings words, determine whether s is a prefix string of words. A string s is a prefix string of words if s can be made by concatenating the first k strings in words for some positive k no larger than words.length. Return true if s is a prefix string of words, or false otherwise. ", + "category": [ + "Array", + "String" + ], + "complexity": "Easy", + "successrate": 54.7, + "totalsubmissions": 45019, + "totalaccepted": 24606, + "likes": 212, + "dislikes": 31, + "hints": "There are only words.length prefix strings. Create all of them and see if s is one of them.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "iloveleetcode", words = ["i","love","leetcode","apples"]", + "expected_output": "true", + "explanation": "s can be made by concatenating "i", "love", and "leetcode" together." + }, + { + "example_num": 2, + "expected_input": "s = "iloveleetcode", words = ["apples","i","love","leetcode"]", + "expected_output": "false", + "explanation": "It is impossible to make s using a prefix of arr." + } + ], + "solution": "/**\n * @param {string} s\n * @param {string[]} words\n * @return {boolean}\n */\nconst isPrefixString = function(s, words) {\n let tmp = ''\n for(let w of words) {\n tmp += w\n if(tmp === s) return true\n }\n return false\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720eae", + "questionid": 995, + "title": "Number of Unique Good Subsequences", + "slug": "number-of-unique-good-subsequences", + "description": "You are given a binary string binary. A subsequence of binary is considered good if it is not empty and has no leading zeros (with the exception of \"0\"). Find the number of unique good subsequences of binary. Return the number of unique good subsequences of binary. Since the answer may be very large, return it modulo 109 + 7. A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements. ", + "category": [ + "String", + "Dynamic Programming" + ], + "complexity": "Hard", + "successrate": 51.9, + "totalsubmissions": 13193, + "totalaccepted": 6850, + "likes": 369, + "dislikes": 7, + "hints": "The number of unique good subsequences is equal to the number of unique decimal values there are for all possible subsequences. Find the answer at each index based on the previous indexes' answers.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "binary = "001"", + "expected_output": "2", + "explanation": "The good subsequences of binary are ["0", "0", "1"].\nThe unique good subsequences are "0" and "1"." + }, + { + "example_num": 2, + "expected_input": "binary = "11"", + "expected_output": "2", + "explanation": "The good subsequences of binary are ["1", "1", "11"].\nThe unique good subsequences are "1" and "11"." + }, + { + "example_num": 3, + "expected_input": "binary = "101"", + "expected_output": "5", + "explanation": "The good subsequences of binary are ["1", "0", "1", "10", "11", "101"]. \nThe unique good subsequences are "0", "1", "10", "11", and "101"." + } + ], + "solution": "/**\n * @param {string} binary\n * @return {number}\n */\nconst numberOfUniqueGoodSubsequences = function (binary) {\n const n = binary.length,\n P = 1e9 + 7\n let first1Position = -1,\n first0Position = -1\n for (let i = 0; i < binary.length; i++) {\n if (binary[i] === '0' && first0Position == -1) {\n first0Position = i\n }\n if (binary[i] === '1' && first1Position == -1) {\n first1Position = i\n }\n if(first0Position !== -1 && first1Position !== -1) break\n }\n if (first1Position === -1) return 1\n if (first0Position === -1) return n\n\n const next0 = new Array(n).fill(0)\n const next1 = new Array(n).fill(0)\n let nextZero = -1,\n nextOne = -1\n for (let i = binary.length - 1; i >= 0; i--) {\n next0[i] = nextZero\n next1[i] = nextOne\n if (binary[i] === '0') {\n nextZero = i\n } else {\n nextOne = i\n }\n }\n const dp = new Array(n).fill(-1)\n return (1 + fn(first1Position)) % P\n\n function fn(index) {\n if (index == n) return 0\n if (dp[index] !== -1) return dp[index]\n let result = 1\n if (next0[index] >= 0) {\n result += fn(next0[index])\n result %= P\n }\n if (next1[index] >= 0) {\n result += fn(next1[index])\n result %= P\n }\n return (dp[index] = result)\n }\n}\n\n// another\n\n/**\n * @param {string} binary\n * @return {number}\n */\nconst numberOfUniqueGoodSubsequences = function (binary) {\n const n = binary.length,\n mod = 1e9 + 7\n let hasZero = 0, ends1 = 0, ends0 = 0\n for(let ch of binary) {\n if(ch === '1') {\n ends1 = (ends1 + ends0 + 1) % mod\n } else {\n ends0 = (ends1 + ends0) % mod\n hasZero = 1\n }\n }\n return (ends1 + ends0 + hasZero) % mod\n}\n\n" + }, + { + "_id": "66f925ddfdfb8e1665720eaf", + "questionid": 996, + "title": "Find Original Array From Doubled Array", + "slug": "find-original-array-from-doubled-array", + "description": "An integer array original is transformed into a doubled array changed by appending twice the value of every element in original, and then randomly shuffling the resulting array. Given an array changed, return original if changed is a doubled array. If changed is not a doubled array, return an empty array. The elements in original may be returned in any order. ", + "category": [ + "Array", + "Hash Table", + "Greedy", + "Sorting" + ], + "complexity": "Medium", + "successrate": 38, + "totalsubmissions": 105116, + "totalaccepted": 39908, + "likes": 571, + "dislikes": 44, + "hints": "If changed is a doubled array, you should be able to delete elements and their doubled values until the array is empty. Which element is guaranteed to not be a doubled value? It is the smallest element. After removing the smallest element and its double from changed, is there another number that is guaranteed to not be a doubled value?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "changed = [1,3,4,2,6,8]", + "expected_output": "[1,3,4]", + "explanation": "One possible original array could be [1,3,4]:\n- Twice the value of 1 is 1 * 2 = 2.\n- Twice the value of 3 is 3 * 2 = 6.\n- Twice the value of 4 is 4 * 2 = 8.\nOther original arrays could be [4,3,1] or [3,1,4]." + }, + { + "example_num": 2, + "expected_input": "changed = [6,3,0,1]", + "expected_output": "[]", + "explanation": "changed is not a doubled array." + }, + { + "example_num": 3, + "expected_input": "changed = [1]", + "expected_output": "[]", + "explanation": "changed is not a doubled array." + } + ], + "solution": "/**\n * @param {number[]} changed\n * @return {number[]}\n */\n const findOriginalArray = function(changed) {\n const n = changed.length, res = [], { abs } = Math\n if(n % 2 === 1 || n === 0) return res\n const hash = {}\n for(let e of changed) {\n if(hash[e] == null) hash[e] = 0\n hash[e]++\n }\n const keys = Object.keys(hash)\n keys.sort((a, b) => abs(a) - abs(b))\n\n for(let k of keys) {\n if(hash[k] > (hash[k * 2] || 0)) return []\n for(let i = 0; i < hash[k]; i++) {\n res.push(k)\n hash[2 * k]--\n }\n }\n\n return res\n};\n\n// another\n\n/**\n * @param {number[]} changed\n * @return {number[]}\n */\n const findOriginalArray = function(changed) {\n const n = changed.length, res = []\n if(n % 2 === 1 || n === 0) return res\n const hash = {}\n for(let e of changed) {\n if(hash[e] == null) hash[e] = 0\n hash[e]++\n }\n changed.sort((a, b) => a - b)\n\n for(let i = 0, len = n; i < len; i++) {\n const cur = changed[i], dVal = cur * 2\n if (cur === 0 && hash[cur] % 2 === 1) continue\n if(hash[dVal] && hash[cur]) {\n res.push(cur)\n hash[dVal]--\n hash[cur]--\n }\n }\n return res.length === n / 2 ? res : []\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720eb0", + "questionid": 997, + "title": "Find if Path Exists in Graph", + "slug": "find-if-path-exists-in-graph", + "description": "There is a bi-directional graph with n vertices, where each vertex is labeled from 0 to n - 1 (inclusive). The edges in the graph are represented as a 2D integer array edges, where each edges[i] = [ui, vi] denotes a bi-directional edge between vertex ui and vertex vi. Every vertex pair is connected by at most one edge, and no vertex has an edge to itself. You want to determine if there is a valid path that exists from vertex source to vertex destination. Given edges and the integers n, source, and destination, return true if there is a valid path from source to destination, or false otherwise. ", + "category": [ + "Depth-First Search", + "Breadth-First Search", + "Graph" + ], + "complexity": "Easy", + "successrate": 50.2, + "totalsubmissions": 164420, + "totalaccepted": 82591, + "likes": 888, + "dislikes": 51, + "hints": "", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 3, edges = [[0,1],[1,2],[2,0]], source = 0, destination = 2", + "expected_output": "true", + "explanation": "There are two paths from vertex 0 to vertex 2:\n- 0 → 1 → 2\n- 0 → 2" + }, + { + "example_num": 2, + "expected_input": "n = 6, edges = [[0,1],[0,2],[3,5],[5,4],[4,3]], source = 0, destination = 5", + "expected_output": "false", + "explanation": "There is no path from vertex 0 to vertex 5." + } + ], + "solution": "/**\n * @param {number} n\n * @param {number[][]} edges\n * @param {number} start\n * @param {number} end\n * @return {boolean}\n */\nconst validPath = function(n, edges, start, end) {\n const graph = {}\n for(const [u, v] of edges) {\n if(graph[u] == null) graph[u] = new Set()\n if(graph[v] == null) graph[v] = new Set()\n graph[u].add(v)\n graph[v].add(u)\n }\n const q = [start], visited = new Set()\n visited.add(start)\n while(q.length) {\n const cur = q.shift()\n if(cur === end) return true\n for(const next of graph[cur]) {\n if(visited.has(next)) continue\n q.push(next)\n visited.add(next)\n }\n }\n\n return false\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720e98", + "questionid": 973, + "title": "Unique Length-3 Palindromic Subsequences", + "slug": "unique-length-3-palindromic-subsequences", + "description": "Given a string s, return the number of unique palindromes of length three that are a subsequence of s. Note that even if there are multiple ways to obtain the same subsequence, it is still only counted once. A palindrome is a string that reads the same forwards and backwards. A subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters. ", + "category": [ + "Hash Table", + "String", + "Prefix Sum" + ], + "complexity": "Medium", + "successrate": 51.1, + "totalsubmissions": 30682, + "totalaccepted": 15670, + "likes": 409, + "dislikes": 11, + "hints": "What is the maximum number of length-3 palindromic strings? How can we keep track of the characters that appeared to the left of a given position?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "aabca"", + "expected_output": "3", + "explanation": "The 3 palindromic subsequences of length 3 are:\n- "aba" (subsequence of "aabca")\n- "aaa" (subsequence of "aabca")\n- "aca" (subsequence of "aabca")" + }, + { + "example_num": 2, + "expected_input": "s = "adc"", + "expected_output": "0", + "explanation": "There are no palindromic subsequences of length 3 in "adc"." + }, + { + "example_num": 3, + "expected_input": "s = "bbcbaba"", + "expected_output": "4", + "explanation": "The 4 palindromic subsequences of length 3 are:\n- "bbb" (subsequence of "bbcbaba")\n- "bcb" (subsequence of "bbcbaba")\n- "bab" (subsequence of "bbcbaba")\n- "aba" (subsequence of "bbcbaba")" + } + ], + "solution": "/**\n * @param {string} s\n * @return {number}\n */\nconst countPalindromicSubsequence = function(s) {\n const first = Array(26).fill(Infinity), last = Array(26).fill(0)\n let res = 0\n const n = s.length, a = 'a'.charCodeAt(0)\n for(let i = 0; i < n; i++) {\n const code = s[i].charCodeAt(0)\n first[code - a] = Math.min(i, first[code - a])\n last[code - a] = i\n }\n\n for(let i = 0; i < 26; i++) {\n if(last[i] - 1 > first[i]) {\n const tmp = s.slice(first[i] + 1, last[i])\n const set = new Set()\n for(let ch of tmp) set.add(ch)\n res += set.size\n }\n }\n\n return res\n};\n\n// another\n\n\n/**\n * @param {string} s\n * @return {number}\n */\nconst countPalindromicSubsequence = (s) => {\n let res = 0;\n for (let i = 0; i < 26; i++) {\n for (let j = 0; j < 26; j++) {\n let len = 0;\n for (const c of s) {\n if(len === 3) break\n if (len == 0) {\n if (c.charCodeAt() - 97 == i) len++; // first char\n } else if (len == 1) {\n if (c.charCodeAt() - 97 == j) len++; // second char\n } else if (len == 2) {\n if (c.charCodeAt() - 97 == i) len++; // third char\n }\n }\n if (len == 3) res++;\n }\n }\n return res;\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720e9a", + "questionid": 975, + "title": "Add Minimum Number of Rungs", + "slug": "add-minimum-number-of-rungs", + "description": "You are given a strictly increasing integer array rungs that represents the height of rungs on a ladder. You are currently on the floor at height 0, and you want to reach the last rung. You are also given an integer dist. You can only climb to the next highest rung if the distance between where you are currently at (the floor or on a rung) and the next rung is at most dist. You are able to insert rungs at any positive integer height if a rung is not already there. Return the minimum number of rungs that must be added to the ladder in order for you to climb to the last rung. ", + "category": [ + "Array", + "Greedy" + ], + "complexity": "Medium", + "successrate": 42.4, + "totalsubmissions": 43557, + "totalaccepted": 18474, + "likes": 220, + "dislikes": 18, + "hints": "Go as far as you can on the available rungs before adding new rungs. If you have to add a new rung, add it as high up as possible. Try using division to decrease the number of computations.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "rungs = [1,3,5,10], dist = 2", + "expected_output": "2\nExplanation:\nYou currently cannot reach the last rung.\nAdd rungs at heights 7 and 8 to climb this ladder. \nThe ladder will now have rungs at [1,3,5,7,8,10].", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "rungs = [3,6,8,10], dist = 3", + "expected_output": "0", + "explanation": "This ladder can be climbed without adding additional rungs." + }, + { + "example_num": 3, + "expected_input": "rungs = [3,4,6,7], dist = 2", + "expected_output": "1", + "explanation": "You currently cannot reach the first rung from the ground.\nAdd a rung at height 1 to climb this ladder.\nThe ladder will now have rungs at [1,3,4,6,7]." + } + ], + "solution": "/**\n * @param {number[]} rungs\n * @param {number} dist\n * @return {number}\n */\nconst addRungs = function(rungs, dist) {\n let res = 0\n let pre = 0\n const { floor, ceil } = Math\n for(let r of rungs) {\n if(r - pre > dist) {\n // console.log(r, pre)\n res += ceil((r - pre) / dist) - 1\n }\n pre = r\n }\n return res\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720e9b", + "questionid": 976, + "title": "Maximum Genetic Difference Query", + "slug": "maximum-genetic-difference-query", + "description": "There is a rooted tree consisting of n nodes numbered 0 to n - 1. Each node's number denotes its unique genetic value (i.e. the genetic value of node x is x). The genetic difference between two genetic values is defined as the bitwise-XOR of their values. You are given the integer array parents, where parents[i] is the parent for node i. If node x is the root of the tree, then parents[x] == -1. You are also given the array queries where queries[i] = [nodei, vali]. For each query i, find the maximum genetic difference between vali and pi, where pi is the genetic value of any node that is on the path between nodei and the root (including nodei and the root). More formally, you want to maximize vali XOR pi. Return an array ans where ans[i] is the answer to the ith query. ", + "category": [ + "Array", + "Bit Manipulation", + "Trie" + ], + "complexity": "Hard", + "successrate": 39.2, + "totalsubmissions": 8253, + "totalaccepted": 3234, + "likes": 218, + "dislikes": 11, + "hints": "How can we use a trie to store all the XOR values in the path from a node to the root? How can we dynamically add the XOR values with a DFS search?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "parents = [-1,0,1,1], queries = [[0,2],[3,2],[2,5]]", + "expected_output": "[2,3,7]\nExplanation: The queries are processed as follows:\n- [0,2]: The node with the maximum genetic difference is 0, with a difference of 2 XOR 0 = 2.\n- [3,2]: The node with the maximum genetic difference is 1, with a difference of 2 XOR 1 = 3.\n- [2,5]: The node with the maximum genetic difference is 2, with a difference of 5 XOR 2 = 7.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "parents = [3,7,-1,2,0,7,0,2], queries = [[4,6],[1,15],[0,5]]", + "expected_output": "[6,14,7]\nExplanation: The queries are processed as follows:\n- [4,6]: The node with the maximum genetic difference is 0, with a difference of 6 XOR 0 = 6.\n- [1,15]: The node with the maximum genetic difference is 1, with a difference of 15 XOR 1 = 14.\n- [0,5]: The node with the maximum genetic difference is 2, with a difference of 5 XOR 2 = 7.", + "explanation": "" + } + ], + "solution": "/**\n * @param {number[]} parents\n * @param {number[][]} queries\n * @return {number[]}\n */\nconst maxGeneticDifference = function (parents, queries) {\n let pn = parents.length,\n qn = queries.length\n let root = parents.indexOf(-1)\n let children = initializeGraph(pn)\n for (let i = 0; i < pn; i++) {\n if (i != root) {\n children[parents[i]].push(i)\n }\n }\n let freq = Array(1 << 20).fill(0)\n let queriesByNode = initializeGraph(pn)\n for (let i = 0; i < qn; i++) {\n let query = queries[i]\n queriesByNode[query[0]].push(new Query(i, query[1]))\n }\n\n let res = Array(qn).fill(0)\n const dfs = (idx) => {\n let y = (1 << 19) + idx\n while (y > 0) {\n freq[y]++\n y >>= 1\n }\n for (const qnode of queriesByNode[idx]) {\n let j = qnode.index,\n x = qnode.val\n let cum = 0\n let bit = 1 << 18\n while (bit > 0) {\n let ii = (((1 << 19) ^ cum ^ x ^ bit) / bit) >> 0\n if (freq[ii] > 0) cum += bit\n bit >>= 1\n }\n res[j] = cum\n }\n for (const child of children[idx]) dfs(child)\n y = (1 << 19) + idx\n while (y > 0) {\n freq[y]--\n y >>= 1\n }\n }\n dfs(root)\n return res\n}\n\nconst initializeGraph = (n) => {\n let G = []\n for (let i = 0; i < n; i++) G.push([])\n return G\n}\n\nfunction Query(index, val) {\n this.index = index\n this.val = val\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720e9c", + "questionid": 977, + "title": "Largest Number After Mutating Substring", + "slug": "largest-number-after-mutating-substring", + "description": "You are given a string num, which represents a large integer. You are also given a 0-indexed integer array change of length 10 that maps each digit 0-9 to another digit. More formally, digit d maps to digit change[d]. You may choose to mutate a single substring of num. To mutate a substring, replace each digit num[i] with the digit it maps to in change (i.e. replace num[i] with change[num[i]]). Return a string representing the largest possible integer after mutating (or choosing not to) a single substring of num. A substring is a contiguous sequence of characters within the string. ", + "category": [ + "Array", + "String", + "Greedy" + ], + "complexity": "Medium", + "successrate": 33.9, + "totalsubmissions": 41615, + "totalaccepted": 14112, + "likes": 139, + "dislikes": 163, + "hints": "Should you change a digit if the new digit is smaller than the original? If changing the first digit and the last digit both make the number bigger, but you can only change one of them; which one should you change? Changing numbers closer to the front is always better", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "num = "132", change = [9,8,5,0,3,6,4,2,6,8]", + "expected_output": ""832"", + "explanation": "Replace the substring "1":\n- 1 maps to change[1] = 8.\nThus, "132" becomes "832".\n"832" is the largest number that can be created, so return it." + }, + { + "example_num": 2, + "expected_input": "num = "021", change = [9,4,3,5,7,2,1,9,0,6]", + "expected_output": ""934"", + "explanation": "Replace the substring "021":\n- 0 maps to change[0] = 9.\n- 2 maps to change[2] = 3.\n- 1 maps to change[1] = 4.\nThus, "021" becomes "934".\n"934" is the largest number that can be created, so return it." + }, + { + "example_num": 3, + "expected_input": "num = "5", change = [1,4,7,5,3,2,5,6,9,4]", + "expected_output": ""5"", + "explanation": ""5" is already the largest number that can be created, so return it." + } + ], + "solution": "/**\n * @param {string} num\n * @param {number[]} change\n * @return {string}\n */\nconst maximumNumber = function(num, change) {\n let res = ''\n const arr = num.split('')\n let prev = false, cnt = 0\n for(let i = 0, n = num.length; i < n; i++) {\n const cur = +num[i]\n if(change[cur] > cur) {\n cnt++\n prev = true\n arr[i] = change[cur]\n }\n if(change[cur] < cur) {\n if(cnt <= 0) continue\n else break\n }\n }\n \n return arr.join('')\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720e9e", + "questionid": 979, + "title": "Delete Duplicate Folders in System", + "slug": "delete-duplicate-folders-in-system", + "description": "Due to a bug, there are many duplicate folders in a file system. You are given a 2D array paths, where paths[i] is an array representing an absolute path to the ith folder in the file system. Two folders (not necessarily on the same level) are identical if they contain the same non-empty set of identical subfolders and underlying subfolder structure. The folders do not need to be at the root level to be identical. If two or more folders are identical, then mark the folders as well as all their subfolders. Once all the identical folders and their subfolders have been marked, the file system will delete all of them. The file system only runs the deletion once, so any folders that become identical after the initial deletion are not deleted. Return the 2D array ans containing the paths of the remaining folders after deleting all the marked folders. The paths may be returned in any order. ", + "category": [ + "Array", + "Hash Table", + "String", + "Trie", + "Hash Function" + ], + "complexity": "Hard", + "successrate": 58.6, + "totalsubmissions": 7699, + "totalaccepted": 4513, + "likes": 166, + "dislikes": 48, + "hints": "Can we use a trie to build the folder structure? Can we utilize hashing to hash the folder structures?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "paths = [["a"],["c"],["d"],["a","b"],["c","b"],["d","a"]]", + "expected_output": "[["d"],["d","a"]]", + "explanation": "The file structure is as shown.\nFolders "/a" and "/c" (and their subfolders) are marked for deletion because they both contain an empty\nfolder named "b"." + }, + { + "example_num": 2, + "expected_input": "paths = [["a"],["c"],["a","b"],["c","b"],["a","b","x"],["a","b","x","y"],["w"],["w","y"]]", + "expected_output": "[["c"],["c","b"],["a"],["a","b"]]\nExplanation: The file structure is as shown. \nFolders "/a/b/x" and "/w" (and their subfolders) are marked for deletion because they both contain an empty folder named "y".\nNote that folders "/a" and "/c" are identical after the deletion, but they are not deleted because they were not marked beforehand.", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "paths = [["a","b"],["c","d"],["c"],["a"]]", + "expected_output": "[["c"],["c","d"],["a"],["a","b"]]", + "explanation": "All folders are unique in the file system.\nNote that the returned array can be in a different order as the order does not matter." + } + ], + "solution": "/**\n * @param {string[][]} paths\n * @return {string[][]}\n */\nconst deleteDuplicateFolder = function(paths) {\n const trie = new Trie()\n for (const path of paths) {\n let cur = trie.trie\n cur.countPrefix++\n for (const name of path) {\n if(cur.children[name] == null) cur.children[name] = new TrieNode(name)\n cur = cur.children[name]\n cur.countPrefix++\n }\n }\n const folders = new Map()\n dfs1(trie.trie)\n for (const value of folders.values()) {\n if (value.length > 1) {\n // found the same dir, mark as to be deleted\n for (const node of value) {\n node.countPrefix = 0\n }\n }\n }\n const ans = []\n // traverse un-deleted dir, put them to result\n dfs2(trie.trie, [])\n return ans\n function dfs1 (node) {\n if (Object.keys(node.children).length === 0) {\n return `(${node.char})`\n }\n const childrenExp = []\n for (const key in node.children) {\n childrenExp.push(dfs1(node.children[key]))\n }\n const exp = childrenExp.sort((a, b) => a.localeCompare(b)).join('')\n if (!folders.has(exp)) {\n folders.set(exp, [])\n }\n folders.get(exp).push(node)\n return `(${node.char}${childrenExp.join('')})`\n }\n function dfs2 (node, path) {\n // already deleted, no need go further\n if (node.countPrefix === 0) {\n return\n }\n if (node.char !== '/') { path.push(node.char) }\n if (path.length) ans.push([...path])\n for (const key in node.children) {\n dfs2(node.children[key], path)\n }\n path.pop()\n } \n};\nclass TrieNode {\n constructor (char) {\n this.char = char\n this.count = 0\n this.countPrefix = 0\n this.children = {}\n }\n};\nclass Trie {\n /**\n * @description Initialize the trie\n */\n constructor () {\n this.trie = new TrieNode('/')\n }\n\n /**\n * @description Insert strings into the trie\n * @param str the string to be inserted\n * @param count number of `str` to be inserted, can be negative for deleting x from the trie\n */\n insert (str, count = 1) {\n let cur = this.trie\n for (const char of str) {\n cur.children[char] ??= new TrieNode(char)\n cur = cur.children[char]\n cur.countPrefix += count\n }\n cur.count += count\n }\n\n /**\n * Traverse the trie with a callback function\n * @param str An input string\n * @param callbackfn A callback function. traverse calls the callbackfn function one time for each char in `str`, however it may skip ending chars in str if the trie has no children to go deeper, the returned char from callbackfn will be used as the direction of traversing\n * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value\n */\n traverse (str, callbackfn, thisArg) {\n let cur = this.trie\n for (let i = 0; i < str.length; i++) {\n const retChar = callbackfn.call(thisArg, str[i], i, cur)\n const tmp = cur.children[retChar]\n if (!tmp || tmp.countPrefix <= 0) return\n cur = tmp\n }\n }\n\n /**\n * @description Search a string in the trie\n * @returns Number of `str` in the trie\n */\n count (str) {\n let ans = 0\n this.traverse(str, (char, idx, node) => {\n const nextNode = node.children[char]\n if (idx === str.length - 1 && nextNode) {\n ans = nextNode.count\n }\n return char\n })\n return ans\n }\n\n /**\n * @description Search a string in the trie\n * @returns Number of prefix of `str` in the trie\n */\n countPrefix (str) {\n let ans = 0\n this.traverse(str, (char, idx, node) => {\n const nextNode = node.children[char]\n ans += nextNode?.countPrefix ?? 0\n return char\n })\n return ans\n }\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720ea0", + "questionid": 981, + "title": "Array With Elements Not Equal to Average of Neighbors", + "slug": "array-with-elements-not-equal-to-average-of-neighbors", + "description": "You are given a 0-indexed array nums of distinct integers. You want to rearrange the elements in the array such that every element in the rearranged array is not equal to the average of its neighbors. More formally, the rearranged array should have the property such that for every i in the range 1 <= i < nums.length - 1, (nums[i-1] + nums[i+1]) / 2 is not equal to nums[i]. Return any rearrangement of nums that meets the requirements. ", + "category": [ + "Array", + "Greedy", + "Sorting" + ], + "complexity": "Medium", + "successrate": 48.5, + "totalsubmissions": 33552, + "totalaccepted": 16267, + "likes": 256, + "dislikes": 17, + "hints": "A number can be the average of its neighbors if one neighbor is smaller than the number and the other is greater than the number. We can put numbers smaller than the median on odd indices and the rest on even indices.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,2,3,4,5]", + "expected_output": "[1,2,4,5,3]", + "explanation": "When i=1, nums[i] = 2, and the average of its neighbors is (1+4) / 2 = 2.5.\nWhen i=2, nums[i] = 4, and the average of its neighbors is (2+5) / 2 = 3.5.\nWhen i=3, nums[i] = 5, and the average of its neighbors is (4+3) / 2 = 3.5." + }, + { + "example_num": 2, + "expected_input": "nums = [6,2,0,9,7]", + "expected_output": "[9,7,6,2,0]", + "explanation": "When i=1, nums[i] = 7, and the average of its neighbors is (9+6) / 2 = 7.5.\nWhen i=2, nums[i] = 6, and the average of its neighbors is (7+2) / 2 = 4.5.\nWhen i=3, nums[i] = 2, and the average of its neighbors is (6+0) / 2 = 3." + } + ], + "solution": "/**\n * @param {number[]} nums\n * @return {number[]}\n */\nconst rearrangeArray = function(nums) {\n nums.sort((a, b) => a - b)\n const res = []\n let idx = 0, i = 0\n const n = ~~((nums.length + 1) / 2)\n while(i < nums.length) {\n if(idx >= nums.length) idx = 1\n // console.log(idx,i)\n res[idx] = nums[i]\n \n idx += 2\n i++\n }\n \n return res\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720ea2", + "questionid": 983, + "title": "Number of Ways to Arrive at Destination", + "slug": "number-of-ways-to-arrive-at-destination", + "description": "You are in a city that consists of n intersections numbered from 0 to n - 1 with bi-directional roads between some intersections. The inputs are generated such that you can reach any intersection from any other intersection and that there is at most one road between any two intersections. You are given an integer n and a 2D integer array roads where roads[i] = [ui, vi, timei] means that there is a road between intersections ui and vi that takes timei minutes to travel. You want to know in how many ways you can travel from intersection 0 to intersection n - 1 in the shortest amount of time. Return the number of ways you can arrive at your destination in the shortest amount of time. Since the answer may be large, return it modulo 109 + 7. ", + "category": [ + "Dynamic Programming", + "Graph", + "Topological Sort", + "Shortest Path" + ], + "complexity": "Medium", + "successrate": 32.9, + "totalsubmissions": 41803, + "totalaccepted": 13760, + "likes": 795, + "dislikes": 23, + "hints": "First use any shortest path algorithm to get edges where dist[u] + weight = dist[v], here dist[x] is the shortest distance between node 0 and x Using those edges only the graph turns into a dag now we just need to know the number of ways to get from node 0 to node n - 1 on a dag using dp", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 7, roads = [[0,6,7],[0,1,2],[1,2,3],[1,3,3],[6,3,3],[3,5,1],[6,5,1],[2,5,1],[0,4,5],[4,6,2]]", + "expected_output": "4", + "explanation": "The shortest amount of time it takes to go from intersection 0 to intersection 6 is 7 minutes.\nThe four ways to get there in 7 minutes are:\n- 0 \u279d 6\n- 0 \u279d 4 \u279d 6\n- 0 \u279d 1 \u279d 2 \u279d 5 \u279d 6\n- 0 \u279d 1 \u279d 3 \u279d 5 \u279d 6" + }, + { + "example_num": 2, + "expected_input": "n = 2, roads = [[1,0,10]]", + "expected_output": "1", + "explanation": "There is only one way to go from intersection 0 to intersection 1, and it takes 10 minutes." + } + ], + "solution": "/**\n * @param {number} n\n * @param {number[][]} roads\n * @return {number}\n */\nconst countPaths = function(n, roads) {\n const graph = {}\n for(let r of roads) {\n const [u, v, t] = r\n if(graph[u] == null) graph[u] = []\n if(graph[v] == null) graph[v] = []\n graph[u].push([v, t])\n graph[v].push([u, t])\n }\n \n return dijkstra(graph, n, 0)\n\n function dijkstra(graph, n, src) {\n const dist = Array(n).fill(Infinity)\n const ways = Array(n).fill(0), mod = 1e9 + 7\n ways[src] = 1\n dist[src] = 0\n const pq = new PriorityQueue((a, b) => a[0] === b[0] ? a[1] < b[1] : a[0] < b[0])\n pq.push([0, 0])\n while(!pq.isEmpty()) {\n const [d, u] = pq.pop()\n if(d > dist[u]) continue\n if(graph[u] == null) graph[u] = []\n for(const [v, time] of graph[u]) {\n if(dist[v] > d + time) {\n ways[v] = ways[u]\n dist[v] = d + time\n pq.push([dist[v], v])\n } else if(dist[v] === d + time) {\n ways[v] = (ways[v] + ways[u]) % mod\n }\n }\n }\n return ways[n - 1]\n }\n \n};\n \nclass PriorityQueue {\n constructor(comparator = (a, b) => a > b) {\n this.heap = []\n this.top = 0\n this.comparator = comparator\n }\n size() {\n return this.heap.length\n }\n isEmpty() {\n return this.size() === 0\n }\n peek() {\n return this.heap[this.top]\n }\n push(...values) {\n values.forEach((value) => {\n this.heap.push(value)\n this.siftUp()\n })\n return this.size()\n }\n pop() {\n const poppedValue = this.peek()\n const bottom = this.size() - 1\n if (bottom > this.top) {\n this.swap(this.top, bottom)\n }\n this.heap.pop()\n this.siftDown()\n return poppedValue\n }\n replace(value) {\n const replacedValue = this.peek()\n this.heap[this.top] = value\n this.siftDown()\n return replacedValue\n }\n\n parent = (i) => ((i + 1) >>> 1) - 1\n left = (i) => (i << 1) + 1\n right = (i) => (i + 1) << 1\n greater = (i, j) => this.comparator(this.heap[i], this.heap[j])\n swap = (i, j) => ([this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]])\n siftUp = () => {\n let node = this.size() - 1\n while (node > this.top && this.greater(node, this.parent(node))) {\n this.swap(node, this.parent(node))\n node = this.parent(node)\n }\n }\n siftDown = () => {\n let node = this.top\n while (\n (this.left(node) < this.size() && this.greater(this.left(node), node)) ||\n (this.right(node) < this.size() && this.greater(this.right(node), node))\n ) {\n let maxChild =\n this.right(node) < this.size() &&\n this.greater(this.right(node), this.left(node))\n ? this.right(node)\n : this.left(node)\n this.swap(node, maxChild)\n node = maxChild\n }\n }\n}\n\n// another\n\n/**\n * @param {number} n\n * @param {number[][]} roads\n * @return {number}\n */\nconst countPaths = function(n, roads) {\n const graph = {}, MOD = 1e9 + 7\n for(const [u, v, t] of roads) {\n if(graph[u] == null) graph[u] = {}\n if(graph[v] == null) graph[v] = {}\n graph[u][v] = t\n graph[v][u] = t\n }\n\n return dijkstra(graph, n, 0)\n\n function dijkstra(graph, n, src) {\n const dist = Array(n).fill(Infinity)\n const ways = Array(n).fill(0)\n ways[src] = 1\n dist[src] = 0\n const pq = new PriorityQueue((a, b) => a[0] < b[0])\n pq.push([0, 0])\n while(!pq.isEmpty()) {\n const [d, u] = pq.pop()\n if(d > dist[u]) continue\n for(const next of Object.keys(graph[u] || {})) {\n const val = graph[u][next]\n if(dist[next] > d + val) {\n dist[next] = d + val\n ways[next] = ways[u]\n pq.push([dist[next], next])\n } else if(dist[next] === d + val) {\n ways[next] = (ways[next] + ways[u]) % MOD\n }\n }\n }\n\n return ways[n - 1]\n }\n};\n\nclass PriorityQueue {\n constructor(comparator = (a, b) => a > b) {\n this.heap = []\n this.top = 0\n this.comparator = comparator\n }\n size() {\n return this.heap.length\n }\n isEmpty() {\n return this.size() === 0\n }\n peek() {\n return this.heap[this.top]\n }\n push(...values) {\n values.forEach((value) => {\n this.heap.push(value)\n this.siftUp()\n })\n return this.size()\n }\n pop() {\n const poppedValue = this.peek()\n const bottom = this.size() - 1\n if (bottom > this.top) {\n this.swap(this.top, bottom)\n }\n this.heap.pop()\n this.siftDown()\n return poppedValue\n }\n replace(value) {\n const replacedValue = this.peek()\n this.heap[this.top] = value\n this.siftDown()\n return replacedValue\n }\n\n parent = (i) => ((i + 1) >>> 1) - 1\n left = (i) => (i << 1) + 1\n right = (i) => (i + 1) << 1\n greater = (i, j) => this.comparator(this.heap[i], this.heap[j])\n swap = (i, j) => ([this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]])\n siftUp = () => {\n let node = this.size() - 1\n while (node > this.top && this.greater(node, this.parent(node))) {\n this.swap(node, this.parent(node))\n node = this.parent(node)\n }\n }\n siftDown = () => {\n let node = this.top\n while (\n (this.left(node) < this.size() && this.greater(this.left(node), node)) ||\n (this.right(node) < this.size() && this.greater(this.right(node), node))\n ) {\n let maxChild =\n this.right(node) < this.size() &&\n this.greater(this.right(node), this.left(node))\n ? this.right(node)\n : this.left(node)\n this.swap(node, maxChild)\n node = maxChild\n }\n }\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720ea8", + "questionid": 989, + "title": "Find All Groups of Farmland", + "slug": "find-all-groups-of-farmland", + "description": "You are given a 0-indexed m x n binary matrix land where a 0 represents a hectare of forested land and a 1 represents a hectare of farmland. To keep the land organized, there are designated rectangular areas of hectares that consist entirely of farmland. These rectangular areas are called groups. No two groups are adjacent, meaning farmland in one group is not four-directionally adjacent to another farmland in a different group. land can be represented by a coordinate system where the top left corner of land is (0, 0) and the bottom right corner of land is (m-1, n-1). Find the coordinates of the top left and bottom right corner of each group of farmland. A group of farmland with a top left corner at (r1, c1) and a bottom right corner at (r2, c2) is represented by the 4-length array [r1, c1, r2, c2]. Return a 2D array containing the 4-length arrays described above for each group of farmland in land. If there are no groups of farmland, return an empty array. You may return the answer in any order. ", + "category": [ + "Array", + "Depth-First Search", + "Breadth-First Search", + "Matrix" + ], + "complexity": "Medium", + "successrate": 67.2, + "totalsubmissions": 19741, + "totalaccepted": 13260, + "likes": 345, + "dislikes": 17, + "hints": "Since every group of farmland is rectangular, the top left corner of each group will have the smallest x-coordinate and y-coordinate of any farmland in the group. Similarly, the bootm right corner of each group will have the largest x-coordinate and y-coordinate of any farmland in the group. Use DFS to traverse through different groups of farmlands and keep track of the smallest and largest x-coordinate and y-coordinates you have seen in each group.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "land = [[1,0,0],[0,1,1],[0,1,1]]", + "expected_output": "[[0,0,0,0],[1,1,2,2]]", + "explanation": "The first group has a top left corner at land[0][0] and a bottom right corner at land[0][0].\nThe second group has a top left corner at land[1][1] and a bottom right corner at land[2][2]." + }, + { + "example_num": 2, + "expected_input": "land = [[1,1],[1,1]]", + "expected_output": "[[0,0,1,1]]", + "explanation": "The first group has a top left corner at land[0][0] and a bottom right corner at land[1][1]." + }, + { + "example_num": 3, + "expected_input": "land = [[0]]", + "expected_output": "[]", + "explanation": "There are no groups of farmland." + } + ], + "solution": null + }, + { + "_id": "66f925ddfdfb8e1665720ea9", + "questionid": 990, + "title": "The Number of Good Subsets", + "slug": "the-number-of-good-subsets", + "description": "You are given an integer array nums. We call a subset of nums good if its product can be represented as a product of one or more distinct prime numbers. Return the number of different good subsets in nums modulo 109 + 7. A subset of nums is any array that can be obtained by deleting some (possibly none or all) elements from nums. Two subsets are different if and only if the chosen indices to delete are different. ", + "category": [ + "Array", + "Math", + "Dynamic Programming", + "Bit Manipulation", + "Bitmask" + ], + "complexity": "Hard", + "successrate": 33.9, + "totalsubmissions": 10566, + "totalaccepted": 3587, + "likes": 208, + "dislikes": 7, + "hints": "Consider only the numbers which have a good prime factorization. Use brute force to find all possible good subsets and then calculate its frequency in nums.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,2,3,4]", + "expected_output": "6", + "explanation": "The good subsets are:\n- [1,2]: product is 2, which is the product of distinct prime 2.\n- [1,2,3]: product is 6, which is the product of distinct primes 2 and 3.\n- [1,3]: product is 3, which is the product of distinct prime 3.\n- [2]: product is 2, which is the product of distinct prime 2.\n- [2,3]: product is 6, which is the product of distinct primes 2 and 3.\n- [3]: product is 3, which is the product of distinct prime 3." + }, + { + "example_num": 2, + "expected_input": "nums = [4,2,3,15]", + "expected_output": "5", + "explanation": "The good subsets are:\n- [2]: product is 2, which is the product of distinct prime 2.\n- [2,3]: product is 6, which is the product of distinct primes 2 and 3.\n- [2,15]: product is 30, which is the product of distinct primes 2, 3, and 5.\n- [3]: product is 3, which is the product of distinct prime 3.\n- [15]: product is 15, which is the product of distinct primes 3 and 5." + } + ], + "solution": "const primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]\nconst M = 1e9 + 7\n/**\n * @param {number[]} nums\n * @return {number}\n */\nvar numberOfGoodSubsets = function (nums) {\n const n = primes.length\n const dp = new Array(1 << n).fill(0)\n dp[0] = 1\n\n const map = new Map()\n for (const x of nums) {\n map.set(x, (map.get(x) || 0) + 1)\n }\n\n let count1 = 0\n for (const [x, count] of map) {\n if (x === 1) continue\n const encode = encoding(x)\n if (encode === -1) continue\n\n for (let state = (1 << n) - 1; state >= 1; state--) {\n if (state - encode === (state ^ encode)) {\n dp[state] = (dp[state] + ((dp[state - encode] * count) % M)) % M\n }\n }\n }\n\n let ret = 0\n for (let state = 1; state < 1 << n; state++) {\n ret = (ret + dp[state]) % M\n }\n\n let power2 = 1\n for (let i = 0; i < (map.get(1) || 0); i++) {\n power2 = (power2 * 2) % M\n }\n\n return mul(ret, power2)\n}\n\nfunction mul(...arr) {\n let res = 1n\n for (const e of arr) {\n res *= BigInt(e)\n }\n\n return Number(res % BigInt(M))\n}\n\nfunction encoding(num) {\n let encode = 0\n for (let i = 0; i < primes.length; i++) {\n if (num % primes[i] === 0) {\n encode += 1 << i\n num /= primes[i]\n }\n if (num % primes[i] === 0) {\n return -1\n }\n }\n return encode\n}\n\n// another\n\nconst M = 1e9 + 7\n\n/**\n * @param {number[]} nums\n * @return {number}\n */\nconst numberOfGoodSubsets = function (nums) {\n const set = new Set([\n 2, 3, 5, 6, 7, 10, 11, 13, 14, 15, 17, 19, 21, 22, 23, 26, 29, 30,\n ])\n const map = new Map()\n let count1 = 0\n\n for (const x of nums) {\n if (set.has(x)) {\n map.set(x, (map.get(x) || 0) + 1)\n }\n if (x === 1) {\n count1++\n }\n }\n\n const n = map.size\n const count = []\n const digit = []\n for (const [key, value] of map) {\n digit.push(key)\n count.push(value)\n }\n\n let ret = 0\n for (let state = 1; state < 1 << n; state++) {\n let flag = 1\n for (let i = 0; i < n; i++) {\n if (((state >> i) & 1) === 0) continue\n for (let j = i + 1; j < n; j++) {\n if (((state >> j) & 1) === 0) continue\n if (gcd(digit[i], digit[j]) !== 1) {\n flag = 0\n break\n }\n }\n if (flag === 0) break\n }\n\n if (flag === 0) continue\n\n let ans = 1\n for (let i = 0; i < n; i++) {\n if (((state >> i) & 1) === 0) continue\n ans = mul(ans, count[i])\n }\n ret = (ret + ans) % M\n }\n\n ret = mul(ret, quickMul(2, count1))\n return ret\n}\n\nfunction quickMul(x, N) {\n if (N === 0) {\n return 1\n }\n const y = quickMul(x, Math.floor(N / 2))\n return N % 2 === 0 ? mul(y, y) : mul(y, y, x)\n}\n\nfunction mul(...arr) {\n let res = 1n\n for (const e of arr) {\n res *= BigInt(e)\n }\n\n return Number(res % BigInt(M))\n}\n\nfunction gcd(a, b) {\n while (b) {\n ;[a, b] = [b, a % b]\n }\n return a\n}\n\n// another\n\n\n/**\n * @param {number[]} nums\n * @return {number}\n */\nconst numberOfGoodSubsets = function (nums) {\n const primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]\n const n = nums.length,\n cnt = {},\n mod = BigInt(1e9 + 7)\n const bm = []\n for (let num of nums) {\n cnt[num] = (cnt[num] || 0n) + 1n\n }\n for (let i = 0; i < 31; i++) {\n let tmp = 0\n for (let j = 0, m = primes.length; j < m; j++) {\n const p = primes[j]\n if (i % p === 0) tmp += 1 << j\n }\n bm[i] = tmp\n }\n const bad = new Set([4, 8, 9, 12, 16, 18, 20, 24, 25, 27, 28])\n const memo = {}\n\n function dp(mask, num) {\n if (num === 1) return 1n\n if (memo[mask] && memo[mask][num] != null) return memo[mask][num]\n let res = dp(mask, num - 1)\n if (!bad.has(num) && (mask | bm[num]) === mask) {\n res += dp(mask ^ bm[num], num - 1) * (cnt[num] || 0n)\n }\n if (memo[mask] == null) memo[mask] = {}\n return (memo[mask][num] = res % mod)\n }\n\n return ((dp(1023, 30) - 1n) * pow(2n, cnt[1] || 0n, mod)) % mod\n}\n\nfunction pow(base, exp, mod) {\n if (exp === 0n) return 1n\n // console.log(base, mod)\n base %= mod\n let res = pow(base, exp / 2n, mod)\n res = (res * res) % mod\n if (exp & 1n) res = (res * base) % mod\n return res\n}\n/**\n * @param {number[]} nums\n * @return {number}\n */\nconst numberOfGoodSubsets = function (nums) {\n const primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]\n const n = nums.length,\n cnt = {},\n mod = BigInt(1e9 + 7)\n const bm = []\n for (let num of nums) {\n cnt[num] = (cnt[num] || 0n) + 1n\n }\n for (let i = 0; i < 31; i++) {\n let tmp = 0\n for (let j = 0, m = primes.length; j < m; j++) {\n const p = primes[j]\n if (i % p === 0) tmp += 1 << j\n }\n bm[i] = tmp\n }\n const bad = new Set([4, 8, 9, 12, 16, 18, 20, 24, 25, 27, 28])\n const memo = {}\n\n function dp(mask, num) {\n if (num === 1) return 1n\n if (memo[mask] && memo[mask][num] != null) return memo[mask][num]\n let res = dp(mask, num - 1)\n if (!bad.has(num) && (mask | bm[num]) === mask) {\n res += dp(mask ^ bm[num], num - 1) * (cnt[num] || 0n)\n }\n if (memo[mask] == null) memo[mask] = {}\n return (memo[mask][num] = res % mod)\n }\n\n return ((dp(1023, 30) - 1n) * pow(2n, cnt[1] || 0n, mod)) % mod\n}\n\nfunction pow(base, exp, mod) {\n if (exp === 0n) return 1n\n // console.log(base, mod)\n base %= mod\n let res = pow(base, exp / 2n, mod)\n res = (res * res) % mod\n if (exp & 1n) res = (res * base) % mod\n return res\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720eb1", + "questionid": 998, + "title": "Reverse Prefix of Word", + "slug": "reverse-prefix-of-word", + "description": "Given a 0-indexed string word and a character ch, reverse the segment of word that starts at index 0 and ends at the index of the first occurrence of ch (inclusive). If the character ch does not exist in word, do nothing. Return the resulting string. ", + "category": [ + "Two Pointers", + "String" + ], + "complexity": "Easy", + "successrate": 78, + "totalsubmissions": 41520, + "totalaccepted": 32378, + "likes": 310, + "dislikes": 6, + "hints": "Find the first index where ch appears. Find a way to reverse a substring of word.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "word = "abcdefd", ch = "d"", + "expected_output": ""dcbaefd"", + "explanation": " The first occurrence of "d" is at index 3. \nReverse the part of word from 0 to 3 (inclusive), the resulting string is "dcbaefd"." + }, + { + "example_num": 2, + "expected_input": "word = "xyxzxe", ch = "z"", + "expected_output": ""zxyxxe"", + "explanation": " The first and only occurrence of "z" is at index 3.\nReverse the part of word from 0 to 3 (inclusive), the resulting string is "zxyxxe"." + }, + { + "example_num": 3, + "expected_input": "word = "abcd", ch = "z"", + "expected_output": ""abcd"", + "explanation": " "z" does not exist in word.\nYou should not do any reverse operation, the resulting string is "abcd"." + } + ], + "solution": "/**\n * @param {string} word\n * @param {character} ch\n * @return {string}\n */\nconst reversePrefix = function(word, ch) {\n const arr = word.split('')\n let idx = -1\n for(let i = 0; i < arr.length; i++) {\n if(arr[i] === ch) {\n idx = i\n break\n }\n }\n if(idx !== -1) {\n const pre = arr.slice(0, idx + 1)\n const remain = arr.slice(idx + 1)\n return pre.reverse().concat(remain).join('')\n }\n return word\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720e8f", + "questionid": 964, + "title": "Find a Peak Element II", + "slug": "find-a-peak-element-ii", + "description": "A peak element in a 2D grid is an element that is strictly greater than all of its adjacent neighbors to the left, right, top, and bottom. Given a 0-indexed m x n matrix mat where no two adjacent cells are equal, find any peak element mat[i][j] and return the length 2 array [i,j]. You may assume that the entire matrix is surrounded by an outer perimeter with the value -1 in each cell. You must write an algorithm that runs in O(m log(n)) or O(n log(m)) time. ", + "category": [ + "Array", + "Binary Search", + "Divide and Conquer", + "Matrix" + ], + "complexity": "Medium", + "successrate": 53.5, + "totalsubmissions": 34416, + "totalaccepted": 18416, + "likes": 681, + "dislikes": 54, + "hints": "Let's assume that the width of the array is bigger than the height, otherwise, we will split in another direction. Split the array into three parts: central column left side and right side. Go through the central column and two neighbor columns and look for maximum. If it's in the central column - this is our peak. If it's on the left side, run this algorithm on subarray left_side + central_column. If it's on the right side, run this algorithm on subarray right_side + central_column", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "mat = [[1,4],[3,2]]", + "expected_output": "[0,1]", + "explanation": " Both 3 and 4 are peak elements so [1,0] and [0,1] are both acceptable answers." + }, + { + "example_num": 2, + "expected_input": "mat = [[10,20,15],[21,30,14],[7,16,32]]", + "expected_output": "[1,1]", + "explanation": " Both 30 and 32 are peak elements so [1,1] and [2,2] are both acceptable answers." + } + ], + "solution": "/**\n * @param {number[][]} mat\n * @return {number[]}\n */\nconst findPeakGrid = function(mat) {\n let lowCol = 0;\n let highCol = mat[0].length - 1;\n\n while(lowCol <= highCol) {\n let midCol = lowCol + ~~((highCol - lowCol) / 2);\n let maxRow = 0;\n for(let i = 0; i < mat.length; i++) {\n maxRow = mat[i][midCol] > mat[maxRow][midCol] ? i : maxRow;\n }\n\n let isLeftElementBig = midCol - 1 >= lowCol && mat[maxRow][midCol - 1] > mat[maxRow][midCol];\n let isRightElementBig = midCol + 1 <= highCol && mat[maxRow][midCol + 1] > mat[maxRow][midCol];\n\n if(!isLeftElementBig && !isRightElementBig) {\n return [maxRow, midCol];\n } else if(isRightElementBig) {\n lowCol = midCol + 1;\n } else {\n highCol = midCol - 1;\n }\n }\n return null;\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720e90", + "questionid": 965, + "title": "Build Array from Permutation", + "slug": "build-array-from-permutation", + "description": "Given a zero-based permutation nums (0-indexed), build an array ans of the same length where ans[i] = nums[nums[i]] for each 0 <= i < nums.length and return it. A zero-based permutation nums is an array of distinct integers from 0 to nums.length - 1 (inclusive). ", + "category": [ + "Array", + "Simulation" + ], + "complexity": "Easy", + "successrate": 91.6, + "totalsubmissions": 160267, + "totalaccepted": 146876, + "likes": 1157, + "dislikes": 156, + "hints": "Just apply what's said in the statement. Notice that you can't apply it on the same array directly since some elements will change after application", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [0,2,1,5,3,4]", + "expected_output": "[0,1,2,4,5,3]\nExplanation: The array ans is built as follows: \nans = [nums[nums[0]], nums[nums[1]], nums[nums[2]], nums[nums[3]], nums[nums[4]], nums[nums[5]]]\n = [nums[0], nums[2], nums[1], nums[5], nums[3], nums[4]]\n = [0,1,2,4,5,3]", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "nums = [5,0,1,2,3,4]", + "expected_output": "[4,5,0,1,2,3]", + "explanation": "The array ans is built as follows:\nans = [nums[nums[0]], nums[nums[1]], nums[nums[2]], nums[nums[3]], nums[nums[4]], nums[nums[5]]]\n = [nums[5], nums[0], nums[1], nums[2], nums[3], nums[4]]\n = [4,5,0,1,2,3]" + } + ], + "solution": "/**\n * @param {number[]} nums\n * @return {number[]}\n */\nconst buildArray = function(nums) {\n const res = []\n for(let i = 0, n = nums.length; i < n; i++) {\n res[i] = nums[nums[i]]\n }\n return res\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720e92", + "questionid": 967, + "title": "Count Good Numbers", + "slug": "count-good-numbers", + "description": "A digit string is good if the digits (0-indexed) at even indices are even and the digits at odd indices are prime (2, 3, 5, or 7). Given an integer n, return the total number of good digit strings of length n. Since the answer may be large, return it modulo 109 + 7. A digit string is a string consisting of digits 0 through 9 that may contain leading zeros. ", + "category": [ + "Math", + "Recursion" + ], + "complexity": "Medium", + "successrate": 38.2, + "totalsubmissions": 38945, + "totalaccepted": 14887, + "likes": 316, + "dislikes": 217, + "hints": "Is there a formula we can use to find the count of all the good numbers? Exponentiation can be done very fast if we looked at the binary bits of n.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 1", + "expected_output": "5", + "explanation": "The good numbers of length 1 are "0", "2", "4", "6", "8"." + }, + { + "example_num": 2, + "expected_input": "n = 4", + "expected_output": "400", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "n = 50", + "expected_output": "564908303", + "explanation": "" + } + ], + "solution": "/**\n * @param {number} n\n * @return {number}\n */\nconst countGoodNumbers = function (n) {\n n = BigInt(n)\n const MOD = BigInt(10 ** 9 + 7)\n let res =\n quick_pow(5n, (n + 1n) / 2n ) * quick_pow(4n, n / 2n)\n res %= MOD\n return res\n\n function quick_pow(b, m) {\n let ans = 1n\n while (m) {\n if (m % 2n === 1n) ans = (ans * b) % MOD\n m = m / 2n\n b = (b * b) % MOD\n }\n return ans\n }\n}\n\n" + }, + { + "_id": "66f925ddfdfb8e1665720e94", + "questionid": 969, + "title": "Check if All Characters Have Equal Number of Occurrences", + "slug": "check-if-all-characters-have-equal-number-of-occurrences", + "description": "Given a string s, return true if s is a good string, or false otherwise. A string s is good if all the characters that appear in s have the same number of occurrences (i.e., the same frequency). ", + "category": [ + "Hash Table", + "String", + "Counting" + ], + "complexity": "Easy", + "successrate": 77.1, + "totalsubmissions": 43486, + "totalaccepted": 33510, + "likes": 328, + "dislikes": 11, + "hints": "Build a dictionary containing the frequency of each character appearing in s Check if all values in the dictionary are the same.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "abacbc"", + "expected_output": "true", + "explanation": "The characters that appear in s are 'a', 'b', and 'c'. All characters occur 2 times in s." + }, + { + "example_num": 2, + "expected_input": "s = "aaabb"", + "expected_output": "false", + "explanation": "The characters that appear in s are 'a' and 'b'.\n'a' occurs 3 times while 'b' occurs 2 times, which is not the same number of times." + } + ], + "solution": "/**\n * @param {string} s\n * @return {boolean}\n */\nvar areOccurrencesEqual = function(s) {\n const n = s.length\n const arr = Array(26).fill(0), a = 'a'.charCodeAt(0)\n for(const ch of s) {\n arr[ch.charCodeAt(0) - a]++\n }\n const set = new Set()\n for(const e of arr) {\n if(e !== 0) set.add(e)\n if(set.size > 1) return false\n }\n return true\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720e9d", + "questionid": 978, + "title": "Maximum Compatibility Score Sum", + "slug": "maximum-compatibility-score-sum", + "description": "There is a survey that consists of n questions where each question's answer is either 0 (no) or 1 (yes). The survey was given to m students numbered from 0 to m - 1 and m mentors numbered from 0 to m - 1. The answers of the students are represented by a 2D integer array students where students[i] is an integer array that contains the answers of the ith student (0-indexed). The answers of the mentors are represented by a 2D integer array mentors where mentors[j] is an integer array that contains the answers of the jth mentor (0-indexed). Each student will be assigned to one mentor, and each mentor will have one student assigned to them. The compatibility score of a student-mentor pair is the number of answers that are the same for both the student and the mentor. You are tasked with finding the optimal student-mentor pairings to maximize the sum of the compatibility scores. Given students and mentors, return the maximum compatibility score sum that can be achieved. ", + "category": [ + "Array", + "Dynamic Programming", + "Backtracking", + "Bit Manipulation", + "Bitmask" + ], + "complexity": "Medium", + "successrate": 60, + "totalsubmissions": 23285, + "totalaccepted": 13971, + "likes": 442, + "dislikes": 9, + "hints": "Calculate the compatibility score for each student-mentor pair. Try every permutation of students with the original mentors array.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "students = [[1,1,0],[1,0,1],[0,0,1]], mentors = [[1,0,0],[0,0,1],[1,1,0]]", + "expected_output": "8", + "explanation": " We assign students to mentors in the following way:\n- student 0 to mentor 2 with a compatibility score of 3.\n- student 1 to mentor 0 with a compatibility score of 2.\n- student 2 to mentor 1 with a compatibility score of 3.\nThe compatibility score sum is 3 + 2 + 3 = 8." + }, + { + "example_num": 2, + "expected_input": "students = [[0,0],[0,0],[0,0]], mentors = [[1,1],[1,1],[1,1]]", + "expected_output": "0", + "explanation": "The compatibility score of any student-mentor pair is 0." + } + ], + "solution": "/**\n * @param {number[][]} students\n * @param {number[][]} mentors\n * @return {number}\n */\nconst maxCompatibilitySum = function(students, mentors) {\n const m = students.length, n = students[0].length\n const limit = 1 << m\n const dp = Array(limit).fill(0)\n for(let mask = 1; mask < limit; mask++) {\n for(let i = 0; i < m; i++) {\n if(mask & (1 << i)) {\n dp[mask] = Math.max(\n dp[mask],\n dp[mask ^ (1 << i)] + calc(bitCnt(mask) - 1, i)\n )\n }\n }\n }\n \n \n return dp[limit - 1]\n \n function bitCnt(num) {\n let res = 0\n while(num) {\n num = num & (num - 1)\n res++\n }\n \n return res\n }\n // student, mentor\n function calc(i, j) {\n let res = 0\n for(let k = 0; k < n; k++) {\n if(students[i][k] === mentors[j][k]) {\n res++\n }\n }\n \n return res\n }\n};\n\n// another\n\n/**\n * @param {number[][]} students\n * @param {number[][]} mentors\n * @return {number}\n */\nconst maxCompatibilitySum = function(students, mentors) {\n const n = students.length, dp = Array(1 << n).fill(-Infinity)\n const m = students[0].length\n return dfs(0, 0)\n \n function dfs(i, mask) {\n if(i === n) return 0\n if(dp[mask] !== -Infinity) return dp[mask]\n for(let j = 0; j < n; j++) {\n if((mask & (1 << j)) === 0) {\n dp[mask] = Math.max(dp[mask], calc(i, j) + dfs(i + 1, mask | (1 << j)))\n }\n }\n \n return dp[mask]\n }\n \n function calc(i, j) {\n let res = 0\n const a = students[i], b = mentors[j]\n for(let k = 0; k < m; k++) {\n if(a[k] === b[k]) res++\n }\n return res\n }\n};\n\n\n// another\n\n/**\n * @param {number[][]} students\n * @param {number[][]} mentors\n * @return {number}\n */\nconst maxCompatibilitySum = function(students, mentors) {\n const obj = { res: 0 }, hash = {}\n bt(students, mentors, 0, 0, obj, hash)\n\n return obj.res\n};\n\nfunction bt(stu, men, i, score, obj, hash) {\n\n if(i === stu.length) {\n if(score > obj.res) {\n obj.res = score\n }\n return\n }\n \n for(let j = 0; j < men.length; j++) {\n const k = `${j}`\n if(hash[k] === 1) continue\n hash[k] = 1\n bt(stu, men, i + 1, score + calc(stu[i], men[j]), obj, hash)\n delete hash[k]\n }\n}\n\nfunction calc(a1, a2) {\n const n = a1.length\n let res = 0\n for(let i = 0; i < n; i++) {\n if(a1[i] === a2[i]) res++\n }\n return res\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720ea6", + "questionid": 987, + "title": "Last Day Where You Can Still Cross", + "slug": "last-day-where-you-can-still-cross", + "description": "There is a 1-based binary matrix where 0 represents land and 1 represents water. You are given integers row and col representing the number of rows and columns in the matrix, respectively. Initially on day 0, the entire matrix is land. However, each day a new cell becomes flooded with water. You are given a 1-based 2D array cells, where cells[i] = [ri, ci] represents that on the ith day, the cell on the rith row and cith column (1-based coordinates) will be covered with water (i.e., changed to 1). You want to find the last day that it is possible to walk from the top to the bottom by only walking on land cells. You can start from any cell in the top row and end at any cell in the bottom row. You can only travel in the four cardinal directions (left, right, up, and down). Return the last day where it is possible to walk from the top to the bottom by only walking on land cells. ", + "category": [ + "Array", + "Binary Search", + "Depth-First Search", + "Breadth-First Search", + "Union Find", + "Matrix" + ], + "complexity": "Hard", + "successrate": 48.5, + "totalsubmissions": 16843, + "totalaccepted": 8176, + "likes": 419, + "dislikes": 8, + "hints": "What graph algorithm allows us to find whether a path exists? Can we use binary search to help us solve the problem?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "row = 2, col = 2, cells = [[1,1],[2,1],[1,2],[2,2]]", + "expected_output": "2", + "explanation": "The above image depicts how the matrix changes each day starting from day 0.\nThe last day where it is possible to cross from top to bottom is on day 2." + }, + { + "example_num": 2, + "expected_input": "row = 2, col = 2, cells = [[1,1],[1,2],[2,1],[2,2]]", + "expected_output": "1", + "explanation": "The above image depicts how the matrix changes each day starting from day 0.\nThe last day where it is possible to cross from top to bottom is on day 1." + }, + { + "example_num": 3, + "expected_input": "row = 3, col = 3, cells = [[1,2],[2,1],[3,3],[2,2],[1,1],[1,3],[2,3],[3,2],[3,1]]", + "expected_output": "3", + "explanation": "The above image depicts how the matrix changes each day starting from day 0.\nThe last day where it is possible to cross from top to bottom is on day 3." + } + ], + "solution": "/**\n * @param {number} row\n * @param {number} col\n * @param {number[][]} cells\n * @return {number}\n */\nconst latestDayToCross = function (row, col, cells) {\n const d = [\n [-1, 0],\n [1, 0],\n [0, 1],\n [0, -1],\n ]\n\n let a = Array.from({ length: row }, () => Array(col).fill(0))\n let visited = Array.from({ length: row }, () => Array(col).fill(false))\n\n for (let i = 0; i < cells.length; i++) {\n a[cells[i][0] - 1][cells[i][1] - 1] = i\n }\n\n let l = 0\n let r = row * col\n while (l + 1 < r) {\n let w = ~~((l + r) / 2)\n if (canCross(w)) {\n l = w\n } else {\n r = w\n }\n }\n\n return l\n\n function canReachBottom(i, j, day) {\n if (i == row - 1) {\n return true\n }\n visited[i][j] = true\n\n for (let diff of d) {\n let newI = i + diff[0]\n let newJ = j + diff[1]\n\n if (newI < 0 || newI >= row || newJ < 0 || newJ >= col) {\n continue\n }\n\n if (visited[newI][newJ] || a[newI][newJ] < day) {\n continue\n }\n\n if (canReachBottom(newI, newJ, day)) {\n return true\n }\n }\n\n return false\n }\n\n function canCross(day) {\n for (let layer of visited) {\n layer.forEach((e, idx) => (layer[idx] = false))\n }\n\n for (let j = 0; j < col; j++) {\n if (a[0][j] >= day && canReachBottom(0, j, day)) {\n return true\n }\n }\n\n return false\n }\n}\n\n\n" + }, + { + "_id": "66f925ddfdfb8e1665720ea7", + "questionid": 988, + "title": "Find the Middle Index in Array", + "slug": "find-the-middle-index-in-array", + "description": "Given a 0-indexed integer array nums, find the leftmost middleIndex (i.e., the smallest amongst all the possible ones). A middleIndex is an index where nums[0] + nums[1] + ... + nums[middleIndex-1] == nums[middleIndex+1] + nums[middleIndex+2] + ... + nums[nums.length-1]. If middleIndex == 0, the left side sum is considered to be 0. Similarly, if middleIndex == nums.length - 1, the right side sum is considered to be 0. Return the leftmost middleIndex that satisfies the condition, or -1 if there is no such index. ", + "category": [ + "Array", + "Prefix Sum" + ], + "complexity": "Easy", + "successrate": 66.2, + "totalsubmissions": 39296, + "totalaccepted": 26017, + "likes": 390, + "dislikes": 18, + "hints": "Could we go from left to right and check to see if an index is a middle index? Do we need to sum every number to the left and right of an index each time? Use a prefix sum array where prefix[i] = nums[0] + nums[1] + ... + nums[i].", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [2,3,-1,8,4]", + "expected_output": "3", + "explanation": "The sum of the numbers before index 3 is: 2 + 3 + -1 = 4\nThe sum of the numbers after index 3 is: 4 = 4" + }, + { + "example_num": 2, + "expected_input": "nums = [1,-1,4]", + "expected_output": "2", + "explanation": "The sum of the numbers before index 2 is: 1 + -1 = 0\nThe sum of the numbers after index 2 is: 0" + }, + { + "example_num": 3, + "expected_input": "nums = [2,5]", + "expected_output": "-1", + "explanation": "There is no valid middleIndex." + } + ], + "solution": "/**\n * @param {number[]} nums\n * @return {number}\n */\nconst findMiddleIndex = function(nums) {\n const n = nums.length\n const sum = nums.reduce((ac, e) => ac + e, 0) \n \n let res, leftSum = 0\n for(let i = 0; i < n; i++) {\n if(leftSum === sum - leftSum - nums[i]) {\n res = i\n break\n }\n leftSum += nums[i]\n }\n\n return res == null ? -1 : res\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720eaa", + "questionid": 991, + "title": "Find Greatest Common Divisor of Array", + "slug": "find-greatest-common-divisor-of-array", + "description": "Given an integer array nums, return the greatest common divisor of the smallest number and largest number in nums. The greatest common divisor of two numbers is the largest positive integer that evenly divides both numbers. ", + "category": [ + "Array", + "Math", + "Number Theory" + ], + "complexity": "Easy", + "successrate": 77.9, + "totalsubmissions": 50222, + "totalaccepted": 39136, + "likes": 355, + "dislikes": 14, + "hints": "Find the minimum and maximum in one iteration. Let them be mn and mx. Try all the numbers in the range [1, mn] and check the largest number which divides both of them.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [2,5,6,9,10]", + "expected_output": "2", + "explanation": "The smallest number in nums is 2.\nThe largest number in nums is 10.\nThe greatest common divisor of 2 and 10 is 2." + }, + { + "example_num": 2, + "expected_input": "nums = [7,5,6,8,3]", + "expected_output": "1", + "explanation": "The smallest number in nums is 3.\nThe largest number in nums is 8.\nThe greatest common divisor of 3 and 8 is 1." + }, + { + "example_num": 3, + "expected_input": "nums = [3,3]", + "expected_output": "3", + "explanation": "The smallest number in nums is 3.\nThe largest number in nums is 3.\nThe greatest common divisor of 3 and 3 is 3." + } + ], + "solution": "/**\n * @param {number[]} nums\n * @return {number}\n */\nconst findGCD = function(nums) {\n let min = Math.min(...nums)\n let max = Math.max(...nums)\n return gcd(min, max)\n};\n\nfunction gcd(a, b) {\n return b === 0 ? a : gcd(b, a % b)\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720eab", + "questionid": 992, + "title": "Find Unique Binary String", + "slug": "find-unique-binary-string", + "description": "Given an array of strings nums containing n unique binary strings each of length n, return a binary string of length n that does not appear in nums. If there are multiple answers, you may return any of them. ", + "category": [ + "Array", + "String", + "Backtracking" + ], + "complexity": "Medium", + "successrate": 63.2, + "totalsubmissions": 34802, + "totalaccepted": 21982, + "likes": 487, + "dislikes": 24, + "hints": "We can convert the given strings into base 10 integers. Can we use recursion to generate all possible strings?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = ["01","10"]", + "expected_output": ""11"", + "explanation": ""11" does not appear in nums. "00" would also be correct." + }, + { + "example_num": 2, + "expected_input": "nums = ["00","01"]", + "expected_output": ""11"", + "explanation": ""11" does not appear in nums. "10" would also be correct." + }, + { + "example_num": 3, + "expected_input": "nums = ["111","011","001"]", + "expected_output": ""101"", + "explanation": ""101" does not appear in nums. "000", "010", "100", and "110" would also be correct." + } + ], + "solution": "/**\n * @param {string[]} nums\n * @return {string}\n */\nconst findDifferentBinaryString = function(nums) {\n const set = new Set(nums)\n const len = nums[0].length\n for(let i = 0, n = 1 << 17; i < n; i++) {\n const tmp = pad(bin(i), len)\n if(!set.has(tmp)) return tmp\n }\n return ''\n};\n\nfunction bin(num) {\n return (num >>> 0).toString(2)\n}\n\nfunction pad(str,n) {\n while(str.length < n) str = '0' + str\n return str\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720e8c", + "questionid": 961, + "title": "Minimum Cost to Reach Destination in Time", + "slug": "minimum-cost-to-reach-destination-in-time", + "description": "There is a country of n cities numbered from 0 to n - 1 where all the cities are connected by bi-directional roads. The roads are represented as a 2D integer array edges where edges[i] = [xi, yi, timei] denotes a road between cities xi and yi that takes timei minutes to travel. There may be multiple roads of differing travel times connecting the same two cities, but no road connects a city to itself. Each time you pass through a city, you must pay a passing fee. This is represented as a 0-indexed integer array passingFees of length n where passingFees[j] is the amount of dollars you must pay when you pass through city j. In the beginning, you are at city 0 and want to reach city n - 1 in maxTime minutes or less. The cost of your journey is the summation of passing fees for each city that you passed through at some moment of your journey (including the source and destination cities). Given maxTime, edges, and passingFees, return the minimum cost to complete your journey, or -1 if you cannot complete it within maxTime minutes. ", + "category": [ + "Dynamic Programming", + "Graph" + ], + "complexity": "Hard", + "successrate": 37.2, + "totalsubmissions": 26465, + "totalaccepted": 9844, + "likes": 435, + "dislikes": 6, + "hints": "Consider a new graph where each node is one of the old nodes at a specific time. For example, node 0 at time 5. You need to find the shortest path in the new graph.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "maxTime = 30, edges = [[0,1,10],[1,2,10],[2,5,10],[0,3,1],[3,4,10],[4,5,15]], passingFees = [5,1,2,20,20,3]", + "expected_output": "11", + "explanation": "The path to take is 0 -> 1 -> 2 -> 5, which takes 30 minutes and has $11 worth of passing fees." + }, + { + "example_num": 2, + "expected_input": "maxTime = 29, edges = [[0,1,10],[1,2,10],[2,5,10],[0,3,1],[3,4,10],[4,5,15]], passingFees = [5,1,2,20,20,3]", + "expected_output": "48", + "explanation": "The path to take is 0 -> 3 -> 4 -> 5, which takes 26 minutes and has $48 worth of passing fees.\nYou cannot take path 0 -> 1 -> 2 -> 5 since it would take too long." + }, + { + "example_num": 3, + "expected_input": "maxTime = 25, edges = [[0,1,10],[1,2,10],[2,5,10],[0,3,1],[3,4,10],[4,5,15]], passingFees = [5,1,2,20,20,3]", + "expected_output": "-1", + "explanation": "There is no way to reach city 5 from city 0 within 25 minutes." + } + ], + "solution": "/**\n * @param {number} maxTime\n * @param {number[][]} edges\n * @param {number[]} passingFees\n * @return {number}\n */\nconst minCost = function(maxTime, edges, passingFees) {\n const n = passingFees.length\n const pq = new PriorityQueue((a, b) => a[0] < b[0])\n const graph = {}\n for(let [s, e, t] of edges) {\n if(graph[s] == null) graph[s] = []\n if(graph[e] == null) graph[e] = []\n graph[s].push([e, t])\n graph[e].push([s, t])\n }\n \n const times = {}\n \n pq.push([passingFees[0], 0, 0])\n while(!pq.isEmpty()) {\n const [cost, node, time] = pq.pop()\n \n if(time > maxTime) continue\n if(node === n - 1) return cost\n \n if(times[node] == null || times[node] > time) {\n times[node] = time\n for(let [nxt, ext] of graph[node]) {\n pq.push([cost + passingFees[nxt], nxt, time + ext])\n }\n }\n \n }\n \n return -1\n};\n\nclass PriorityQueue {\n constructor(comparator = (a, b) => a > b) {\n this.heap = []\n this.top = 0\n this.comparator = comparator\n }\n size() {\n return this.heap.length\n }\n isEmpty() {\n return this.size() === 0\n }\n peek() {\n return this.heap[this.top]\n }\n push(...values) {\n values.forEach((value) => {\n this.heap.push(value)\n this.siftUp()\n })\n return this.size()\n }\n pop() {\n const poppedValue = this.peek()\n const bottom = this.size() - 1\n if (bottom > this.top) {\n this.swap(this.top, bottom)\n }\n this.heap.pop()\n this.siftDown()\n return poppedValue\n }\n replace(value) {\n const replacedValue = this.peek()\n this.heap[this.top] = value\n this.siftDown()\n return replacedValue\n }\n\n parent = (i) => ((i + 1) >>> 1) - 1\n left = (i) => (i << 1) + 1\n right = (i) => (i + 1) << 1\n greater = (i, j) => this.comparator(this.heap[i], this.heap[j])\n swap = (i, j) => ([this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]])\n siftUp = () => {\n let node = this.size() - 1\n while (node > this.top && this.greater(node, this.parent(node))) {\n this.swap(node, this.parent(node))\n node = this.parent(node)\n }\n }\n siftDown = () => {\n let node = this.top\n while (\n (this.left(node) < this.size() && this.greater(this.left(node), node)) ||\n (this.right(node) < this.size() && this.greater(this.right(node), node))\n ) {\n let maxChild =\n this.right(node) < this.size() &&\n this.greater(this.right(node), this.left(node))\n ? this.right(node)\n : this.left(node)\n this.swap(node, maxChild)\n node = maxChild\n }\n }\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720e8e", + "questionid": 963, + "title": "Number of Wonderful Substrings", + "slug": "number-of-wonderful-substrings", + "description": "A wonderful string is a string where at most one letter appears an odd number of times. Given a string word that consists of the first ten lowercase English letters ('a' through 'j'), return the number of wonderful non-empty substrings in word. If the same substring appears multiple times in word, then count each occurrence separately. A substring is a contiguous sequence of characters in a string. ", + "category": [ + "Hash Table", + "String", + "Bit Manipulation", + "Prefix Sum" + ], + "complexity": "Medium", + "successrate": 43.4, + "totalsubmissions": 19348, + "totalaccepted": 8405, + "likes": 598, + "dislikes": 43, + "hints": "For each prefix of the string, check which characters are of even frequency and which are not and represent it by a bitmask. Find the other prefixes whose masks differs from the current prefix mask by at most one bit.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "word = "aba"", + "expected_output": "4", + "explanation": "The four wonderful substrings are underlined below:\r\n- "aba" -> "a"\r\n- "aba" -> "b"\r\n- "aba" -> "a"\r\n- "aba" -> "aba"" + }, + { + "example_num": 2, + "expected_input": "word = "aabb"", + "expected_output": "9", + "explanation": "The nine wonderful substrings are underlined below:\r\n- "aabb" -> "a"\r\n- "aabb" -> "aa"\r\n- "aabb" -> "aab"\r\n- "aabb" -> "aabb"\r\n- "aabb" -> "a"\r\n- "aabb" -> "abb"\r\n- "aabb" -> "b"\r\n- "aabb" -> "bb"\r\n- "aabb" -> "b"" + }, + { + "example_num": 3, + "expected_input": "word = "he"", + "expected_output": "2", + "explanation": "The two wonderful substrings are underlined below:\r\n- "he" -> "h"\r\n- "he" -> "e"" + } + ], + "solution": "/**\n * @param {string} word\n * @return {number}\n */\nconst wonderfulSubstrings = function (word) {\n const n = word.length,\n a = 'a'.charCodeAt(0)\n const map = new Map()\n map.set(0, 1)\n let res = 0\n for (let i = 0, mask = 0; i < n; i++) {\n const idx = word[i].charCodeAt(0) - a\n mask ^= 1 << idx\n res += (map.get(mask) || 0) \n for (let j = 0; j < 10; j++) {\n const tmp = mask ^ (1 << j)\n res += map.get(tmp) || 0\n }\n\n map.set(mask, (map.get(mask) || 0) + 1)\n }\n return res\n}\n\n// another\n\n\n/**\n * @param {string} word\n * @return {number}\n */\nconst wonderfulSubstrings = (word) => {\n let res = 0, count = Array(1024).fill(0);\n let cur = 0;\n count[0] = 1;\n for (let i = 0; i < word.length; ++i) {\n const num = word[i].charCodeAt() - 97;\n cur ^= 1 << (num);\n res += count[cur];\n ++count[cur];\n \n for (let j = 0; j < 10; ++j) {\n res += count[cur ^ (1 << j)];\n }\n }\n \n return res;\n};\n\n// another\n\n/**\n * @param {string} word\n * @return {number}\n */\nconst asi = (c) => c.charCodeAt();\nconst wonderfulSubstrings = (s) => {\n let res = 0;\n let f = Array(2 ** 10).fill(0);\n f[0] = 1; // count array\n let cur = res = 0;\n for (const c of s) {\n cur ^= 1 << asi(c) - 97; // get Hash (the set bit for a character.), update prefix parity\n res += f[cur];\n for (let i = 0; i < 10; i++) { // a ~ j\n res += f[cur ^ 1 << i]; // 1 << i get Hash\n }\n f[cur]++;\n }\n return res;\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720e97", + "questionid": 972, + "title": "Concatenation of Array", + "slug": "concatenation-of-array", + "description": "Given an integer array nums of length n, you want to create an array ans of length 2n where ans[i] == nums[i] and ans[i + n] == nums[i] for 0 <= i < n (0-indexed). Specifically, ans is the concatenation of two nums arrays. Return the array ans. ", + "category": [ + "Array" + ], + "complexity": "Easy", + "successrate": 91.6, + "totalsubmissions": 184207, + "totalaccepted": 168811, + "likes": 908, + "dislikes": 181, + "hints": "Build an array of size 2 * n and assign num[i] to ans[i] and ans[i + n]", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,2,1]", + "expected_output": "[1,2,1,1,2,1]", + "explanation": "The array ans is formed as follows:\n- ans = [nums[0],nums[1],nums[2],nums[0],nums[1],nums[2]]\n- ans = [1,2,1,1,2,1]" + }, + { + "example_num": 2, + "expected_input": "nums = [1,3,2,1]", + "expected_output": "[1,3,2,1,1,3,2,1]", + "explanation": "The array ans is formed as follows:\n- ans = [nums[0],nums[1],nums[2],nums[3],nums[0],nums[1],nums[2],nums[3]]\n- ans = [1,3,2,1,1,3,2,1]" + } + ], + "solution": "/**\n * @param {number[]} nums\n * @return {number[]}\n */\nconst getConcatenation = function(nums) {\n return nums.concat(nums)\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720ea3", + "questionid": 984, + "title": "Number of Ways to Separate Numbers", + "slug": "number-of-ways-to-separate-numbers", + "description": "You wrote down many positive integers in a string called num. However, you realized that you forgot to add commas to seperate the different numbers. You remember that the list of integers was non-decreasing and that no integer had leading zeros. Return the number of possible lists of integers that you could have written down to get the string num. Since the answer may be large, return it modulo 109 + 7. ", + "category": [ + "String", + "Dynamic Programming", + "Suffix Array" + ], + "complexity": "Hard", + "successrate": 22.3, + "totalsubmissions": 12191, + "totalaccepted": 2715, + "likes": 223, + "dislikes": 29, + "hints": "If we know the current number has d digits, how many digits can the previous number have? Is there a quick way of calculating the number of possibilities for the previous number if we know that it must have less than or equal to d digits? Try to do some pre-processing.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "num = "327"", + "expected_output": "2", + "explanation": "You could have written down the numbers:\n3, 27\n327" + }, + { + "example_num": 2, + "expected_input": "num = "094"", + "expected_output": "0", + "explanation": "No numbers can have leading zeros and all numbers must be positive." + }, + { + "example_num": 3, + "expected_input": "num = "0"", + "expected_output": "0", + "explanation": "No numbers can have leading zeros and all numbers must be positive." + } + ], + "solution": "/**\n * @param {string} num\n * @return {number}\n */\nfunction numberOfCombinations(num) {\n let dpArr = Array(3501).fill(0),\n dp = Array(3501).fill(0),\n prefix = Array(3501).fill(0),\n n = num.length,\n mod = 1e9 + 7\n for (let l = 1; l <= n; ++l) {\n dp[0] = 1\n for (let i = n; i - l > 0; --i)\n prefix[i - 1] = num[i - 1 - l] === num[i - 1] ? prefix[i] + 1 : 0\n for (let i = 0; i < n; ++i) {\n dpArr[i + 1] = dp[i + 1]\n if (l <= i + 1 && num[i + 1 - l] != '0') {\n if (\n i + 1 - 2 * l >= 0 &&\n (prefix[i + 1 - l] >= l ||\n num[i + 1 - l + prefix[i + 1 - l]] > num[i + 1 - 2 * l + prefix[i + 1 - l]])\n )\n dpArr[i + 1] = (dpArr[i + 1] + dpArr[i + 1 - l]) % mod\n else dpArr[i + 1] = (dpArr[i + 1] + dp[i + 1 - l]) % mod\n }\n }\n const tmp = dp\n dp = dpArr\n dpArr = tmp\n }\n return dp[n]\n}\n" + }, + { + "_id": "66f925ddfdfb8e1665720ea5", + "questionid": 986, + "title": "Number of Strings That Appear as Substrings in Word", + "slug": "number-of-strings-that-appear-as-substrings-in-word", + "description": "Given an array of strings patterns and a string word, return the number of strings in patterns that exist as a substring in word. A substring is a contiguous sequence of characters within a string. ", + "category": [ + "String" + ], + "complexity": "Easy", + "successrate": 79.4, + "totalsubmissions": 34760, + "totalaccepted": 27602, + "likes": 276, + "dislikes": 12, + "hints": "Deal with each of the patterns individually. Use the built-in function in the language you are using to find if the pattern exists as a substring in word.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "patterns = ["a","abc","bc","d"], word = "abc"", + "expected_output": "3", + "explanation": "- "a" appears as a substring in "abc".\n- "abc" appears as a substring in "abc".\n- "bc" appears as a substring in "abc".\n- "d" does not appear as a substring in "abc".\n3 of the strings in patterns appear as a substring in word." + }, + { + "example_num": 2, + "expected_input": "patterns = ["a","b","c"], word = "aaaaabbbbb"", + "expected_output": "2", + "explanation": "- "a" appears as a substring in "aaaaabbbbb".\n- "b" appears as a substring in "aaaaabbbbb".\n- "c" does not appear as a substring in "aaaaabbbbb".\n2 of the strings in patterns appear as a substring in word." + }, + { + "example_num": 3, + "expected_input": "patterns = ["a","a","a"], word = "ab"", + "expected_output": "3", + "explanation": "Each of the patterns appears as a substring in word "ab"." + } + ], + "solution": "/**\n * @param {string[]} patterns\n * @param {string} word\n * @return {number}\n */\nconst numOfStrings = function(patterns, word) {\n let res = 0\n for(let e of patterns) {\n if(word.indexOf(e) !== -1) res++\n }\n return res\n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720eac", + "questionid": 993, + "title": "Minimize the Difference Between Target and Chosen Elements", + "slug": "minimize-the-difference-between-target-and-chosen-elements", + "description": "You are given an m x n integer matrix mat and an integer target. Choose one integer from each row in the matrix such that the absolute difference between target and the sum of the chosen elements is minimized. Return the minimum absolute difference. The absolute difference between two numbers a and b is the absolute value of a - b. ", + "category": [ + "Array", + "Dynamic Programming", + "Matrix" + ], + "complexity": "Medium", + "successrate": 32.7, + "totalsubmissions": 44943, + "totalaccepted": 14696, + "likes": 478, + "dislikes": 89, + "hints": "The sum of chosen elements will not be too large. Consider using a hash set to record all possible sums while iterating each row. Instead of keeping track of all possible sums, since in each row, we are adding positive numbers, only keep those that can be a candidate, not exceeding the target by too much.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "mat = [[1,2,3],[4,5,6],[7,8,9]], target = 13", + "expected_output": "0", + "explanation": "One possible choice is to:\n- Choose 1 from the first row.\n- Choose 5 from the second row.\n- Choose 7 from the third row.\nThe sum of the chosen elements is 13, which equals the target, so the absolute difference is 0." + }, + { + "example_num": 2, + "expected_input": "mat = [[1],[2],[3]], target = 100", + "expected_output": "94", + "explanation": "The best possible choice is to:\n- Choose 1 from the first row.\n- Choose 2 from the second row.\n- Choose 3 from the third row.\nThe sum of the chosen elements is 6, and the absolute difference is 94." + }, + { + "example_num": 3, + "expected_input": "mat = [[1,2,9,8,7]], target = 6", + "expected_output": "1", + "explanation": "The best choice is to choose 7 from the first row.\nThe absolute difference is 1." + } + ], + "solution": "/**\n * @param {number[][]} mat\n * @param {number} target\n * @return {number}\n */\nconst minimizeTheDifference = function(mat, target) {\n const m = mat.length, n = mat[0].length\n const dp = Array.from({length: m}, () => Array(70*70).fill(-1))\n return fn(0, 0)\n \n function fn(row, sum) {\n if(row === m) return Math.abs(target - sum)\n if(dp[row][sum] !== -1) return dp[row][sum]\n let res = Number.MAX_SAFE_INTEGER\n for(let j = 0; j < n; j++) {\n res = Math.min(res, fn(row + 1, sum + mat[row][j]))\n }\n return dp[row][sum] = res\n }\n};\n\n// another\n\n/**\n * @param {number[][]} mat\n * @param {number} target\n * @return {number}\n */\nconst minimizeTheDifference = function(mat, target) {\n const m = mat.length, n = mat[0].length\n const memo = Array.from({ length: m }, () => Array())\n return dfs(0, 0)\n \n function dfs(row, sum) {\n if(row === m) return Math.abs(target - sum)\n if(memo[row][sum] != null) return memo[row][sum]\n let res = Number.MAX_SAFE_INTEGER\n for(let i = 0; i < n; i++) {\n res = Math.min(res, dfs(row + 1, sum + mat[row][i]))\n }\n \n return memo[row][sum] = res\n }\n};\n\n\n\n" + }, + { + "_id": "66f925ddfdfb8e1665720ead", + "questionid": 994, + "title": "Minimum Difference Between Highest and Lowest of K Scores", + "slug": "minimum-difference-between-highest-and-lowest-of-k-scores", + "description": "You are given a 0-indexed integer array nums, where nums[i] represents the score of the ith student. You are also given an integer k. Pick the scores of any k students from the array so that the difference between the highest and the lowest of the k scores is minimized. Return the minimum possible difference. ", + "category": [ + "Array", + "Sliding Window", + "Sorting" + ], + "complexity": "Easy", + "successrate": 53.7, + "totalsubmissions": 39714, + "totalaccepted": 21342, + "likes": 295, + "dislikes": 42, + "hints": "For the difference between the highest and lowest element to be minimized, the k chosen scores need to be as close to each other as possible. What if the array was sorted? After sorting the scores, any contiguous k scores are as close to each other as possible. Apply a sliding window solution to iterate over each contiguous k scores, and find the minimum of the differences of all windows.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [90], k = 1", + "expected_output": "0", + "explanation": "There is one way to pick score(s) of one student:\n- [90]. The difference between the highest and lowest score is 90 - 90 = 0.\nThe minimum possible difference is 0." + }, + { + "example_num": 2, + "expected_input": "nums = [9,4,1,7], k = 2", + "expected_output": "2", + "explanation": "There are six ways to pick score(s) of two students:\n- [9,4,1,7]. The difference between the highest and lowest score is 9 - 4 = 5.\n- [9,4,1,7]. The difference between the highest and lowest score is 9 - 1 = 8.\n- [9,4,1,7]. The difference between the highest and lowest score is 9 - 7 = 2.\n- [9,4,1,7]. The difference between the highest and lowest score is 4 - 1 = 3.\n- [9,4,1,7]. The difference between the highest and lowest score is 7 - 4 = 3.\n- [9,4,1,7]. The difference between the highest and lowest score is 7 - 1 = 6.\nThe minimum possible difference is 2." + } + ], + "solution": "/**\n * @param {number[]} nums\n * @param {number} k\n * @return {number}\n */\nconst minimumDifference = function(nums, k) {\n nums.sort((a, b) => a - b)\n let res = Infinity\n for(let i = 0, n = nums.length; i < n - k + 1; i++) {\n res = Math.min(res, nums[i + k - 1] - nums[i])\n }\n \n return res\n \n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720eb2", + "questionid": 999, + "title": "Number of Pairs of Interchangeable Rectangles", + "slug": "number-of-pairs-of-interchangeable-rectangles", + "description": "You are given n rectangles represented by a 0-indexed 2D integer array rectangles, where rectangles[i] = [widthi, heighti] denotes the width and height of the ith rectangle. Two rectangles i and j (i < j) are considered interchangeable if they have the same width-to-height ratio. More formally, two rectangles are interchangeable if widthi/heighti == widthj/heightj (using decimal division, not integer division). Return the number of pairs of interchangeable rectangles in rectangles. ", + "category": [ + "Array", + "Hash Table", + "Math", + "Counting", + "Number Theory" + ], + "complexity": "Medium", + "successrate": 43, + "totalsubmissions": 36412, + "totalaccepted": 15645, + "likes": 212, + "dislikes": 20, + "hints": "Store the rectangle height and width ratio in a hashmap. Traverse the ratios, and for each ratio, use the frequency of the ratio to add to the total pair count.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "rectangles = [[4,8],[3,6],[10,20],[15,30]]", + "expected_output": "6", + "explanation": "The following are the interchangeable pairs of rectangles by index (0-indexed):\n- Rectangle 0 with rectangle 1: 4/8 == 3/6.\n- Rectangle 0 with rectangle 2: 4/8 == 10/20.\n- Rectangle 0 with rectangle 3: 4/8 == 15/30.\n- Rectangle 1 with rectangle 2: 3/6 == 10/20.\n- Rectangle 1 with rectangle 3: 3/6 == 15/30.\n- Rectangle 2 with rectangle 3: 10/20 == 15/30." + }, + { + "example_num": 2, + "expected_input": "rectangles = [[4,5],[7,8]]", + "expected_output": "0", + "explanation": "There are no interchangeable pairs of rectangles." + } + ], + "solution": "/**\n * @param {number[][]} rectangles\n * @return {number}\n */\nconst interchangeableRectangles = function(rectangles) {\n const count = new Map()\n\n for (const [w, h] of rectangles) {\n count.set( w / h, 1 + (count.get( w / h) || 0))\n }\n\n let res = 0\n for (let c of count.values()) {\n if(c > 1) res += ((c * (c - 1)) / 2)\n }\n return res \n};\n" + }, + { + "_id": "66f925ddfdfb8e1665720eb3", + "questionid": 1000, + "title": "Maximum Product of the Length of Two Palindromic Subsequences", + "slug": "maximum-product-of-the-length-of-two-palindromic-subsequences", + "description": "Given a string s, find two disjoint palindromic subsequences of s such that the product of their lengths is maximized. The two subsequences are disjoint if they do not both pick a character at the same index. Return the maximum possible product of the lengths of the two palindromic subsequences. A subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters. A string is palindromic if it reads the same forward and backward. ", + "category": [ + "String", + "Dynamic Programming", + "Backtracking", + "Bit Manipulation", + "Bitmask" + ], + "complexity": "Medium", + "successrate": 52.8, + "totalsubmissions": 21493, + "totalaccepted": 11339, + "likes": 436, + "dislikes": 30, + "hints": "Could you generate all possible pairs of disjoint subsequences? Could you find the maximum length palindrome in each subsequence for a pair of disjoint subsequences?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "leetcodecom"", + "expected_output": "9\nExplanation: An optimal solution is to choose "ete" for the 1st subsequence and "cdc" for the 2nd subsequence.\nThe product of their lengths is: 3 * 3 = 9.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "s = "bb"", + "expected_output": "1\nExplanation: An optimal solution is to choose "b" (the first character) for the 1st subsequence and "b" (the second character) for the 2nd subsequence.\nThe product of their lengths is: 1 * 1 = 1.", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "s = "accbcaxxcxx"", + "expected_output": "25\nExplanation: An optimal solution is to choose "accca" for the 1st subsequence and "xxcxx" for the 2nd subsequence.\nThe product of their lengths is: 5 * 5 = 25.", + "explanation": "" + } + ], + "solution": "/**\n * @param {string} s\n * @return {number}\n */\nconst maxProduct = function(s) {\n const n = s.length\n const limit = (1 << n) - 1\n let res = 0\n for(let mask = 1; mask < limit; mask++) {\n res = Math.max(res, lp(mask) * lp(limit - mask))\n }\n return res\n \n function lp(state) {\n if(state === 0) return 0\n const str = []\n let idx = 0\n // console.log((state))\n while(idx < s.length) {\n // console.log((state >>> 0).toString(2))\n if((state >> idx) & 1) str.push(s[s.length - 1 - idx])\n idx++\n }\n // console.log(str)\n const len = str.length\n const dp = Array.from({ length: len }, () => Array(len).fill(0))\n for(let i = 0; i < len; i++) dp[i][i] = 1\n \n for(let length = 2; length <= len; length++) {\n for(let i = 0; i + length - 1 < len; i++) {\n const j = i + length - 1\n if(str[i] === str[j]) dp[i][j] = dp[i + 1][j - 1] + 2\n else dp[i][j] = Math.max(dp[i + 1][j], dp[i][j - 1])\n }\n }\n \n // console.log(dp, len)\n return dp[0][len - 1]\n } \n};\n\n// another\n\n/**\n * @param {string} s\n * @return {number}\n */\nvar maxProduct = function(s) {\n const n = s.length;\n let max = 0;\n for (let i = 0; i < (1 << n); i++) {\n let n0 = palindromic(i, s, true);\n if (n0 === 0) continue;\n for (let j = 0; j < (1 << n); j++) {\n if ((i & j) > 0) continue;\n max = Math.max(palindromic(j, s) * n0, max);\n }\n }\n return max; \n};\nfunction palindromic( i, s) {\n const n = s.length;\n let sub = \"\";\n for (let x = 0; x < n; x++) {\n if (i & (1 << x)) sub += s[x]\n }\n let len = sub.length;\n for (let i = 0; i < len; i++) {\n if (sub[i] !== sub[len - i - 1]) return 0;\n }\n return len;\n}\n\n// another\n\n/**\n * @param {string} s\n * @return {number}\n */\nconst maxProduct = function(s) {\n const s1 = [], s2 = [], n = s.length\n let res = 0\n dfs(0)\n return res\n \n function dfs(idx) {\n if(idx === n) {\n if(isPalindromic(s1) && isPalindromic(s2)) {\n res = Math.max(res, s1.length * s2.length)\n }\n return\n }\n const ch = s[idx]\n s1.push(ch)\n dfs(idx + 1)\n s1.pop()\n \n s2.push(ch)\n dfs(idx + 1)\n s2.pop()\n \n dfs(idx + 1)\n }\n function isPalindromic(arr) {\n let l = 0, r = arr.length - 1\n while(l < r) {\n if(arr[l] === arr[r]) {\n l++\n r--\n } else {\n return false\n }\n }\n return true\n }\n};\n" + }, + { + "_id": "66f925defdfb8e1665720eb6", + "questionid": 1003, + "title": "Number of Pairs of Strings With Concatenation Equal to Target", + "slug": "number-of-pairs-of-strings-with-concatenation-equal-to-target", + "description": "Given an array of digit strings nums and a digit string target, return the number of pairs of indices (i, j) (where i != j) such that the concatenation of nums[i] + nums[j] equals target. ", + "category": [ + "Array", + "String" + ], + "complexity": "Medium", + "successrate": 73, + "totalsubmissions": 23817, + "totalaccepted": 17394, + "likes": 278, + "dislikes": 26, + "hints": "Try to concatenate every two different strings from the list. Count the number of pairs with concatenation equals to target.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = ["777","7","77","77"], target = "7777"", + "expected_output": "4", + "explanation": "Valid pairs are:\n- (0, 1): "777" + "7"\n- (1, 0): "7" + "777"\n- (2, 3): "77" + "77"\n- (3, 2): "77" + "77"" + }, + { + "example_num": 2, + "expected_input": "nums = ["123","4","12","34"], target = "1234"", + "expected_output": "2", + "explanation": "Valid pairs are:\n- (0, 1): "123" + "4"\n- (2, 3): "12" + "34"" + }, + { + "example_num": 3, + "expected_input": "nums = ["1","1","1"], target = "11"", + "expected_output": "6", + "explanation": "Valid pairs are:\n- (0, 1): "1" + "1"\n- (1, 0): "1" + "1"\n- (0, 2): "1" + "1"\n- (2, 0): "1" + "1"\n- (1, 2): "1" + "1"\n- (2, 1): "1" + "1"" + } + ], + "solution": "/**\n * @param {string[]} nums\n * @param {string} target\n * @return {number}\n */\nconst numOfPairs = function(nums, target) {\n let res = 0\n \n const n = nums.length\n for(let i = 0; i < n; i++) {\n for(let j = 0; j < n; j++) {\n if(i !== j && nums[i] + nums[j] === target) res++\n }\n }\n \n return res\n};\n" + }, + { + "_id": "66f925defdfb8e1665720eb7", + "questionid": 1004, + "title": "Longest Subsequence Repeated k Times", + "slug": "longest-subsequence-repeated-k-times", + "description": "You are given a string s of length n, and an integer k. You are tasked to find the longest subsequence repeated k times in string s. A subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters. A subsequence seq is repeated k times in the string s if seq * k is a subsequence of s, where seq * k represents a string constructed by concatenating seq k times. Return the longest subsequence repeated k times in string s. If multiple such subsequences are found, return the lexicographically largest one. If there is no such subsequence, return an empty string. ", + "category": [ + "String", + "Backtracking", + "Greedy", + "Counting", + "Enumeration" + ], + "complexity": "Hard", + "successrate": 54.7, + "totalsubmissions": 7316, + "totalaccepted": 4005, + "likes": 185, + "dislikes": 52, + "hints": "The length of the longest subsequence does not exceed n/k. Do you know why? Find the characters that could be included in the potential answer. A character occurring more than or equal to k times can be used in the answer up to (count of the character / k) times. Try all possible candidates in reverse lexicographic order, and check the string for the subsequence condition.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "letsleetcode", k = 2", + "expected_output": ""let"", + "explanation": "There are two longest subsequences repeated 2 times: "let" and "ete".\n"let" is the lexicographically largest one." + }, + { + "example_num": 2, + "expected_input": "s = "bb", k = 2", + "expected_output": ""b"", + "explanation": "The longest subsequence repeated 2 times is "b"." + }, + { + "example_num": 3, + "expected_input": "s = "ab", k = 2", + "expected_output": """", + "explanation": "There is no subsequence repeated 2 times. Empty string is returned." + } + ], + "solution": "/**\n * @param {string} s\n * @param {number} k\n * @return {string}\n */\nconst longestSubsequenceRepeatedK = function(s, k) {\n const n = s.length, a = 'a'.charCodeAt(0)\n \n let res = ''\n const q = ['']\n \n while(q.length) {\n const size = q.length\n for(let i = 0; i < size; i++) {\n const cur = q.shift()\n for(let j = 0; j < 26; j++) {\n const next = cur + String.fromCharCode(a + j)\n if(isSub(s, next, k)) {\n res = next\n q.push(next)\n }\n }\n \n }\n }\n \n return res\n \n \n function isSub(s, p, k) {\n let repeated = 0\n for(let i = 0, j = 0, n = s.length, m = p.length; i < n; i++) {\n if(s[i] === p[j]) {\n j++\n if(j === m) {\n repeated++\n j = 0\n if(repeated === k) {\n return true\n }\n }\n }\n }\n \n return false\n }\n};\n\n// another\n\n/**\n * @param {string} s\n * @param {number} k\n * @return {string}\n */\nvar longestSubsequenceRepeatedK = function(s, k) {\n // Max length of the subsequence can be determined by the length of the string and k\n const maxLen = Math.floor(s.length / k);\n\n // Find all possible characters that can appear in the subsequence (characters must appear at\n // least k times in s)\n const charCount = new Map();\n const possibleChars = []\n\n for (const char of s) {\n if (charCount.has(char)) {\n charCount.set(char, charCount.get(char) + 1);\n } else {\n charCount.set(char, 1);\n }\n }\n\n for (const char of charCount.keys()) {\n if (charCount.get(char) >= k) {\n possibleChars.push(char);\n }\n }\n\n // Test possibilities\n let ans = \"\";\n dfs(\"\");\n\n return ans;\n\n // Recursive function, tests if the given subsequence repeats k times in s\n function dfs(seq) {\n // Does not have enough repeats, return\n if (countRepeats(seq) < k) {\n return;\n }\n\n // Update our answer if the new subsequence is better\n if (seq.length > ans.length || (seq.length === ans.length && seq > ans)) {\n ans = seq;\n }\n\n // Append possible characters to the subsequence and test again\n if (seq.length < maxLen) {\n for (const char of possibleChars) {\n dfs(seq + char);\n }\n }\n }\n\n // Counts the number of times the given subsequence repeats in s (up to k)\n function countRepeats(seq) {\n\n // Empty string, return k\n if (!seq) {\n return k;\n }\n\n let repeats = 0;\n let seqIdx = 0;\n\n for (const char of s) {\n if (char === seq[seqIdx]) {\n seqIdx += 1;\n\n if (seqIdx >= seq.length) {\n seqIdx = 0;\n repeats += 1;\n\n if (repeats >= k) {\n break;\n }\n }\n }\n }\n\n return repeats;\n } \n};\n" + }, + { + "_id": "66f925defdfb8e1665720ec1", + "questionid": 1014, + "title": "Kth Distinct String in an Array", + "slug": "kth-distinct-string-in-an-array", + "description": "A distinct string is a string that is present only once in an array. Given an array of strings arr, and an integer k, return the kth distinct string present in arr. If there are fewer than k distinct strings, return an empty string \"\". Note that the strings are considered in the order in which they appear in the array. ", + "category": [ + "Array", + "Hash Table", + "String", + "Counting" + ], + "complexity": "Easy", + "successrate": 72.9, + "totalsubmissions": 29728, + "totalaccepted": 21680, + "likes": 288, + "dislikes": 6, + "hints": "Try 'mapping' the strings to check if they are unique or not.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "arr = ["d","b","c","b","c","a"], k = 2", + "expected_output": ""a"", + "explanation": "The only distinct strings in arr are "d" and "a".\n"d" appears 1st, so it is the 1st distinct string.\n"a" appears 2nd, so it is the 2nd distinct string.\nSince k == 2, "a" is returned." + }, + { + "example_num": 2, + "expected_input": "arr = ["aaa","aa","a"], k = 1", + "expected_output": ""aaa"", + "explanation": "All strings in arr are distinct, so the 1st string "aaa" is returned." + }, + { + "example_num": 3, + "expected_input": "arr = ["a","b","a"], k = 3", + "expected_output": """", + "explanation": "The only distinct string is "b". Since there are fewer than 3 distinct strings, we return an empty string ""." + } + ], + "solution": "/**\n * @param {string[]} arr\n * @param {number} k\n * @return {string}\n */\nconst kthDistinct = function(arr, k) {\n let num = 0, hash = {}\n \n for(let str of arr) {\n if(hash[str] == null) hash[str] = 0\n hash[str]++ \n }\n for(let str of arr) {\n if(hash[str] > 1) continue\n num++\n if(num === k) return str\n }\n return ''\n};\n" + }, + { + "_id": "66f925defdfb8e1665720ec2", + "questionid": 1015, + "title": "Plates Between Candles", + "slug": "plates-between-candles", + "description": "There is a long table with a line of plates and candles arranged on top of it. You are given a 0-indexed string s consisting of characters '*' and '|' only, where a '*' represents a plate and a '|' represents a candle. You are also given a 0-indexed 2D integer array queries where queries[i] = [lefti, righti] denotes the substring s[lefti...righti] (inclusive). For each query, you need to find the number of plates between candles that are in the substring. A plate is considered between candles if there is at least one candle to its left and at least one candle to its right in the substring. Return an integer array answer where answer[i] is the answer to the ith query. ", + "category": [ + "Array", + "String", + "Binary Search", + "Prefix Sum" + ], + "complexity": "Medium", + "successrate": 46, + "totalsubmissions": 22217, + "totalaccepted": 10217, + "likes": 381, + "dislikes": 10, + "hints": "Can you find the indices of the most left and right candles for a given substring, perhaps by using binary search (or better) over an array of indices of all the bars? Once the indices of the most left and right bars are determined, how can you efficiently count the number of plates within the range? Prefix sums?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "**|**|***|", queries = [[2,5],[5,9]]", + "expected_output": "[2,3]", + "explanation": "- queries[0] has two plates between candles.\n- queries[1] has three plates between candles." + }, + { + "example_num": 2, + "expected_input": "s = "***|**|*****|**||**|*", queries = [[1,17],[4,5],[14,17],[5,11],[15,16]]", + "expected_output": "[9,0,0,0,0]", + "explanation": "- queries[0] has nine plates between candles.\n- The other queries have zero plates between candles." + } + ], + "solution": "/**\n * @param {string} s\n * @param {number[][]} queries\n * @return {number[]}\n */\nconst platesBetweenCandles = function (s, queries) {\n const candleIdxArr = []\n const n = s.length\n for(let i = 0; i < n; i++) {\n if(s[i] === '|') candleIdxArr.push(i)\n }\n // console.log(candleIdxArr)\n const res = []\n for(const [s, e] of queries) {\n const l = lower(candleIdxArr, s, e)\n const r = upper(candleIdxArr, s ,e)\n const tmp = (candleIdxArr[r] - candleIdxArr[l] + 1) - (r - l + 1)\n res.push(tmp >= 0 ? tmp : 0)\n }\n\n return res\n\n\n function lower(arr,s,e) {\n let l = 0, r = arr.length - 1\n while(l < r) {\n // console.log('lower',l, r)\n const mid = ~~(l + (r - l)/2)\n if(arr[mid] < s) l = mid + 1\n else r = mid\n }\n return l\n }\n\n function upper(arr,s, e) {\n let l = 0, r = arr.length - 1\n while(l < r) {\n\n const mid = r - ~~((r - l)/2)\n // console.log('upper', l, r, mid, e)\n if(arr[mid] > e) r = mid - 1\n else l = mid\n }\n return l\n }\n}\n\n// another\n\n/**\n * @param {string} s\n * @param {number[][]} queries\n * @return {number[]}\n */\nconst platesBetweenCandles = function(s, queries) {\n const n = s.length,\n leftCandlePos = Array(n).fill(-1)\n rightCandlePos = Array(n).fill(-1)\n candleCnt = Array(n).fill(0)\n let pos = -1\n for(let i = 0; i < n; i++) {\n if(s[i] === '|') pos = i\n leftCandlePos[i] = pos\n }\n pos = -1\n for(let i = n - 1; i >= 0; i--) {\n if(s[i] === '|') pos = i\n rightCandlePos[i] = pos\n }\n for(let i = 0, cnt = 0; i < n; i++) {\n if(s[i] === '|') cnt++\n candleCnt[i] = cnt\n }\n\n const len = queries.length, res = Array(len).fill(0)\n\n for(let i = 0; i < len; i++) {\n const [left, right] = queries[i]\n const leftCandle = rightCandlePos[left], rightCandle = leftCandlePos[right]\n const delta = rightCandle - leftCandle\n if(leftCandle !== -1 && rightCandle !== -1 && delta > 1) {\n res[i] = delta + 1 - (candleCnt[rightCandle] - candleCnt[leftCandle] + 1)\n }\n }\n\n return res\n}\n\n// another\n\n/**\n * @param {string} s\n * @param {number[][]} queries\n * @return {number[]}\n */\nconst platesBetweenCandles = function (s, queries) {\n const n = s.length\n const leftArr = Array(n).fill(-1),\n rightArr = Array(n).fill(n),\n candleCnt = Array(n).fill(0)\n let candle = -1\n for (let i = 0; i < n; i++) {\n if (s[i] === '|') candle = i\n leftArr[i] = candle\n }\n candle = n\n for (let i = n - 1; i >= 0; i--) {\n if (s[i] === '|') candle = i\n rightArr[i] = candle\n }\n let cnt = 0\n for (let i = 0; i < n; i++) {\n if (s[i] === '|') cnt++\n candleCnt[i] = cnt\n }\n // console.log(leftArr, rightArr)\n const res = []\n for (const [s, e] of queries) {\n const l = rightArr[s]\n const r = leftArr[e]\n const diff = r - l\n if (diff > 1) {\n const e = r - l + 1 - (candleCnt[r] - candleCnt[l] + 1)\n res.push(e)\n } else res.push(0)\n }\n\n return res\n}\n\n" + }, + { + "_id": "66f925defdfb8e1665720ec4", + "questionid": 1017, + "title": "Count Number of Maximum Bitwise-OR Subsets", + "slug": "count-number-of-maximum-bitwise-or-subsets", + "description": "Given an integer array nums, find the maximum possible bitwise OR of a subset of nums and return the number of different non-empty subsets with the maximum bitwise OR. An array a is a subset of an array b if a can be obtained from b by deleting some (possibly zero) elements of b. Two subsets are considered different if the indices of the elements chosen are different. The bitwise OR of an array a is equal to a[0] OR a[1] OR ... OR a[a.length - 1] (0-indexed). ", + "category": [ + "Array", + "Backtracking", + "Bit Manipulation" + ], + "complexity": "Medium", + "successrate": 74.8, + "totalsubmissions": 17312, + "totalaccepted": 12945, + "likes": 246, + "dislikes": 13, + "hints": "Can we enumerate all possible subsets? The maximum bitwise-OR is the bitwise-OR of the whole array.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [3,1]", + "expected_output": "2", + "explanation": "The maximum possible bitwise OR of a subset is 3. There are 2 subsets with a bitwise OR of 3:\n- [3]\n- [3,1]" + }, + { + "example_num": 2, + "expected_input": "nums = [2,2,2]", + "expected_output": "7", + "explanation": "All non-empty subsets of [2,2,2] have a bitwise OR of 2. There are 23 - 1 = 7 total subsets." + }, + { + "example_num": 3, + "expected_input": "nums = [3,2,1,5]", + "expected_output": "6", + "explanation": "The maximum possible bitwise OR of a subset is 7. There are 6 subsets with a bitwise OR of 7:\n- [3,5]\n- [3,1,5]\n- [3,2,5]\n- [3,2,1,5]\n- [2,5]\n- [2,1,5]" + } + ], + "solution": "/**\n * @param {number[]} nums\n * @return {number}\n */\nconst countMaxOrSubsets = function(nums) {\n let res = 0, max = 0, n = nums.length\n for(let num of nums) max |= num\n dfs(0, 0)\n dfs(0, nums[0])\n return res\n \n function dfs(i, cur) {\n if(i === n) return\n if(cur === max) return res += Math.pow(2, n - 1 - i)\n dfs(i + 1, cur)\n dfs(i + 1, cur | nums[i + 1])\n }\n};\n" + }, + { + "_id": "66f925defdfb8e1665720ecb", + "questionid": 1024, + "title": "Find the Minimum and Maximum Number of Nodes Between Critical Points", + "slug": "find-the-minimum-and-maximum-number-of-nodes-between-critical-points", + "description": "A critical point in a linked list is defined as either a local maxima or a local minima. A node is a local maxima if the current node has a value strictly greater than the previous node and the next node. A node is a local minima if the current node has a value strictly smaller than the previous node and the next node. Note that a node can only be a local maxima/minima if there exists both a previous node and a next node. Given a linked list head, return an array of length 2 containing [minDistance, maxDistance] where minDistance is the minimum distance between any\u00a0two distinct critical points and maxDistance is the maximum distance between any\u00a0two distinct critical points. If there are fewer than two critical points, return [-1, -1]. ", + "category": [ + "Linked List" + ], + "complexity": "Medium", + "successrate": 57.7, + "totalsubmissions": 25922, + "totalaccepted": 14965, + "likes": 248, + "dislikes": 12, + "hints": "The maximum distance must be the distance between the first and last critical point. For each adjacent critical point, calculate the difference and check if it is the minimum distance.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "head = [3,1]", + "expected_output": "[-1,-1]", + "explanation": "There are no critical points in [3,1]." + }, + { + "example_num": 2, + "expected_input": "head = [5,3,1,2,5,1,2]", + "expected_output": "[1,3]", + "explanation": "There are three critical points:\n- [5,3,1,2,5,1,2]: The third node is a local minima because 1 is less than 3 and 2.\n- [5,3,1,2,5,1,2]: The fifth node is a local maxima because 5 is greater than 2 and 1.\n- [5,3,1,2,5,1,2]: The sixth node is a local minima because 1 is less than 5 and 2.\nThe minimum distance is between the fifth and the sixth node. minDistance = 6 - 5 = 1.\nThe maximum distance is between the third and the sixth node. maxDistance = 6 - 3 = 3." + }, + { + "example_num": 3, + "expected_input": "head = [1,3,2,2,3,2,2,2,7]", + "expected_output": "[3,3]", + "explanation": "There are two critical points:\n- [1,3,2,2,3,2,2,2,7]: The second node is a local maxima because 3 is greater than 1 and 2.\n- [1,3,2,2,3,2,2,2,7]: The fifth node is a local maxima because 3 is greater than 2 and 2.\nBoth the minimum and maximum distances are between the second and the fifth node.\nThus, minDistance and maxDistance is 5 - 2 = 3.\nNote that the last node is not considered a local maxima because it does not have a next node." + } + ], + "solution": "/**\n * Definition for singly-linked list.\n * function ListNode(val, next) {\n * this.val = (val===undefined ? 0 : val)\n * this.next = (next===undefined ? null : next)\n * }\n */\n/**\n * @param {ListNode} head\n * @return {number[]}\n */\nconst nodesBetweenCriticalPoints = function(head) {\n const arr = []\n let cur = head\n while(cur) {\n arr.push(cur.val)\n cur = cur.next\n }\n const idxArr = []\n const n = arr.length\n for(let i = 1; i < n - 1; i++) {\n if((arr[i] > arr[i - 1] && arr[i] > arr[i + 1]) || (arr[i] < arr[i - 1] && arr[i] < arr[i + 1])) {\n idxArr.push(i)\n }\n }\n \n let min = Infinity, max = -1\n for(let i = 1; i < idxArr.length; i++) {\n if(idxArr[i] - idxArr[i - 1] < min) min = idxArr[i] - idxArr[i - 1]\n }\n if(idxArr.length > 1) max = idxArr[idxArr.length - 1] - idxArr[0]\n return [min === Infinity ? -1 : min, max]\n};\n" + }, + { + "_id": "66f925defdfb8e1665720ecf", + "questionid": 1028, + "title": "Time Needed to Buy Tickets", + "slug": "time-needed-to-buy-tickets", + "description": "There are n people in a line queuing to buy tickets, where the 0th person is at the front of the line and the (n - 1)th person is at the back of the line. You are given a 0-indexed integer array tickets of length n where the number of tickets that the ith person would like to buy is tickets[i]. Each person takes exactly 1 second to buy a ticket. A person can only buy 1 ticket at a time and has to go back to the end of the line (which happens instantaneously) in order to buy more tickets. If a person does not have any tickets left to buy, the person will leave the line. Return the time taken for the person at position k\u00a0(0-indexed)\u00a0to finish buying tickets. ", + "category": [ + "Array", + "Queue", + "Simulation" + ], + "complexity": "Easy", + "successrate": 62.4, + "totalsubmissions": 33581, + "totalaccepted": 20942, + "likes": 329, + "dislikes": 22, + "hints": "Loop through the line of people and decrement the number of tickets for each to buy one at a time as if simulating the line moving forward. Keep track of how many tickets have been sold up until person k has no more tickets to buy. Remember that those who have no more tickets to buy will leave the line.", + "deleted": false, + "examples": [], + "solution": "/**\n * @param {number[]} tickets\n * @param {number} k\n * @return {number}\n */\nconst timeRequiredToBuy = function(tickets, k) {\n let res = 0\n \n while(tickets[k] !== 0) {\n res += helper(tickets, k)\n }\n \n return res\n \n function helper(arr, k) {\n let tmp = 0\n for(let i = 0; i < arr.length; i++) {\n if(arr[i] > 0) {\n arr[i]--\n tmp++\n }\n if(arr[k] === 0) break\n }\n return tmp\n }\n \n};\n" + }, + { + "_id": "66f925defdfb8e1665720edc", + "questionid": 1041, + "title": "Sum of Subarray Ranges", + "slug": "sum-of-subarray-ranges", + "description": "You are given an integer array nums. The range of a subarray of nums is the difference between the largest and smallest element in the subarray. Return the sum of all subarray ranges of nums. A subarray is a contiguous non-empty sequence of elements within an array. ", + "category": [ + "Array", + "Stack", + "Monotonic Stack" + ], + "complexity": "Medium", + "successrate": 60.3, + "totalsubmissions": 39464, + "totalaccepted": 23805, + "likes": 626, + "dislikes": 29, + "hints": "Can you get the max/min of a certain subarray by using the max/min of a smaller subarray within it? Notice that the max of the subarray from index i to j is equal to max of (max of the subarray from index i to j-1) and nums[j].", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,2,3]", + "expected_output": "4", + "explanation": "The 6 subarrays of nums are the following:\n[1], range = largest - smallest = 1 - 1 = 0 \n[2], range = 2 - 2 = 0\n[3], range = 3 - 3 = 0\n[1,2], range = 2 - 1 = 1\n[2,3], range = 3 - 2 = 1\n[1,2,3], range = 3 - 1 = 2\nSo the sum of all ranges is 0 + 0 + 0 + 1 + 1 + 2 = 4." + }, + { + "example_num": 2, + "expected_input": "nums = [1,3,3]", + "expected_output": "4", + "explanation": "The 6 subarrays of nums are the following:\n[1], range = largest - smallest = 1 - 1 = 0\n[3], range = 3 - 3 = 0\n[3], range = 3 - 3 = 0\n[1,3], range = 3 - 1 = 2\n[3,3], range = 3 - 3 = 0\n[1,3,3], range = 3 - 1 = 2\nSo the sum of all ranges is 0 + 0 + 0 + 2 + 0 + 2 = 4." + }, + { + "example_num": 3, + "expected_input": "nums = [4,-2,-3,4,1]", + "expected_output": "59", + "explanation": "The sum of all subarray ranges of nums is 59." + } + ], + "solution": "/**\n * @param {number[]} nums\n * @return {number}\n */\nconst subArrayRanges = function(nums) {\n const n = nums.length, { max, min } = Math\n let res = 0\n \n for(let i = 0; i < n; i++) {\n let [most, least] = [-Infinity, Infinity]\n for(let j = i; j < n; j++) {\n most = max(most, nums[j])\n least = min(least, nums[j])\n res += most - least \n }\n }\n return res\n};\n\n// another\n\n/**\n * @param {number[]} nums\n * @return {number}\n */\nconst subArrayRanges = function(nums) {\n let res = 0, n = nums.length\n for(let i = 0; i < n; i++) {\n let max = nums[i], min = nums[i]\n for(let j = i; j < n; j++) {\n max = Math.max(max, nums[j])\n min = Math.min(min, nums[j])\n res += max - min\n }\n }\n return res\n};\n" + }, + { + "_id": "66f925defdfb8e1665720ee1", + "questionid": 1046, + "title": "Minimum Operations to Make the Array K-Increasing", + "slug": "minimum-operations-to-make-the-array-k-increasing", + "description": "You are given a 0-indexed array arr consisting of n positive integers, and a positive integer k. The array arr is called K-increasing if arr[i-k] <= arr[i] holds for every index i, where k <= i <= n-1. In one operation, you can choose an index i and change arr[i] into any positive integer. Return the minimum number of operations required to make the array K-increasing for the given k. ", + "category": [ + "Array", + "Binary Search" + ], + "complexity": "Hard", + "successrate": 36.4, + "totalsubmissions": 23198, + "totalaccepted": 8433, + "likes": 467, + "dislikes": 8, + "hints": "Can we divide the array into non-overlapping subsequences and simplify the problem? In the final array, arr[i-k] \u2030\u00a4 arr[i] should hold. We can use this to divide the array into at most k non-overlapping sequences, where arr[i] will belong to the (i%k)th sequence. Now our problem boils down to performing the minimum operations on each sequence such that it becomes non-decreasing. Our answer will be the sum of operations on each sequence. Which indices of a sequence should we not change in order to count the minimum operations? Can finding the longest non-decreasing subsequence of the sequence help?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "arr = [5,4,3,2,1], k = 1", + "expected_output": "4\nExplanation:\nFor k = 1, the resultant array has to be non-decreasing.\nSome of the K-increasing arrays that can be formed are [5,6,7,8,9], [1,1,1,1,1], [2,2,3,4,4]. All of them require 4 operations.\nIt is suboptimal to change the array to, for example, [6,7,8,9,10] because it would take 5 operations.\nIt can be shown that we cannot make the array K-increasing in less than 4 operations.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "arr = [4,1,5,2,6,2], k = 2", + "expected_output": "0", + "explanation": "This is the same example as the one in the problem description.\nHere, for every index i where 2 <= i <= 5, arr[i-2] <= arr[i].\nSince the given array is already K-increasing, we do not need to perform any operations." + }, + { + "example_num": 3, + "expected_input": "arr = [4,1,5,2,6,2], k = 3", + "expected_output": "2", + "explanation": "Indices 3 and 5 are the only ones not satisfying arr[i-3] <= arr[i] for 3 <= i <= 5.\nOne of the ways we can make the array K-increasing is by changing arr[3] to 4 and arr[5] to 5.\nThe array will now be [4,1,5,4,6,5].\nNote that there can be other ways to make the array K-increasing, but none of them require less than 2 operations." + } + ], + "solution": "/**\n * @param {number[]} arr\n * @param {number} k\n * @return {number}\n */\nconst kIncreasing = function(arr, k) {\n let res = 0, matrix = Array.from({ length: k }, () => []), n = arr.length\n for(let i = 0; i < k; i++) {\n for(let j = i; j < n; j += k) {\n matrix[i].push(arr[j])\n }\n }\n\n for (let i = 0; i < k; i++) {\n res += matrix[i].length - nonDecreasing(matrix[i])\n }\n\n return res\n\n function bisect_right(ar, x, l = 0, r) {\n if(r == null) r = ar.length\n while(l < r) {\n const mid = ~~((l + r) / 2)\n if(ar[mid] <= x) l = mid + 1\n else r = mid\n }\n return l\n }\n\n function nonDecreasing(ar) {\n let stk = []\n for(let e of ar) {\n const idx = bisect_right(stk, e)\n if(idx === stk.length) stk.push(e)\n else stk[idx] = e\n }\n\n return stk.length\n }\n};\n\n// another\n/**\n * @param {number[]} arr\n * @param {number} k\n * @return {number}\n */\nconst kIncreasing = function(arr, k) {\n const n = arr.length\n const a = Array.from({ length: k }, () => Array())\n \n for(let i = 0; i < k; i++) {\n for(let j = i; j < n; j += k) {\n a[i].push(arr[j])\n }\n }\n \n let res = 0\n for(let i = 0; i < a.length; i++) {\n const r = a[i]\n res += r.length - lis(r)\n }\n \n return res\n \n function bisect_right(a, x, lo = 0, hi = null) { // > upper_bound\n if (lo < 0) throw new Error('lo must be non-negative');\n if (hi == null) hi = a.length;\n while (lo < hi) {\n let mid = parseInt((lo + hi) / 2);\n x < a[mid] ? hi = mid : lo = mid + 1;\n }\n return lo;\n }\n \n function lis(ar) {\n let q = []\n for (let x of ar) {\n let i = bisect_right(q, x)\n if (i == q.length) q.push(x)\n else q[i] = x \n }\n\n return q.length\n }\n};\n\n" + }, + { + "_id": "66f925defdfb8e1665720ee3", + "questionid": 1048, + "title": "Longest Palindrome by Concatenating Two Letter Words", + "slug": "longest-palindrome-by-concatenating-two-letter-words", + "description": "You are given an array of strings words. Each element of words consists of two lowercase English letters. Create the longest possible palindrome by selecting some elements from words and concatenating them in any order. Each element can be selected at most once. Return the length of the longest palindrome that you can create. If it is impossible to create any palindrome, return 0. A palindrome is a string that reads the same forward and backward. ", + "category": [ + "Array", + "Hash Table", + "String", + "Greedy", + "Counting" + ], + "complexity": "Medium", + "successrate": 38.3, + "totalsubmissions": 33870, + "totalaccepted": 12956, + "likes": 381, + "dislikes": 8, + "hints": "A palindrome must be mirrored over the center. Suppose we have a palindrome. If we prepend the word \"ab\" on the left, what must we append on the right to keep it a palindrome? We must append \"ba\" on the right. The number of times we can do this is the minimum of (occurrences of \"ab\") and (occurrences of \"ba\"). For words that are already palindromes, e.g. \"aa\", we can prepend and append these in pairs as described in the previous hint. We can also use exactly one in the middle to form an even longer palindrome.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "words = ["lc","cl","gg"]", + "expected_output": "6", + "explanation": "One longest palindrome is "lc" + "gg" + "cl" = "lcggcl", of length 6.\nNote that "clgglc" is another longest palindrome that can be created." + }, + { + "example_num": 2, + "expected_input": "words = ["ab","ty","yt","lc","cl","ab"]", + "expected_output": "8", + "explanation": "One longest palindrome is "ty" + "lc" + "cl" + "yt" = "tylcclyt", of length 8.\nNote that "lcyttycl" is another longest palindrome that can be created." + }, + { + "example_num": 3, + "expected_input": "words = ["cc","ll","xx"]", + "expected_output": "2", + "explanation": "One longest palindrome is "cc", of length 2.\nNote that "ll" is another longest palindrome that can be created, and so is "xx"." + } + ], + "solution": null + }, + { + "_id": "66f925defdfb8e1665720ee6", + "questionid": 1051, + "title": "Destroying Asteroids", + "slug": "destroying-asteroids", + "description": "You are given an integer mass, which represents the original mass of a planet. You are further given an integer array asteroids, where asteroids[i] is the mass of the ith asteroid. You can arrange for the planet to collide with the asteroids in any arbitrary order. If the mass of the planet is greater than or equal to the mass of the asteroid, the asteroid is destroyed and the planet gains the mass of the asteroid. Otherwise, the planet is destroyed. Return true if all asteroids can be destroyed. Otherwise, return false. ", + "category": [ + "Array", + "Greedy", + "Sorting" + ], + "complexity": "Medium", + "successrate": 48.4, + "totalsubmissions": 37728, + "totalaccepted": 18243, + "likes": 198, + "dislikes": 106, + "hints": "Choosing the asteroid to collide with can be done greedily. If an asteroid will destroy the planet, then every bigger asteroid will also destroy the planet. You only need to check the smallest asteroid at each collision. If it will destroy the planet, then every other asteroid will also destroy the planet. Sort the asteroids in non-decreasing order by mass, then greedily try to collide with the asteroids in that order.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "mass = 10, asteroids = [3,9,19,5,21]", + "expected_output": "true", + "explanation": "One way to order the asteroids is [9,19,5,3,21]:\n- The planet collides with the asteroid with a mass of 9. New planet mass: 10 + 9 = 19\n- The planet collides with the asteroid with a mass of 19. New planet mass: 19 + 19 = 38\n- The planet collides with the asteroid with a mass of 5. New planet mass: 38 + 5 = 43\n- The planet collides with the asteroid with a mass of 3. New planet mass: 43 + 3 = 46\n- The planet collides with the asteroid with a mass of 21. New planet mass: 46 + 21 = 67\nAll asteroids are destroyed." + }, + { + "example_num": 2, + "expected_input": "mass = 5, asteroids = [4,9,23,4]", + "expected_output": "false", + "explanation": "The planet cannot ever gain enough mass to destroy the asteroid with a mass of 23.\nAfter the planet destroys the other asteroids, it will have a mass of 5 + 4 + 9 + 4 = 22.\nThis is less than 23, so a collision would not destroy the last asteroid." + } + ], + "solution": "/**\n * @param {number} mass\n * @param {number[]} asteroids\n * @return {boolean}\n */\nconst asteroidsDestroyed = function(mass, asteroids) {\n asteroids.sort((a, b) => a - b)\n let res = true\n for(let i = 0, n = asteroids.length; i < n; i++) {\n const cur = asteroids[i]\n if(mass >= cur) {\n mass += cur\n } else {\n res = false\n break\n }\n }\n \n return res\n};\n" + }, + { + "_id": "66f925defdfb8e1665720ee9", + "questionid": 1054, + "title": "Count the Hidden Sequences", + "slug": "count-the-hidden-sequences", + "description": "You are given a 0-indexed array of n integers differences, which describes the differences between each pair of consecutive integers of a hidden sequence of length (n + 1). More formally, call the hidden sequence hidden, then we have that differences[i] = hidden[i + 1] - hidden[i]. You are further given two integers lower and upper that describe the inclusive range of values [lower, upper] that the hidden sequence can contain. Return the number of possible hidden sequences there are. If there are no possible sequences, return 0. ", + "category": [ + "Array", + "Prefix Sum" + ], + "complexity": "Medium", + "successrate": 35.1, + "totalsubmissions": 32252, + "totalaccepted": 11334, + "likes": 356, + "dislikes": 37, + "hints": "Fix the first element of the hidden sequence to any value x and ignore the given bounds. Notice that we can then determine all the other elements of the sequence by using the differences array. We will also be able to determine the difference between the minimum and maximum elements of the sequence. Notice that the value of x does not affect this. We now have the \u20ac\u02dcrange\u20ac\u2122 of the sequence (difference between min and max element), we can then calculate how many ways there are to fit this range into the given range of lower to upper. Answer is (upper - lower + 1) - (range of sequence)", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "differences = [1,-3,4], lower = 1, upper = 6", + "expected_output": "2", + "explanation": "The possible hidden sequences are:\n- [3, 4, 1, 5]\n- [4, 5, 2, 6]\nThus, we return 2." + }, + { + "example_num": 2, + "expected_input": "differences = [3,-4,5,1,-2], lower = -4, upper = 5", + "expected_output": "4", + "explanation": "The possible hidden sequences are:\n- [-3, 0, -4, 1, 2, 0]\n- [-2, 1, -3, 2, 3, 1]\n- [-1, 2, -2, 3, 4, 2]\n- [0, 3, -1, 4, 5, 3]\nThus, we return 4." + }, + { + "example_num": 3, + "expected_input": "differences = [4,-7,2], lower = 3, upper = 6", + "expected_output": "0", + "explanation": "There are no possible hidden sequences. Thus, we return 0." + } + ], + "solution": null + }, + { + "_id": "66f925defdfb8e1665720eeb", + "questionid": 1056, + "title": "Check if Every Row and Column Contains All Numbers", + "slug": "check-if-every-row-and-column-contains-all-numbers", + "description": "An n x n matrix is valid if every row and every column contains all the integers from 1 to n (inclusive). Given an n x n integer matrix matrix, return true if the matrix is valid. Otherwise, return false. ", + "category": [ + "Array", + "Hash Table", + "Matrix" + ], + "complexity": "Easy", + "successrate": 52.2, + "totalsubmissions": 49781, + "totalaccepted": 25978, + "likes": 309, + "dislikes": 19, + "hints": "Use for loops to check each row for every number from 1 to n. Similarly, do the same for each column. For each check, you can keep a set of the unique elements in the checked row/col. By the end of the check, the size of the set should be n.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "matrix = [[1,2,3],[3,1,2],[2,3,1]]", + "expected_output": "true", + "explanation": "In this case, n = 3, and every row and column contains the numbers 1, 2, and 3.\nHence, we return true." + }, + { + "example_num": 2, + "expected_input": "matrix = [[1,1,1],[1,2,3],[1,2,3]]", + "expected_output": "false", + "explanation": "In this case, n = 3, but the first row and the first column do not contain the numbers 2 or 3.\nHence, we return false." + } + ], + "solution": "/**\n * @param {number[][]} matrix\n * @return {boolean}\n */\nvar checkValid = function(matrix) {\n const n = matrix.length\n let res = true\n for(let i = 0; i < n; i++) {\n if(!chkRow(i) || !chkCol(i)) {\n res = false\n break\n }\n }\n \n \n return res\n \n function chkRow(i) {\n const row = matrix[i], set = new Set()\n for(let i = 0; i < n; i++) {\n set.add(row[i])\n }\n return set.size === n\n }\n \n function chkCol(j) {\n const set = new Set()\n for(let i = 0; i < n; i++) {\n set.add(matrix[i][j])\n }\n \n return set.size === n\n }\n};\n" + }, + { + "_id": "66f925defdfb8e1665720ef0", + "questionid": 1061, + "title": "Count Elements With Strictly Smaller and Greater Elements ", + "slug": "count-elements-with-strictly-smaller-and-greater-elements", + "description": "Given an integer array nums, return the number of elements that have both a strictly smaller and a strictly greater element appear in nums. ", + "category": [ + "Array", + "Sorting" + ], + "complexity": "Easy", + "successrate": 60.5, + "totalsubmissions": 42268, + "totalaccepted": 25577, + "likes": 243, + "dislikes": 7, + "hints": "All the elements in the array should be counted except for the minimum and maximum elements. If the array has n elements, the answer will be n - count(min(nums)) - count(max(nums)) This formula will not work in case the array has all the elements equal, why?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [11,7,2,15]", + "expected_output": "2", + "explanation": "The element 7 has the element 2 strictly smaller than it and the element 11 strictly greater than it.\nElement 11 has element 7 strictly smaller than it and element 15 strictly greater than it.\nIn total there are 2 elements having both a strictly smaller and a strictly greater element appear in nums." + }, + { + "example_num": 2, + "expected_input": "nums = [-3,3,3,90]", + "expected_output": "2", + "explanation": "The element 3 has the element -3 strictly smaller than it and the element 90 strictly greater than it.\nSince there are two elements with the value 3, in total there are 2 elements having both a strictly smaller and a strictly greater element appear in nums." + } + ], + "solution": "/**\n * @param {number[]} nums\n * @return {number}\n */\nvar countElements = function(nums) {\n let min = Infinity, max = -Infinity\n for(let e of nums) {\n if(e > max) max = e\n if(e < min) min = e\n }\n let res = 0\n for(let e of nums) {\n if(e > min && e < max) res++\n }\n return res\n};\n" + }, + { + "_id": "66f925defdfb8e1665720ef5", + "questionid": 1066, + "title": "Smallest Value of the Rearranged Number", + "slug": "smallest-value-of-the-rearranged-number", + "description": "You are given an integer num. Rearrange the digits of num such that its value is minimized and it does not contain any leading zeros. Return the rearranged number with minimal value. Note that the sign of the number does not change after rearranging the digits. ", + "category": [ + "Math", + "Sorting" + ], + "complexity": "Medium", + "successrate": 50.7, + "totalsubmissions": 39260, + "totalaccepted": 19915, + "likes": 287, + "dislikes": 9, + "hints": "For positive numbers, the leading digit should be the smallest nonzero digit. Then the remaining digits follow in ascending order. For negative numbers, the digits should be arranged in descending order.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "num = 310", + "expected_output": "103", + "explanation": "The possible arrangements for the digits of 310 are 013, 031, 103, 130, 301, 310. \nThe arrangement with the smallest value that does not contain any leading zeros is 103." + }, + { + "example_num": 2, + "expected_input": "num = -7605", + "expected_output": "-7650", + "explanation": "Some possible arrangements for the digits of -7605 are -7650, -6705, -5076, -0567.\nThe arrangement with the smallest value that does not contain any leading zeros is -7650." + } + ], + "solution": "/**\n * @param {number} num\n * @return {number}\n */\nvar smallestNumber = function(num) {\n const minus = num < 0\n const nums = Math.abs(num)\n .toString()\n .split('')\n .map(_ => parseInt(_))\n .sort((a, b) => minus ? b-a : a-b);\n if(!minus && nums[0] === 0) {\n let i = 0\n while(nums[i] === 0 && i < nums.length-1) i++\n nums[0] = nums[i]\n nums[i] = 0\n }\n const answer = parseInt(nums.map(_ => _.toString()).join(''))\n return minus ? -answer : answer\n};\n" + }, + { + "_id": "66f925defdfb8e1665720ef6", + "questionid": 1067, + "title": "Count Operations to Obtain Zero", + "slug": "count-operations-to-obtain-zero", + "description": "You are given two non-negative integers num1 and num2. In one operation, if num1 >= num2, you must subtract num2 from num1, otherwise subtract num1 from num2. Return the number of operations required to make either num1 = 0 or num2 = 0. ", + "category": [ + "Math", + "Simulation" + ], + "complexity": "Easy", + "successrate": 75.3, + "totalsubmissions": 36407, + "totalaccepted": 27423, + "likes": 200, + "dislikes": 5, + "hints": "Try simulating the process until either of the two integers is zero. Count the number of operations done.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "num1 = 2, num2 = 3", + "expected_output": "3", + "explanation": "- Operation 1: num1 = 2, num2 = 3. Since num1 < num2, we subtract num1 from num2 and get num1 = 2, num2 = 3 - 2 = 1.\n- Operation 2: num1 = 2, num2 = 1. Since num1 > num2, we subtract num2 from num1.\n- Operation 3: num1 = 1, num2 = 1. Since num1 == num2, we subtract num2 from num1.\nNow num1 = 0 and num2 = 1. Since num1 == 0, we do not need to perform any further operations.\nSo the total number of operations required is 3." + }, + { + "example_num": 2, + "expected_input": "num1 = 10, num2 = 10", + "expected_output": "1", + "explanation": "- Operation 1: num1 = 10, num2 = 10. Since num1 == num2, we subtract num2 from num1 and get num1 = 10 - 10 = 0.\nNow num1 = 0 and num2 = 10. Since num1 == 0, we are done.\nSo the total number of operations required is 1." + } + ], + "solution": "/**\n * @param {number} num1\n * @param {number} num2\n * @return {number}\n */\nvar countOperations = function(num1, num2) {\n let res = 0\n while(num1 !== 0 && num2 !== 0) {\n if(num1 >= num2) num1 -= num2\n else num2 -= num1\n res++\n }\n return res\n};\n" + }, + { + "_id": "66f925defdfb8e1665720ef7", + "questionid": 1068, + "title": "Removing Minimum Number of Magic Beans", + "slug": "removing-minimum-number-of-magic-beans", + "description": "You are given an array of positive integers beans, where each integer represents the number of magic beans found in a particular magic bag. Remove any number of beans (possibly none) from each bag such that the number of beans in each remaining non-empty bag (still containing at least one bean) is equal. Once a bean has been removed from a bag, you are not allowed to return it to any of the bags. Return the minimum number of magic beans that you have to remove. ", + "category": [ + "Array", + "Sorting", + "Prefix Sum" + ], + "complexity": "Medium", + "successrate": 40.9, + "totalsubmissions": 34492, + "totalaccepted": 14124, + "likes": 456, + "dislikes": 26, + "hints": "Notice that if we choose to make x bags of beans empty, we should choose the x bags with the least amount of beans. Notice that if the minimum number of beans in a non-empty bag is m, then the best way to make all bags have an equal amount of beans is to reduce all the bags to have m beans. Can we iterate over how many bags we should remove and choose the one that minimizes the total amount of beans to remove? Sort the bags of beans first.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "beans = [4,1,6,5]", + "expected_output": "4", + "explanation": "- We remove 1 bean from the bag with only 1 bean.\n This results in the remaining bags: [4,0,6,5]\n- Then we remove 2 beans from the bag with 6 beans.\n This results in the remaining bags: [4,0,4,5]\n- Then we remove 1 bean from the bag with 5 beans.\n This results in the remaining bags: [4,0,4,4]\nWe removed a total of 1 + 2 + 1 = 4 beans to make the remaining non-empty bags have an equal number of beans.\nThere are no other solutions that remove 4 beans or fewer." + }, + { + "example_num": 2, + "expected_input": "beans = [2,10,3,2]", + "expected_output": "7", + "explanation": "- We remove 2 beans from one of the bags with 2 beans.\n This results in the remaining bags: [0,10,3,2]\n- Then we remove 2 beans from the other bag with 2 beans.\n This results in the remaining bags: [0,10,3,0]\n- Then we remove 3 beans from the bag with 3 beans. \n This results in the remaining bags: [0,10,0,0]\nWe removed a total of 2 + 2 + 3 = 7 beans to make the remaining non-empty bags have an equal number of beans.\nThere are no other solutions that removes 7 beans or fewer." + } + ], + "solution": null + }, + { + "_id": "66f925defdfb8e1665720efc", + "questionid": 1073, + "title": "Minimum Time to Finish the Race", + "slug": "minimum-time-to-finish-the-race", + "description": "You are given a 0-indexed 2D integer array tires where tires[i] = [fi, ri] indicates that the ith tire can finish its xth successive lap in fi * ri(x-1) seconds. You are also given an integer changeTime and an integer numLaps. The race consists of numLaps laps and you may start the race with any tire. You have an unlimited supply of each tire and after every lap, you may change to any given tire (including the current tire type) if you wait changeTime seconds. Return the minimum time to finish the race. ", + "category": [ + "Array", + "Dynamic Programming" + ], + "complexity": "Hard", + "successrate": 40.4, + "totalsubmissions": 14102, + "totalaccepted": 5697, + "likes": 315, + "dislikes": 9, + "hints": "What is the maximum number of times we would want to go around the track without changing tires? Can we precompute the minimum time to go around the track x times without changing tires? Can we use dynamic programming to solve this efficiently using the precomputed values?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "tires = [[2,3],[3,4]], changeTime = 5, numLaps = 4", + "expected_output": "21", + "explanation": "Lap 1: Start with tire 0 and finish the lap in 2 seconds.\nLap 2: Continue with tire 0 and finish the lap in 2 * 3 = 6 seconds.\nLap 3: Change tires to a new tire 0 for 5 seconds and then finish the lap in another 2 seconds.\nLap 4: Continue with tire 0 and finish the lap in 2 * 3 = 6 seconds.\nTotal time = 2 + 6 + 5 + 2 + 6 = 21 seconds.\nThe minimum time to complete the race is 21 seconds." + }, + { + "example_num": 2, + "expected_input": "tires = [[1,10],[2,2],[3,4]], changeTime = 6, numLaps = 5", + "expected_output": "25", + "explanation": "Lap 1: Start with tire 1 and finish the lap in 2 seconds.\nLap 2: Continue with tire 1 and finish the lap in 2 * 2 = 4 seconds.\nLap 3: Change tires to a new tire 1 for 6 seconds and then finish the lap in another 2 seconds.\nLap 4: Continue with tire 1 and finish the lap in 2 * 2 = 4 seconds.\nLap 5: Change tires to tire 0 for 6 seconds then finish the lap in another 1 second.\nTotal time = 2 + 4 + 6 + 2 + 4 + 6 + 1 = 25 seconds.\nThe minimum time to complete the race is 25 seconds." + } + ], + "solution": "/**\n * @param {number[][]} tires\n * @param {number} changeTime\n * @param {number} numLaps\n * @return {number}\n */\n const minimumFinishTime = function (tires, changeTime, numLaps) {\n tires = preprocess(tires)\n let n = tires.length\n const { max, min } = Math\n // to handle the cases where numLaps is small\n // pre[i][j]: the total time to run j laps consecutively with tire i\n const pre = Array.from({ length: n }, () =>\n Array(20).fill(Infinity)\n )\n for (let i = 0; i < n; i++) {\n pre[i][1] = tires[i][0]\n for (let j = 2; j < 20; j++) {\n if (pre[i][j - 1] * tires[i][1] >= 2e9) break\n pre[i][j] = pre[i][j - 1] * tires[i][1]\n }\n // since we define it as the total time, rather than just the time for the j-th lap\n // we have to make it prefix sum\n for (let j = 2; j < 20; j++) {\n if (pre[i][j - 1] + pre[i][j] >= 2e9) break\n pre[i][j] += pre[i][j - 1]\n }\n }\n\n // dp[x]: the minimum time to finish x laps\n const dp = Array(numLaps + 1).fill(Infinity)\n for (let i = 0; i < n; i++) {\n dp[1] = min(dp[1], tires[i][0])\n }\n for (let x = 1; x <= numLaps; x++) {\n if (x < 20) {\n // x is small enough, so an optimal solution might never changes tires!\n for (let i = 0; i < n; i++) {\n dp[x] = min(dp[x], pre[i][x])\n }\n }\n for (let j = x - 1; j > 0 && j >= x - 18; j--) {\n dp[x] = min(dp[x], dp[j] + changeTime + dp[x - j])\n }\n }\n\n return dp[numLaps]\n}\n\nfunction preprocess(tires) {\n tires.sort((a, b) => (a[0] === b[0] ? a[1] - b[1] : a[0] - b[0]))\n const res = []\n for (let t of tires) {\n if (res.length === 0 || res[res.length - 1][1] > t[1]) {\n res.push(t)\n }\n }\n return res\n}\n\n// another\n\n/**\n * @param {number[][]} tires\n * @param {number} changeTime\n * @param {number} numLaps\n * @return {number}\n */\nvar minimumFinishTime = function (tires, changeTime, numLaps) {\n let N = tires.length,\n len = 0\n const { max, min } = Math\n const best = Array(numLaps).fill(Infinity),\n dp = Array(numLaps + 1).fill(Infinity)\n for (let i = 0; i < N; ++i) {\n // We assume we also need `changeTime` time to use the first tire\n // so that we don't need to treat the first tire as a special case\n let f = tires[i][0],\n r = tires[i][1],\n sum = changeTime,\n p = 1\n for (let j = 0; j < numLaps; ++j) {\n sum += f * p\n // If using the same tire takes no less time than changing the tire,\n // stop further using the current tire\n if (f * p >= f + changeTime) break \n best[j] = min(best[j], sum)\n len = max(len, j + 1)\n p *= r\n }\n }\n // dp[i + 1] is the minimum time to finish `numLaps` laps\n dp[0] = 0 \n for (let i = 0; i < numLaps; ++i) {\n for (let j = 0; j < len && i - j >= 0; ++j) {\n // try using the same tire in the last `j+1` laps\n dp[i + 1] = min(dp[i + 1], dp[i - j] + best[j])\n }\n }\n // minus the `changeTime` we added to the first tire\n return dp[numLaps] - changeTime \n}\n\n" + }, + { + "_id": "66f925defdfb8e1665720efd", + "questionid": 1074, + "title": "Count Integers With Even Digit Sum", + "slug": "count-integers-with-even-digit-sum", + "description": "Given a positive integer num, return the number of positive integers less than or equal to num whose digit sums are even. The digit sum of a positive integer is the sum of all its digits. ", + "category": [ + "Math", + "Simulation" + ], + "complexity": "Easy", + "successrate": 64.8, + "totalsubmissions": 36506, + "totalaccepted": 23649, + "likes": 220, + "dislikes": 12, + "hints": "Iterate through all integers from 1 to num. For any integer, extract the individual digits to compute their sum and check if it is even.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "num = 4", + "expected_output": "2", + "explanation": "The only integers less than or equal to 4 whose digit sums are even are 2 and 4." + }, + { + "example_num": 2, + "expected_input": "num = 30", + "expected_output": "14", + "explanation": "The 14 integers less than or equal to 30 whose digit sums are even are\n2, 4, 6, 8, 11, 13, 15, 17, 19, 20, 22, 24, 26, and 28." + } + ], + "solution": "/**\n * @param {number} num\n * @return {number}\n */\nvar countEven = function(num) {\n let res = 0\n for(let i = 1; i <= num; i++) {\n const tmp = sum(i)\n if(tmp % 2 === 0) res++\n }\n \n return res\n};\n\nfunction sum(e) {\n let res = 0\n while(e) {\n res += e % 10\n e = Math.floor(e/10)\n }\n return res\n}\n" + }, + { + "_id": "66f925defdfb8e1665720f00", + "questionid": 1077, + "title": "Append K Integers With Minimal Sum", + "slug": "append-k-integers-with-minimal-sum", + "description": "You are given an integer array nums and an integer k. Append k unique positive integers that do not appear in nums to nums such that the resulting total sum is minimum. Return the sum of the k integers appended to nums. ", + "category": [ + "Array", + "Math", + "Greedy", + "Sorting" + ], + "complexity": "Medium", + "successrate": 22.9, + "totalsubmissions": 66897, + "totalaccepted": 15315, + "likes": 316, + "dislikes": 223, + "hints": "The k smallest numbers that do not appear in nums will result in the minimum sum. Recall that the sum of the first n positive numbers is equal to n * (n+1) / 2. Initialize the answer as the sum of 1 to k. Then, adjust the answer depending on the values in nums.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,4,25,10,25], k = 2", + "expected_output": "5", + "explanation": "The two unique positive integers that do not appear in nums which we append are 2 and 3.\nThe resulting sum of nums is 1 + 4 + 25 + 10 + 25 + 2 + 3 = 70, which is the minimum.\nThe sum of the two integers appended is 2 + 3 = 5, so we return 5." + }, + { + "example_num": 2, + "expected_input": "nums = [5,6], k = 6", + "expected_output": "25", + "explanation": "The six unique positive integers that do not appear in nums which we append are 1, 2, 3, 4, 7, and 8.\nThe resulting sum of nums is 5 + 6 + 1 + 2 + 3 + 4 + 7 + 8 = 36, which is the minimum. \nThe sum of the six integers appended is 1 + 2 + 3 + 4 + 7 + 8 = 25, so we return 25." + } + ], + "solution": null + }, + { + "_id": "66f925defdfb8e1665720f02", + "questionid": 1079, + "title": "Maximize Number of Subsequences in a String", + "slug": "maximize-number-of-subsequences-in-a-string", + "description": "You are given a 0-indexed string text and another 0-indexed string pattern of length 2, both of which consist of only lowercase English letters. You can add either pattern[0] or pattern[1] anywhere in text exactly once. Note that the character can be added even at the beginning or at the end of text. Return the maximum number of times pattern can occur as a subsequence of the modified text. A subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters. ", + "category": [ + "String", + "Greedy", + "Prefix Sum" + ], + "complexity": "Medium", + "successrate": 30.7, + "totalsubmissions": 33828, + "totalaccepted": 10383, + "likes": 215, + "dislikes": 12, + "hints": "Find the optimal position to add pattern[0] so that the number of subsequences is maximized. Similarly, find the optimal position to add pattern[1]. For each of the above cases, count the number of times the pattern occurs as a subsequence in text. The larger count is the required answer.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "text = "abdcdbc", pattern = "ac"", + "expected_output": "4", + "explanation": "If we add pattern[0] = 'a' in between text[1] and text[2], we get "abadcdbc". Now, the number of times "ac" occurs as a subsequence is 4.\nSome other strings which have 4 subsequences "ac" after adding a character to text are "aabdcdbc" and "abdacdbc".\nHowever, strings such as "abdcadbc", "abdccdbc", and "abdcdbcc", although obtainable, have only 3 subsequences "ac" and are thus suboptimal.\nIt can be shown that it is not possible to get more than 4 subsequences "ac" by adding only one character." + }, + { + "example_num": 2, + "expected_input": "text = "aabb", pattern = "ab"", + "expected_output": "6", + "explanation": "Some of the strings which can be obtained from text and have 6 subsequences "ab" are "aaabb", "aaabb", and "aabbb"." + } + ], + "solution": null + }, + { + "_id": "66f925defdfb8e1665720f04", + "questionid": 1081, + "title": "Count Hills and Valleys in an Array", + "slug": "count-hills-and-valleys-in-an-array", + "description": "You are given a 0-indexed integer array nums. An index i is part of a hill in nums if the closest non-equal neighbors of i are smaller than nums[i]. Similarly, an index i is part of a valley in nums if the closest non-equal neighbors of i are larger than nums[i]. Adjacent indices i and j are part of the same hill or valley if nums[i] == nums[j]. Note that for an index to be part of a hill or valley, it must have a non-equal neighbor on both the left and right of the index. Return the number of hills and valleys in nums. ", + "category": [ + "Array" + ], + "complexity": "Easy", + "successrate": 56.3, + "totalsubmissions": 30741, + "totalaccepted": 17316, + "likes": 184, + "dislikes": 44, + "hints": "For each index, could you find the closest non-equal neighbors? Ensure that adjacent indices that are part of the same hill or valley are not double-counted.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [2,4,1,1,6,5]", + "expected_output": "3", + "explanation": "At index 0: There is no non-equal neighbor of 2 on the left, so index 0 is neither a hill nor a valley.\nAt index 1: The closest non-equal neighbors of 4 are 2 and 1. Since 4 > 2 and 4 > 1, index 1 is a hill. \nAt index 2: The closest non-equal neighbors of 1 are 4 and 6. Since 1 < 4 and 1 < 6, index 2 is a valley.\nAt index 3: The closest non-equal neighbors of 1 are 4 and 6. Since 1 < 4 and 1 < 6, index 3 is a valley, but note that it is part of the same valley as index 2.\nAt index 4: The closest non-equal neighbors of 6 are 1 and 5. Since 6 > 1 and 6 > 5, index 4 is a hill.\nAt index 5: There is no non-equal neighbor of 5 on the right, so index 5 is neither a hill nor a valley. \nThere are 3 hills and valleys so we return 3." + }, + { + "example_num": 2, + "expected_input": "nums = [6,6,5,5,4,1]", + "expected_output": "0", + "explanation": "At index 0: There is no non-equal neighbor of 6 on the left, so index 0 is neither a hill nor a valley.\nAt index 1: There is no non-equal neighbor of 6 on the left, so index 1 is neither a hill nor a valley.\nAt index 2: The closest non-equal neighbors of 5 are 6 and 4. Since 5 < 6 and 5 > 4, index 2 is neither a hill nor a valley.\nAt index 3: The closest non-equal neighbors of 5 are 6 and 4. Since 5 < 6 and 5 > 4, index 3 is neither a hill nor a valley.\nAt index 4: The closest non-equal neighbors of 4 are 5 and 1. Since 4 < 5 and 4 > 1, index 4 is neither a hill nor a valley.\nAt index 5: There is no non-equal neighbor of 1 on the right, so index 5 is neither a hill nor a valley.\nThere are 0 hills and valleys so we return 0." + } + ], + "solution": "/**\n * @param {number[]} nums\n * @return {number}\n */\nconst countHillValley = function(nums) {\n const arr = [nums[0]], n = nums.length\n for(let i = 1; i < n; i++) {\n if(nums[i] !== nums[i - 1]) arr.push(nums[i])\n }\n let res = 0\n for(let i = 1; i < arr.length - 1; i++) {\n if(\n arr[i] > arr[i - 1] && arr[i] > arr[i + 1] ||\n arr[i] < arr[i - 1] && arr[i] < arr[i + 1]\n ) res++\n }\n \n return res\n};\n" + }, + { + "_id": "66f925defdfb8e1665720f09", + "questionid": 1086, + "title": "Sum of Scores of Built Strings", + "slug": "sum-of-scores-of-built-strings", + "description": "You are building a string s of length n one character at a time, prepending each new character to the front of the string. The strings are labeled from 1 to n, where the string with length i is labeled si. The score of si is the length of the longest common prefix between si and sn (Note that s == sn). Given the final string s, return the sum of the score of every si. ", + "category": [ + "String", + "Binary Search", + "Rolling Hash", + "Suffix Array", + "String Matching", + "Hash Function" + ], + "complexity": "Hard", + "successrate": 32.9, + "totalsubmissions": 9479, + "totalaccepted": 3120, + "likes": 110, + "dislikes": 146, + "hints": "Each s_i is a suffix of the string s, so consider algorithms that can determine the longest prefix that is also a suffix. Could you use the Z array from the Z algorithm to find the score of each s_i?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "babab"", + "expected_output": "9", + "explanation": "For s1 == "b", the longest common prefix is "b" which has a score of 1.\nFor s2 == "ab", there is no common prefix so the score is 0.\nFor s3 == "bab", the longest common prefix is "bab" which has a score of 3.\nFor s4 == "abab", there is no common prefix so the score is 0.\nFor s5 == "babab", the longest common prefix is "babab" which has a score of 5.\nThe sum of the scores is 1 + 0 + 3 + 0 + 5 = 9, so we return 9." + }, + { + "example_num": 2, + "expected_input": "s = "azbazbzaz"", + "expected_output": "14", + "explanation": "For s2 == "az", the longest common prefix is "az" which has a score of 2.\nFor s6 == "azbzaz", the longest common prefix is "azb" which has a score of 3.\nFor s9 == "azbazbzaz", the longest common prefix is "azbazbzaz" which has a score of 9.\nFor all other si, the score is 0.\nThe sum of the scores is 2 + 3 + 9 = 14, so we return 14." + } + ], + "solution": "/**\n * @param {string} s\n * @return {number}\n */\nvar sumScores = function(s) {\n function z_function(s) {\n let n = s.length\n let z = Array(n).fill(0)\n let l = 0, r = 0\n for (let i = 1; i < n; i++) {\n if (i <= r) z[i] = Math.min(r - i + 1, z[i - l])\n while (i + z[i] < n && s[z[i]] == s[i + z[i]]) {\n z[i] += 1 \n }\n\n if (i + z[i] - 1 > r) {\n l = i\n r = i + z[i] - 1 \n }\n\n }\n return z \n }\n\n const sum = z_function(s).reduce((ac, e) => ac + e, 0)\n return sum + s.length \n};\n \n" + }, + { + "_id": "66f925defdfb8e1665720f0a", + "questionid": 1087, + "title": "Largest Number After Digit Swaps by Parity", + "slug": "largest-number-after-digit-swaps-by-parity", + "description": "You are given a positive integer num. You may swap any two digits of num that have the same parity (i.e. both odd digits or both even digits). Return the largest possible value of num after any number of swaps. ", + "category": [ + "Sorting", + "Heap (Priority Queue)" + ], + "complexity": "Easy", + "successrate": 56.4, + "totalsubmissions": 27114, + "totalaccepted": 15301, + "likes": 134, + "dislikes": 139, + "hints": "The bigger digit should appear first (more to the left) because it contributes more to the value of the number. Get all the even digits, as well as odd digits. Sort them separately. Reconstruct the number by giving the earlier digits the highest available digit of the same parity.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "num = 1234", + "expected_output": "3412", + "explanation": "Swap the digit 3 with the digit 1, this results in the number 3214.\nSwap the digit 2 with the digit 4, this results in the number 3412.\nNote that there may be other sequences of swaps but it can be shown that 3412 is the largest possible number.\nAlso note that we may not swap the digit 4 with the digit 1 since they are of different parities." + }, + { + "example_num": 2, + "expected_input": "num = 65875", + "expected_output": "87655", + "explanation": "Swap the digit 8 with the digit 6, this results in the number 85675.\nSwap the first digit 5 with the digit 7, this results in the number 87655.\nNote that there may be other sequences of swaps but it can be shown that 87655 is the largest possible number." + } + ], + "solution": null + }, + { + "_id": "66f925defdfb8e1665720eb8", + "questionid": 1005, + "title": "Maximum Difference Between Increasing Elements", + "slug": "maximum-difference-between-increasing-elements", + "description": "Given a 0-indexed integer array nums of size n, find the maximum difference between nums[i] and nums[j] (i.e., nums[j] - nums[i]), such that 0 <= i < j < n and nums[i] < nums[j]. Return the maximum difference. If no such i and j exists, return -1. ", + "category": [ + "Array" + ], + "complexity": "Easy", + "successrate": 54.6, + "totalsubmissions": 54942, + "totalaccepted": 30006, + "likes": 368, + "dislikes": 15, + "hints": "Could you keep track of the minimum element visited while traversing? We have a potential candidate for the answer if the prefix min is lesser than nums[i].", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [7,1,5,4]", + "expected_output": "4", + "explanation": "The maximum difference occurs with i = 1 and j = 2, nums[j] - nums[i] = 5 - 1 = 4.\nNote that with i = 1 and j = 0, the difference nums[j] - nums[i] = 7 - 1 = 6, but i > j, so it is not valid." + }, + { + "example_num": 2, + "expected_input": "nums = [9,4,3,2]", + "expected_output": "-1", + "explanation": "There is no i and j such that i < j and nums[i] < nums[j]." + }, + { + "example_num": 3, + "expected_input": "nums = [1,5,2,10]", + "expected_output": "9", + "explanation": "The maximum difference occurs with i = 0 and j = 3, nums[j] - nums[i] = 10 - 1 = 9." + } + ], + "solution": null + }, + { + "_id": "66f925defdfb8e1665720ebb", + "questionid": 1008, + "title": "Minimum Moves to Convert String", + "slug": "minimum-moves-to-convert-string", + "description": "You are given a string s consisting of n characters which are either 'X' or 'O'. A move is defined as selecting three consecutive characters of s and converting them to 'O'. Note that if a move is applied to the character 'O', it will stay the same. Return the minimum number of moves required so that all the characters of s are converted to 'O'. ", + "category": [ + "String", + "Greedy" + ], + "complexity": "Easy", + "successrate": 53.4, + "totalsubmissions": 33422, + "totalaccepted": 17856, + "likes": 198, + "dislikes": 46, + "hints": "Find the smallest substring you need to consider at a time. Try delaying a move as long as possible.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "XXX"", + "expected_output": "1", + "explanation": "XXX -> OOO\nWe select all the 3 characters and convert them in one move." + }, + { + "example_num": 2, + "expected_input": "s = "XXOX"", + "expected_output": "2", + "explanation": "XXOX -> OOOX -> OOOO\nWe select the first 3 characters in the first move, and convert them to 'O'.\nThen we select the last 3 characters and convert them so that the final string contains all 'O's." + }, + { + "example_num": 3, + "expected_input": "s = "OOOO"", + "expected_output": "0", + "explanation": "There are no 'X's in s to convert." + } + ], + "solution": null + }, + { + "_id": "66f925defdfb8e1665720ebc", + "questionid": 1009, + "title": "Find Missing Observations", + "slug": "find-missing-observations", + "description": "You have observations of n + m 6-sided dice rolls with each face numbered from 1 to 6. n of the observations went missing, and you only have the observations of m rolls. Fortunately, you have also calculated the average value of the n + m rolls. You are given an integer array rolls of length m where rolls[i] is the value of the ith observation. You are also given the two integers mean and n. Return an array of length n containing the missing observations such that the average value of the n + m rolls is exactly mean. If there are multiple valid answers, return any of them. If no such array exists, return an empty array. The average value of a set of k numbers is the sum of the numbers divided by k. Note that mean is an integer, so the sum of the n + m rolls should be divisible by n + m. ", + "category": [ + "Array", + "Math", + "Simulation" + ], + "complexity": "Medium", + "successrate": 41.9, + "totalsubmissions": 30688, + "totalaccepted": 12857, + "likes": 211, + "dislikes": 10, + "hints": "What should the sum of the n rolls be? Could you generate an array of size n such that each element is between 1 and 6?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "rolls = [3,2,4,3], mean = 4, n = 2", + "expected_output": "[6,6]", + "explanation": "The mean of all n + m rolls is (3 + 2 + 4 + 3 + 6 + 6) / 6 = 4." + }, + { + "example_num": 2, + "expected_input": "rolls = [1,5,6], mean = 3, n = 4", + "expected_output": "[2,3,2,2]", + "explanation": "The mean of all n + m rolls is (1 + 5 + 6 + 2 + 3 + 2 + 2) / 7 = 3." + }, + { + "example_num": 3, + "expected_input": "rolls = [1,2,3,4], mean = 6, n = 4", + "expected_output": "[]", + "explanation": "It is impossible for the mean to be 6 no matter what the 4 missing rolls are." + } + ], + "solution": null + }, + { + "_id": "66f925defdfb8e1665720eca", + "questionid": 1023, + "title": "Smallest Index With Equal Value", + "slug": "smallest-index-with-equal-value", + "description": "Given a 0-indexed integer array nums, return the smallest index i of nums such that i mod 10 == nums[i], or -1 if such index does not exist. x mod y denotes the remainder when x is divided by y. ", + "category": [ + "Array" + ], + "complexity": "Easy", + "successrate": 73.2, + "totalsubmissions": 32095, + "totalaccepted": 23484, + "likes": 144, + "dislikes": 67, + "hints": "Starting with i=0, check the condition for each index. The first one you find to be true is the smallest index.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [0,1,2]", + "expected_output": "0", + "explanation": "i=0: 0 mod 10 = 0 == nums[0].\ni=1: 1 mod 10 = 1 == nums[1].\ni=2: 2 mod 10 = 2 == nums[2].\nAll indices have i mod 10 == nums[i], so we return the smallest index 0." + }, + { + "example_num": 2, + "expected_input": "nums = [4,3,2,1]", + "expected_output": "2", + "explanation": "i=0: 0 mod 10 = 0 != nums[0].\ni=1: 1 mod 10 = 1 != nums[1].\ni=2: 2 mod 10 = 2 == nums[2].\ni=3: 3 mod 10 = 3 != nums[3].\n2 is the only index which has i mod 10 == nums[i]." + }, + { + "example_num": 3, + "expected_input": "nums = [1,2,3,4,5,6,7,8,9,0]", + "expected_output": "-1", + "explanation": "No index satisfies i mod 10 == nums[i]." + } + ], + "solution": "/**\n * @param {number[]} nums\n * @return {number}\n */\nvar smallestEqual = function(nums) {\n const n = nums.length\n for(let i = 0; i < n; i++) {\n if(i % 10 === nums[i]) return i\n }\n return -1\n};\n" + }, + { + "_id": "66f925defdfb8e1665720ed4", + "questionid": 1033, + "title": "Detonate the Maximum Bombs", + "slug": "detonate-the-maximum-bombs", + "description": "You are given a list of bombs. The range of a bomb is defined as the area where its effect can be felt. This area is in the shape of a circle with the center as the location of the bomb. The bombs are represented by a 0-indexed 2D integer array bombs where bombs[i] = [xi, yi, ri]. xi and yi denote the X-coordinate and Y-coordinate of the location of the ith bomb, whereas ri denotes the radius of its range. You may choose to detonate a single bomb. When a bomb is detonated, it will detonate all bombs that lie in its range. These bombs will further detonate the bombs that lie in their ranges. Given the list of bombs, return the maximum number of bombs that can be detonated if you are allowed to detonate only one bomb. ", + "category": [ + "Array", + "Math", + "Depth-First Search", + "Breadth-First Search", + "Graph", + "Geometry" + ], + "complexity": "Medium", + "successrate": 39.9, + "totalsubmissions": 25051, + "totalaccepted": 9999, + "likes": 374, + "dislikes": 42, + "hints": "How can we model the relationship between different bombs? Can \"graphs\" help us? Bombs are nodes and are connected to other bombs in their range by directed edges. If we know which bombs will be affected when any bomb is detonated, how can we find the total number of bombs that will be detonated if we start from a fixed bomb? Run a Depth First Search (DFS) from every node, and all the nodes it reaches are the bombs that will be detonated.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "bombs = [[2,1,3],[6,1,4]]", + "expected_output": "2", + "explanation": "The above figure shows the positions and ranges of the 2 bombs.\nIf we detonate the left bomb, the right bomb will not be affected.\nBut if we detonate the right bomb, both bombs will be detonated.\nSo the maximum bombs that can be detonated is max(1, 2) = 2." + }, + { + "example_num": 2, + "expected_input": "bombs = [[1,1,5],[10,10,5]]", + "expected_output": "1\nExplanation:\nDetonating either bomb will not detonate the other bomb, so the maximum number of bombs that can be detonated is 1.", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "bombs = [[1,2,3],[2,3,1],[3,4,2],[4,5,3],[5,6,4]]", + "expected_output": "5", + "explanation": "The best bomb to detonate is bomb 0 because:\n- Bomb 0 detonates bombs 1 and 2. The red circle denotes the range of bomb 0.\n- Bomb 2 detonates bomb 3. The blue circle denotes the range of bomb 2.\n- Bomb 3 detonates bomb 4. The green circle denotes the range of bomb 3.\nThus all 5 bombs are detonated." + } + ], + "solution": "/**\n * @param {number[][]} bombs\n * @return {number}\n */\n const maximumDetonation = function(bombs) {\n let n = bombs.length, res = 1, graph = {}\n for(let i = 0; i < n; i++) {\n for(let j = 0; j < n; j++) {\n if (i === j) continue\n if (bombAdj(bombs[i], bombs[j])) {\n if (graph[i] == null) graph[i] = []\n graph[i].push(j)\n }\n }\n }\n function dfs(node, visited) {\n for(const next of (graph[node] || [])) {\n if(!visited.has(next)) {\n visited.add(next)\n dfs(next, visited)\n }\n }\n }\n for (let i = 0; i < n; i++) {\n const set = new Set([i])\n dfs(i, set)\n res = Math.max(res, set.size)\n }\n\n return res\n};\n\nfunction bombAdj(source, target) {\n const [x1, y1, r1] = source\n const [x2, y2] = target\n const { abs } = Math\n return abs(x1 - x2) ** 2 + abs(y1 - y2) ** 2 <= r1 ** 2\n}\n\n// another\n\n/**\n * @param {number[][]} bombs\n * @return {number}\n */\nconst maximumDetonation = function(bombs) {\n const n = bombs.length, graph = {}\n for(let i = 0; i < n; i++) {\n for(let j = 0; j < n; j++) {\n if(i === j) continue\n if(adjValid(bombs[i], bombs[j])) {\n if(graph[i] == null) graph[i] = []\n graph[i].push(j)\n }\n }\n }\n \n let res = 0\n for(let i = 0; i < n; i++) {\n const set = new Set([i])\n dfs(i, set)\n res = Math.max(res, set.size)\n }\n return res\n \n function dfs(node, visited){\n for (const e of (graph[node] || [])) {\n if(!visited.has(e)) {\n visited.add(e)\n dfs(e, visited)\n }\n }\n }\n \n function adjValid(start, target) {\n const [sx, sy, r] = start\n const [ex, ey] = target\n return Math.abs(sx - ex) ** 2 + Math.abs(sy - ey) ** 2 <= r ** 2\n }\n};\n\n\n" + }, + { + "_id": "66f925defdfb8e1665720eda", + "questionid": 1039, + "title": "Maximum Number of Words Found in Sentences", + "slug": "maximum-number-of-words-found-in-sentences", + "description": "A sentence is a list of words that are separated by a single space\u00a0with no leading or trailing spaces. You are given an array of strings sentences, where each sentences[i] represents a single sentence. Return the maximum number of words that appear in a single sentence. ", + "category": [ + "Array", + "String" + ], + "complexity": "Easy", + "successrate": 89, + "totalsubmissions": 68223, + "totalaccepted": 60728, + "likes": 485, + "dislikes": 17, + "hints": "Process each sentence separately and count the number of words by looking for the number of space characters in the sentence and adding it by 1.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "sentences = ["alice and bob love leetcode", "i think so too", "this is great thanks very much"]", + "expected_output": "6", + "explanation": "- The first sentence, "alice and bob love leetcode", has 5 words in total.\n- The second sentence, "i think so too", has 4 words in total.\n- The third sentence, "this is great thanks very much", has 6 words in total.\nThus, the maximum number of words in a single sentence comes from the third sentence, which has 6 words." + }, + { + "example_num": 2, + "expected_input": "sentences = ["please wait", "continue to fight", "continue to win"]", + "expected_output": "3", + "explanation": "It is possible that multiple sentences contain the same number of words. \nIn this example, the second and third sentences (underlined) have the same number of words." + } + ], + "solution": null + }, + { + "_id": "66f925defdfb8e1665720ee0", + "questionid": 1045, + "title": "Number of Smooth Descent Periods of a Stock", + "slug": "number-of-smooth-descent-periods-of-a-stock", + "description": "You are given an integer array prices representing the daily price history of a stock, where prices[i] is the stock price on the ith day. A smooth descent period of a stock consists of one or more contiguous days such that the price on each day is lower than the price on the preceding day by exactly 1. The first day of the period is exempted from this rule. Return the number of smooth descent periods. ", + "category": [ + "Array", + "Math", + "Dynamic Programming" + ], + "complexity": "Medium", + "successrate": 55.3, + "totalsubmissions": 32528, + "totalaccepted": 17988, + "likes": 326, + "dislikes": 12, + "hints": "Any array is a series of adjacent longest possible smooth descent periods. For example, [5,3,2,1,7,6] is [5] + [3,2,1] + [7,6]. Think of a 2-pointer approach to traverse the array and find each longest possible period. Suppose you found the longest possible period with a length of k. How many periods are within that period? How can you count them quickly? Think of the formula to calculate the sum of 1, 2, 3, ..., k.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "prices = [3,2,1,4]", + "expected_output": "7", + "explanation": "There are 7 smooth descent periods:\n[3], [2], [1], [4], [3,2], [2,1], and [3,2,1]\nNote that a period with one day is a smooth descent period by the definition." + }, + { + "example_num": 2, + "expected_input": "prices = [8,6,7,7]", + "expected_output": "4", + "explanation": "There are 4 smooth descent periods: [8], [6], [7], and [7]\nNote that [8,6] is not a smooth descent period as 8 - 6 ≠ 1." + }, + { + "example_num": 3, + "expected_input": "prices = [1]", + "expected_output": "1", + "explanation": "There is 1 smooth descent period: [1]" + } + ], + "solution": "/**\n * @param {number[]} prices\n * @return {number}\n */\nconst getDescentPeriods = function(prices) {\n if(prices.length === 1) return 1\n let res = 0, idx = 0\n \n for (let i = 1, n = prices.length; i < n ; i++) {\n if(prices[i - 1] - prices[i] === 1) {\n if (i === n - 1) {\n const len = i - idx + 1\n res += (len + 1) * len / 2\n }\n } else {\n const len = i - 1 - idx + 1\n res += (len + 1) * len / 2\n idx = i\n if(i === n - 1) {\n res += 1\n }\n }\n\n }\n \n return res\n};\n" + }, + { + "_id": "66f925defdfb8e1665720ee5", + "questionid": 1050, + "title": "Check if All A's Appears Before All B's", + "slug": "check-if-all-as-appears-before-all-bs", + "description": "Given a string s consisting of only the characters 'a' and 'b', return true if every 'a' appears before every 'b' in the string. Otherwise, return false. ", + "category": [ + "String" + ], + "complexity": "Easy", + "successrate": 72.5, + "totalsubmissions": 38380, + "totalaccepted": 27813, + "likes": 283, + "dislikes": 3, + "hints": "You can check the opposite: check if there is a \u20ac\u02dcb\u20ac\u2122 before an \u20ac\u02dca\u20ac\u2122. Then, negate and return that answer. s should not have any occurrences of \u20ac\u0153ba\u20ac\u009d as a substring.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "aaabbb"", + "expected_output": "true", + "explanation": "The 'a's are at indices 0, 1, and 2, while the 'b's are at indices 3, 4, and 5.\nHence, every 'a' appears before every 'b' and we return true." + }, + { + "example_num": 2, + "expected_input": "s = "abab"", + "expected_output": "false", + "explanation": "There is an 'a' at index 2 and a 'b' at index 1.\nHence, not every 'a' appears before every 'b' and we return false." + }, + { + "example_num": 3, + "expected_input": "s = "bbb"", + "expected_output": "true", + "explanation": "There are no 'a's, hence, every 'a' appears before every 'b' and we return true." + } + ], + "solution": "/**\n * @param {string} s\n * @return {boolean}\n */\nconst checkString = function(s) {\n const la = s.lastIndexOf('a')\n const fb = s.indexOf('b')\n return fb === -1 ? true : la < fb\n};\n" + }, + { + "_id": "66f925defdfb8e1665720eed", + "questionid": 1058, + "title": "Solving Questions With Brainpower", + "slug": "solving-questions-with-brainpower", + "description": "You are given a 0-indexed 2D integer array questions where questions[i] = [pointsi, brainpoweri]. The array describes the questions of an exam, where you have to process the questions in order (i.e., starting from question 0) and make a decision whether to solve or skip each question. Solving question i will earn you pointsi points but you will be unable to solve each of the next brainpoweri questions. If you skip question i, you get to make the decision on the next question. Return the maximum points you can earn for the exam. ", + "category": [ + "Array", + "Dynamic Programming" + ], + "complexity": "Medium", + "successrate": 44.3, + "totalsubmissions": 40097, + "totalaccepted": 17782, + "likes": 532, + "dislikes": 7, + "hints": "For each question, we can either solve it or skip it. How can we use Dynamic Programming to decide the most optimal option for each problem? We store for each question the maximum points we can earn if we started the exam on that question. If we skip a question, then the answer for it will be the same as the answer for the next question. If we solve a question, then the answer for it will be the points of the current question plus the answer for the next solvable question. The maximum of these two values will be the answer to the current question.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "questions = [[3,2],[4,3],[4,4],[2,5]]", + "expected_output": "5", + "explanation": "The maximum points can be earned by solving questions 0 and 3.\n- Solve question 0: Earn 3 points, will be unable to solve the next 2 questions\n- Unable to solve questions 1 and 2\n- Solve question 3: Earn 2 points\nTotal points earned: 3 + 2 = 5. There is no other way to earn 5 or more points." + }, + { + "example_num": 2, + "expected_input": "questions = [[1,1],[2,2],[3,3],[4,4],[5,5]]", + "expected_output": "7", + "explanation": "The maximum points can be earned by solving questions 1 and 4.\n- Skip question 0\n- Solve question 1: Earn 2 points, will be unable to solve the next 2 questions\n- Unable to solve questions 2 and 3\n- Solve question 4: Earn 5 points\nTotal points earned: 2 + 5 = 7. There is no other way to earn 7 or more points." + } + ], + "solution": "/**\n * @param {number[][]} questions\n * @return {number}\n */\nconst mostPoints = function(questions) {\n const n = questions.length, dp = Array(n + 1).fill(0)\n for (let i = n - 1; i >= 0; i--) {\n const [gain, p] = questions[i]\n dp[i] = Math.max(dp[i + 1], (dp[p + i + 1] || 0) + gain)\n }\n return dp[0]\n};\n\n// another\n\n/**\n * @param {number[][]} questions\n * @return {number}\n */\nconst mostPoints = function (questions) {\n let n = questions.length\n const temp = Array(n).fill(0)\n\n temp[n - 1] = questions[n - 1][0]\n\n for (let i = n - 2; i >= 0; i--) {\n if (i + questions[i][1] + 1 <= n - 1)\n temp[i] = Math.max(\n temp[i + 1],\n questions[i][0] + temp[i + questions[i][1] + 1]\n )\n else temp[i] = Math.max(temp[i + 1], questions[i][0])\n }\n return temp[0]\n}\n" + }, + { + "_id": "66f925defdfb8e1665720eee", + "questionid": 1059, + "title": "Maximum Running Time of N Computers", + "slug": "maximum-running-time-of-n-computers", + "description": "You have n computers. You are given the integer n and a 0-indexed integer array batteries where the ith battery can run a computer for batteries[i] minutes. You are interested in running all n computers simultaneously using the given batteries. Initially, you can insert at most one battery into each computer. After that and at any integer time moment, you can remove a battery from a computer and insert another battery any number of times. The inserted battery can be a totally new battery or a battery from another computer. You may assume that the removing and inserting processes take no time. Note that the batteries cannot be recharged. Return the maximum number of minutes you can run all the n computers simultaneously. ", + "category": [ + "Array", + "Binary Search", + "Greedy", + "Sorting" + ], + "complexity": "Hard", + "successrate": 37.5, + "totalsubmissions": 20733, + "totalaccepted": 7779, + "likes": 437, + "dislikes": 10, + "hints": "For a given running time, can you determine if it is possible to run all n computers simultaneously? Try to use Binary Search to find the maximal running time", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 2, batteries = [3,3,3]", + "expected_output": "4", + "explanation": "Initially, insert battery 0 into the first computer and battery 1 into the second computer.\nAfter two minutes, remove battery 1 from the second computer and insert battery 2 instead. Note that battery 1 can still run for one minute.\nAt the end of the third minute, battery 0 is drained, and you need to remove it from the first computer and insert battery 1 instead.\nBy the end of the fourth minute, battery 1 is also drained, and the first computer is no longer running.\nWe can run the two computers simultaneously for at most 4 minutes, so we return 4." + }, + { + "example_num": 2, + "expected_input": "n = 2, batteries = [1,1,1,1]", + "expected_output": "2", + "explanation": "Initially, insert battery 0 into the first computer and battery 2 into the second computer. \nAfter one minute, battery 0 and battery 2 are drained so you need to remove them and insert battery 1 into the first computer and battery 3 into the second computer. \nAfter another minute, battery 1 and battery 3 are also drained so the first and second computers are no longer running.\nWe can run the two computers simultaneously for at most 2 minutes, so we return 2." + } + ], + "solution": "/**\n * @param {number} n\n * @param {number[]} batteries\n * @return {number}\n */\nconst maxRunTime = function(n, batteries) {\n n = BigInt(n)\n batteries = batteries.map(e => BigInt(e))\n const sum = batteries.reduce((ac, e) => ac + e, 0n)\n let l = 0n, r = sum / n\n while(l < r) {\n const mid = r - (r - l) / 2n\n if(valid(mid)) l = mid\n else r = mid - 1n\n }\n \n return l\n \n function valid(mid) {\n let curSum = 0n, target = mid * n\n for(const e of batteries) {\n curSum += e > mid ? mid : e\n if(curSum >= target) return true\n }\n return false\n }\n};\n\n\n// another\n\n\n/**\n * @param {number} n\n * @param {number[]} batteries\n * @return {number}\n */\nvar maxRunTime = function (n, batteries) {\n batteries.sort((a, b) => a - b)\n const sum = batteries.reduce((ac, e) => ac + BigInt(e), 0n)\n let hi = ~~(sum / BigInt(n)) + 1n,\n lo = 0n\n while (lo < hi) {\n let mid = ~~((lo + hi) / 2n)\n if (chk(mid)) {\n lo = mid + 1n\n } else {\n hi = mid\n }\n }\n\n return lo - 1n\n function chk(x) {\n let current = 0n\n let i = 0n\n for (let b of batteries) {\n if (i == BigInt(n)) break\n if (b > x) b = x\n if (b >= x - current) {\n i += 1n\n current = BigInt(b) - (x - current)\n } else {\n current += BigInt(b)\n }\n }\n\n return i == n\n }\n}\n" + }, + { + "_id": "66f925defdfb8e1665720eef", + "questionid": 1060, + "title": "Minimum Sum of Four Digit Number After Splitting Digits", + "slug": "minimum-sum-of-four-digit-number-after-splitting-digits", + "description": "You are given a positive integer num consisting of exactly four digits. Split num into two new integers new1 and new2 by using the digits found in num. Leading zeros are allowed in new1 and new2, and all the digits found in num must be used. Return the minimum possible sum of new1 and new2. ", + "category": [ + "Math", + "Greedy", + "Sorting" + ], + "complexity": "Easy", + "successrate": 88, + "totalsubmissions": 30322, + "totalaccepted": 26673, + "likes": 295, + "dislikes": 36, + "hints": "Notice that the most optimal way to obtain the minimum possible sum using 4 digits is by summing up two 2-digit numbers. We can use the two smallest digits out of the four as the digits found in the tens place respectively. Similarly, we use the final 2 larger digits as the digits found in the ones place.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "num = 2932", + "expected_output": "52", + "explanation": "Some possible pairs [new1, new2] are [29, 23], [223, 9], etc.\nThe minimum sum can be obtained by the pair [29, 23]: 29 + 23 = 52." + }, + { + "example_num": 2, + "expected_input": "num = 4009", + "expected_output": "13", + "explanation": "Some possible pairs [new1, new2] are [0, 49], [490, 0], etc. \nThe minimum sum can be obtained by the pair [4, 9]: 4 + 9 = 13." + } + ], + "solution": null + }, + { + "_id": "66f925defdfb8e1665720ef1", + "questionid": 1062, + "title": "Find All Lonely Numbers in the Array", + "slug": "find-all-lonely-numbers-in-the-array", + "description": "You are given an integer array nums. A number x is lonely when it appears only once, and no adjacent numbers (i.e. x + 1 and x - 1) appear in the array. Return all lonely numbers in nums. You may return the answer in any order. ", + "category": [ + "Array", + "Hash Table", + "Counting" + ], + "complexity": "Medium", + "successrate": 60.6, + "totalsubmissions": 37637, + "totalaccepted": 22804, + "likes": 212, + "dislikes": 31, + "hints": "For a given element x, how can you quickly check if x - 1 and x + 1 are present in the array without reiterating through the entire array? Use a set or a hash map.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [10,6,5,8]", + "expected_output": "[10,8]", + "explanation": "- 10 is a lonely number since it appears exactly once and 9 and 11 does not appear in nums.\n- 8 is a lonely number since it appears exactly once and 7 and 9 does not appear in nums.\n- 5 is not a lonely number since 6 appears in nums and vice versa.\nHence, the lonely numbers in nums are [10, 8].\nNote that [8, 10] may also be returned." + }, + { + "example_num": 2, + "expected_input": "nums = [1,3,5,3]", + "expected_output": "[1,5]", + "explanation": "- 1 is a lonely number since it appears exactly once and 0 and 2 does not appear in nums.\n- 5 is a lonely number since it appears exactly once and 4 and 6 does not appear in nums.\n- 3 is not a lonely number since it appears twice.\nHence, the lonely numbers in nums are [1, 5].\nNote that [5, 1] may also be returned." + } + ], + "solution": "/**\n * @param {number[]} nums\n * @return {number[]}\n */\nvar findLonely = function(nums) {\n nums.sort((a, b) => a - b)\n const cnt = {}\n for(let e of nums) {\n if(cnt[e] == null) cnt[e] = 0\n cnt[e]++\n }\n // console.log(cnt)\n const res = []\n for(let i = 0, n = nums.length; i < n; i++) {\n if(i === 0){\n if(nums[i + 1] !== nums[i] + 1 && cnt[nums[i]] === 1) {\n res.push(nums[i]) \n }\n } \n else if(i === n - 1 ) {\n if(nums[i] !== nums[i - 1] + 1 && cnt[nums[i]] === 1) {\n res.push(nums[i])\n }\n }\n else if(cnt[nums[i]] === 1 && nums[i] !== nums[i - 1] + 1 && nums[i] !== nums[i + 1] - 1) {\n res.push(nums[i])\n }\n }\n \n return res\n};\n" + }, + { + "_id": "66f925defdfb8e1665720ef2", + "questionid": 1063, + "title": "Find Three Consecutive Integers That Sum to a Given Number", + "slug": "find-three-consecutive-integers-that-sum-to-a-given-number", + "description": "Given an integer num, return three consecutive integers (as a sorted array) that sum to num. If num cannot be expressed as the sum of three consecutive integers, return an empty array. ", + "category": [ + "Math", + "Simulation" + ], + "complexity": "Medium", + "successrate": 60.4, + "totalsubmissions": 30561, + "totalaccepted": 18456, + "likes": 234, + "dislikes": 60, + "hints": "Notice that if a solution exists, we can represent them as x-1, x, x+1. What does this tell us about the number? Notice the sum of the numbers will be 3x. Can you solve for x?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "num = 33", + "expected_output": "[10,11,12]", + "explanation": "33 can be expressed as 10 + 11 + 12 = 33.\n10, 11, 12 are 3 consecutive integers, so we return [10, 11, 12]." + }, + { + "example_num": 2, + "expected_input": "num = 4", + "expected_output": "[]", + "explanation": "There is no way to express 4 as the sum of 3 consecutive integers." + } + ], + "solution": null + }, + { + "_id": "66f925defdfb8e1665720ef3", + "questionid": 1064, + "title": "Maximum Split of Positive Even Integers", + "slug": "maximum-split-of-positive-even-integers", + "description": "You are given an integer finalSum. Split it into a sum of a maximum number of unique positive even integers. Return a list of integers that represent a valid split containing a maximum number of integers. If no valid split exists for finalSum, return an empty list. You may return the integers in any order. ", + "category": [ + "Math", + "Greedy" + ], + "complexity": "Medium", + "successrate": 54.6, + "totalsubmissions": 26382, + "totalaccepted": 14415, + "likes": 331, + "dislikes": 38, + "hints": "First, check if finalSum is divisible by 2. If it isn\u20ac\u2122t, then we cannot split it into even integers. Let k be the number of elements in our split. As we want the maximum number of elements, we should try to use the first k - 1 even elements to grow our sum as slowly as possible. Thus, we find the maximum sum of the first k - 1 even elements which is less than finalSum. We then add the difference over to the kth element.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "finalSum = 12", + "expected_output": "[2,4,6]", + "explanation": "The following are valid splits: (12), (2 + 10), (2 + 4 + 6), and (4 + 8).\n(2 + 4 + 6) has the maximum number of integers, which is 3. Thus, we return [2,4,6].\nNote that [2,6,4], [6,2,4], etc. are also accepted." + }, + { + "example_num": 2, + "expected_input": "finalSum = 7", + "expected_output": "[]", + "explanation": "There are no valid splits for the given finalSum.\nThus, we return an empty array." + }, + { + "example_num": 3, + "expected_input": "finalSum = 28", + "expected_output": "[6,8,2,12]", + "explanation": "The following are valid splits: (2 + 26), (6 + 8 + 2 + 12), and (4 + 24). \n(6 + 8 + 2 + 12) has the maximum number of integers, which is 4. Thus, we return [6,8,2,12].\nNote that [10,2,4,12], [6,2,4,16], etc. are also accepted." + } + ], + "solution": "/**\n * @param {number} finalSum\n * @return {number[]}\n */\nconst maximumEvenSplit = function(finalSum) {\n if(finalSum % 2 === 1) return []\n const res = []\n let i = 2\n while(i <= finalSum) {\n res.push(i)\n finalSum -= i\n i += 2\n }\n \n const last = res.pop()\n res.push(finalSum + last)\n return res\n};\n" + }, + { + "_id": "66f925defdfb8e1665720ef4", + "questionid": 1065, + "title": "Count Good Triplets in an Array", + "slug": "count-good-triplets-in-an-array", + "description": "You are given two 0-indexed arrays nums1 and nums2 of length n, both of which are permutations of [0, 1, ..., n - 1]. A good triplet is a set of 3 distinct values which are present in increasing order by position both in nums1 and nums2. In other words, if we consider pos1v as the index of the value v in nums1 and pos2v as the index of the value v in nums2, then a good triplet will be a set (x, y, z) where 0 <= x, y, z <= n - 1, such that pos1x < pos1y < pos1z and pos2x < pos2y < pos2z. Return the total number of good triplets. ", + "category": [ + "Array", + "Binary Search", + "Divide and Conquer", + "Binary Indexed Tree", + "Segment Tree", + "Merge Sort", + "Ordered Set" + ], + "complexity": "Hard", + "successrate": 34, + "totalsubmissions": 10057, + "totalaccepted": 3422, + "likes": 257, + "dislikes": 10, + "hints": "For every value y, how can you find the number of values x (0 \u2030\u00a4 x, y \u2030\u00a4 n - 1) such that x appears before y in both of the arrays? Similarly, for every value y, try finding the number of values z (0 \u2030\u00a4 y, z \u2030\u00a4 n - 1) such that z appears after y in both of the arrays. Now, for every value y, count the number of good triplets that can be formed if y is considered as the middle element.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums1 = [2,0,1,3], nums2 = [0,1,2,3]", + "expected_output": "1", + "explanation": "There are 4 triplets (x,y,z) such that pos1x < pos1y < pos1z. They are (2,0,1), (2,0,3), (2,1,3), and (0,1,3). \nOut of those triplets, only the triplet (0,1,3) satisfies pos2x < pos2y < pos2z. Hence, there is only 1 good triplet." + }, + { + "example_num": 2, + "expected_input": "nums1 = [4,0,1,3,2], nums2 = [4,1,0,2,3]", + "expected_output": "4", + "explanation": "The 4 good triplets are (4,0,3), (4,0,2), (4,1,3), and (4,1,2)." + } + ], + "solution": "/**\n * @param {number[]} a\n * @param {number[]} b\n * @return {number}\n */\nconst goodTriplets = function(a, b) {\n let n = a.length, m = new Map(), res = 0;\n for (let i = 0; i < n; i++) m.set(b[i], i);\n let fen = new Fenwick(n + 3);\n for (let i = 0; i < n; i++) {\n let pos = m.get(a[i]);\n let l = fen.query(pos), r = (n - 1 - pos) - (fen.query(n - 1) - fen.query(pos));\n res += l * r; \n fen.update(pos, 1);\n }\n return res;\n};\nfunction Fenwick(n) {\n let tree = Array(n).fill(0);\n return { query, update }\n function query(i) {\n let sum = 0;\n i++;\n while (i > 0) {\n sum += tree[i];\n i -= i & -i;\n }\n return sum;\n }\n function update(i, v) {\n i++;\n while (i < n) {\n tree[i] += v;\n i += i & -i;\n }\n }\n}\n" + }, + { + "_id": "66f925defdfb8e1665720ef8", + "questionid": 1069, + "title": "Maximum AND Sum of Array", + "slug": "maximum-and-sum-of-array", + "description": "You are given an integer array nums of length n and an integer numSlots such that 2 * numSlots >= n. There are numSlots slots numbered from 1 to numSlots. You have to place all n integers into the slots such that each slot contains at most two numbers. The AND sum of a given placement is the sum of the bitwise AND of every number with its respective slot number. Return the maximum possible AND sum of nums given numSlots slots. ", + "category": [ + "Array", + "Dynamic Programming", + "Bit Manipulation", + "Bitmask" + ], + "complexity": "Hard", + "successrate": 43.1, + "totalsubmissions": 12204, + "totalaccepted": 5263, + "likes": 220, + "dislikes": 11, + "hints": "Can you think of a dynamic programming solution to this problem? Can you use a bitmask to represent the state of the slots?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,2,3,4,5,6], numSlots = 3", + "expected_output": "9", + "explanation": "One possible placement is [1, 4] into slot 1, [2, 6] into slot 2, and [3, 5] into slot 3. \nThis gives the maximum AND sum of (1 AND 1) + (4 AND 1) + (2 AND 2) + (6 AND 2) + (3 AND 3) + (5 AND 3) = 1 + 0 + 2 + 2 + 3 + 1 = 9." + }, + { + "example_num": 2, + "expected_input": "nums = [1,3,10,4,7,1], numSlots = 9", + "expected_output": "24", + "explanation": "One possible placement is [1, 1] into slot 1, [3] into slot 3, [4] into slot 4, [7] into slot 7, and [10] into slot 9.\nThis gives the maximum AND sum of (1 AND 1) + (1 AND 1) + (3 AND 3) + (4 AND 4) + (7 AND 7) + (10 AND 9) = 1 + 1 + 3 + 4 + 7 + 8 = 24.\nNote that slots 2, 5, 6, and 8 are empty which is permitted." + } + ], + "solution": "/**\n * @param {number[]} nums\n * @param {number} numSlots\n * @return {number}\n */\nconst maximumANDSum = function (nums, numSlots) {\n const n = nums.length\n nums.unshift(0)\n const m = Math.pow(3, numSlots)\n\n const dp = Array.from({ length: n + 1 }, () => Array(m).fill(-Infinity))\n dp[0][0] = 0\n\n let ret = 0\n\n for (let state = 1; state < m; state++) {\n let i = 0\n let temp = state\n while (temp > 0) {\n i += temp % 3\n temp = Math.floor(temp / 3)\n }\n if (i > n) continue\n\n for (let j = 0; j < numSlots; j++) {\n if (filled(state, j) >= 1) {\n dp[i][state] = Math.max(\n dp[i][state],\n dp[i - 1][state - Math.pow(3, j)] + (nums[i] & (j + 1))\n )\n }\n }\n if (i === n) ret = Math.max(ret, dp[i][state])\n }\n\n return ret\n}\n\nfunction filled(state, k) {\n for (let i = 0; i < k; i++) state = Math.floor(state / 3)\n return state % 3\n}\n" + }, + { + "_id": "66f925defdfb8e1665720f01", + "questionid": 1078, + "title": "Create Binary Tree From Descriptions", + "slug": "create-binary-tree-from-descriptions", + "description": "You are given a 2D integer array descriptions where descriptions[i] = [parenti, childi, isLefti] indicates that parenti is the parent of childi in a binary tree of unique values. Furthermore, Construct the binary tree described by descriptions and return its root. The test cases will be generated such that the binary tree is valid. ", + "category": [ + "Array", + "Hash Table", + "Tree", + "Depth-First Search", + "Breadth-First Search", + "Binary Tree" + ], + "complexity": "Medium", + "successrate": 70.3, + "totalsubmissions": 19891, + "totalaccepted": 13986, + "likes": 334, + "dislikes": 7, + "hints": "Could you represent and store the descriptions more efficiently? Could you find the root node? The node that is not a child in any of the descriptions is the root node.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "descriptions = [[20,15,1],[20,17,0],[50,20,1],[50,80,0],[80,19,1]]", + "expected_output": "[50,20,80,15,17,19]", + "explanation": "The root node is the node with value 50 since it has no parent.\nThe resulting binary tree is shown in the diagram." + }, + { + "example_num": 2, + "expected_input": "descriptions = [[1,2,1],[2,3,0],[3,4,1]]", + "expected_output": "[1,2,null,null,3,4]", + "explanation": "The root node is the node with value 1 since it has no parent.\nThe resulting binary tree is shown in the diagram." + } + ], + "solution": null + }, + { + "_id": "66f925defdfb8e1665720f07", + "questionid": 1084, + "title": "Minimum Weighted Subgraph With the Required Paths", + "slug": "minimum-weighted-subgraph-with-the-required-paths", + "description": "You are given an integer n denoting the number of nodes of a weighted directed graph. The nodes are numbered from 0 to n - 1. You are also given a 2D integer array edges where edges[i] = [fromi, toi, weighti] denotes that there exists a directed edge from fromi to toi with weight weighti. Lastly, you are given three distinct integers src1, src2, and dest denoting three distinct nodes of the graph. Return the minimum weight of a subgraph of the graph such that it is possible to reach dest from both src1 and src2 via a set of edges of this subgraph. In case such a subgraph does not exist, return -1. A subgraph is a graph whose vertices and edges are subsets of the original graph. The weight of a subgraph is the sum of weights of its constituent edges. ", + "category": [ + "Graph", + "Shortest Path" + ], + "complexity": "Hard", + "successrate": 35.1, + "totalsubmissions": 16637, + "totalaccepted": 5834, + "likes": 369, + "dislikes": 11, + "hints": "Consider what the paths from src1 to dest and src2 to dest would look like in the optimal solution. It can be shown that in an optimal solution, the two paths from src1 and src2 will coincide at one node, and the remaining part to dest will be the same for both paths. Now consider how to find the node where the paths will coincide. How can algorithms for finding the shortest path between two nodes help us?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 6, edges = [[0,2,2],[0,5,6],[1,0,3],[1,4,5],[2,1,1],[2,3,3],[2,3,4],[3,4,2],[4,5,1]], src1 = 0, src2 = 1, dest = 5", + "expected_output": "9", + "explanation": "The above figure represents the input graph.\nThe blue edges represent one of the subgraphs that yield the optimal answer.\nNote that the subgraph [[1,0,3],[0,5,6]] also yields the optimal answer. It is not possible to get a subgraph with less weight satisfying all the constraints." + }, + { + "example_num": 2, + "expected_input": "n = 3, edges = [[0,1,1],[2,1,1]], src1 = 0, src2 = 1, dest = 2", + "expected_output": "-1", + "explanation": "The above figure represents the input graph.\nIt can be seen that there does not exist any path from node 1 to node 2, hence there are no subgraphs satisfying all the constraints." + } + ], + "solution": "const initializeGraph = (n) => {\n let g = []\n for (let i = 0; i < n; i++) {\n g.push([])\n }\n return g\n}\nconst packDGCost = (g, ig, edges) => {\n for (const [u, v, cost] of edges) {\n g[u].push([v, cost])\n ig[v].push([u, cost])\n }\n}\n/**\n * @param {number} n\n * @param {number[][]} edges\n * @param {number} src1\n * @param {number} src2\n * @param {number} dest\n * @return {number}\n */\nvar minimumWeight = function(n, edges, src1, src2, dest) {\n let g = initializeGraph(n),\n ig = initializeGraph(n)\n packDGCost(g, ig, edges)\n /*\n src1 -> x\n src2 -> x\n x -> dest find smallest distance from all nodes to the destination, run Dijkstra in reverse from the destination\n */\n let d1 = dijkstra(g, src1),\n d2 = dijkstra(g, src2),\n d3 = dijkstra(ig, dest),\n res = Number.MAX_SAFE_INTEGER\n for (let i = 0; i < n; i++) res = Math.min(res, d1[i] + d2[i] + d3[i])\n return res == Number.MAX_SAFE_INTEGER ? -1 : res\n}\n\nconst dijkstra = (g, start) => {\n // store the shortest distance from startNode to all other nodes\n let n = g.length,\n dis = Array(n).fill(Number.MAX_SAFE_INTEGER)\n let pq = new MinPriorityQueue({\n compare: (x, y) => {\n if (x[0] != y[0]) return x[0] - y[0]\n return x[1] - y[1]\n },\n })\n dis[start] = 0\n pq.enqueue([start, 0])\n while (pq.size()) {\n let [cur, d] = pq.dequeue()\n if (d > dis[cur]) continue // larger distance, no need to find the route to next node\n for (const [child, cost] of g[cur]) {\n let toChildCost = d + cost\n if (toChildCost < dis[child]) {\n // each time total wight/cost to current child is smaller, updated it\n dis[child] = toChildCost\n pq.enqueue([child, toChildCost])\n }\n }\n }\n return dis \n};\n" + }, + { + "_id": "66f925defdfb8e1665720f0b", + "questionid": 1088, + "title": "Minimize Result by Adding Parentheses to Expression", + "slug": "minimize-result-by-adding-parentheses-to-expression", + "description": "You are given a 0-indexed string expression of the form \"+\" where and represent positive integers. Add a pair of parentheses to expression such that after the addition of parentheses, expression is a valid mathematical expression and evaluates to the smallest possible value. The left parenthesis must be added to the left of '+' and the right parenthesis must be added to the right of '+'. Return expression after adding a pair of parentheses such that expression evaluates to the smallest possible value. If there are multiple answers that yield the same result, return any of them. The input has been generated such that the original value of expression, and the value of expression after adding any pair of parentheses that meets the requirements fits within a signed 32-bit integer. ", + "category": [ + "String", + "Enumeration" + ], + "complexity": "Medium", + "successrate": 63.6, + "totalsubmissions": 14828, + "totalaccepted": 9438, + "likes": 102, + "dislikes": 210, + "hints": "The maximum length of expression is very low. We can try every possible spot to place the parentheses. Every possibility of expression is of the form a * (b + c) * d where a, b, c, d represent integers. Note the edge cases where a and/or d do not exist, in which case use 1 instead of them.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "expression = "247+38"", + "expected_output": ""2(47+38)"", + "explanation": "The expression evaluates to 2 * (47 + 38) = 2 * 85 = 170.\nNote that "2(4)7+38" is invalid because the right parenthesis must be to the right of the '+'.\nIt can be shown that 170 is the smallest possible value." + }, + { + "example_num": 2, + "expected_input": "expression = "12+34"", + "expected_output": ""1(2+3)4"", + "explanation": "The expression evaluates to 1 * (2 + 3) * 4 = 1 * 5 * 4 = 20." + }, + { + "example_num": 3, + "expected_input": "expression = "999+999"", + "expected_output": ""(999+999)"", + "explanation": "The expression evaluates to 999 + 999 = 1998." + } + ], + "solution": null + }, + { + "_id": "66f925defdfb8e1665720eb4", + "questionid": 1001, + "title": "Smallest Missing Genetic Value in Each Subtree", + "slug": "smallest-missing-genetic-value-in-each-subtree", + "description": "There is a family tree rooted at 0 consisting of n nodes numbered 0 to n - 1. You are given a 0-indexed integer array parents, where parents[i] is the parent for node i. Since node 0 is the root, parents[0] == -1. There are 105 genetic values, each represented by an integer in the inclusive range [1, 105]. You are given a 0-indexed integer array nums, where nums[i] is a distinct genetic value for node i. Return an array ans of length n where ans[i] is the smallest genetic value that is missing from the subtree rooted at node i. The subtree rooted at a node x contains node x and all of its descendant nodes. ", + "category": [ + "Dynamic Programming", + "Tree", + "Depth-First Search", + "Union Find" + ], + "complexity": "Hard", + "successrate": 42.3, + "totalsubmissions": 11335, + "totalaccepted": 4799, + "likes": 266, + "dislikes": 16, + "hints": "If the subtree doesn't contain 1, then the missing value will always be 1. What data structure allows us to dynamically update the values that are currently not present?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "parents = [-1,0,0,2], nums = [1,2,3,4]", + "expected_output": "[5,1,1,1]", + "explanation": "The answer for each subtree is calculated as follows:\n- 0: The subtree contains nodes [0,1,2,3] with values [1,2,3,4]. 5 is the smallest missing value.\n- 1: The subtree contains only node 1 with value 2. 1 is the smallest missing value.\n- 2: The subtree contains nodes [2,3] with values [3,4]. 1 is the smallest missing value.\n- 3: The subtree contains only node 3 with value 4. 1 is the smallest missing value." + }, + { + "example_num": 2, + "expected_input": "parents = [-1,0,1,0,3,3], nums = [5,4,6,2,1,3]", + "expected_output": "[7,1,1,4,2,1]", + "explanation": "The answer for each subtree is calculated as follows:\n- 0: The subtree contains nodes [0,1,2,3,4,5] with values [5,4,6,2,1,3]. 7 is the smallest missing value.\n- 1: The subtree contains nodes [1,2] with values [4,6]. 1 is the smallest missing value.\n- 2: The subtree contains only node 2 with value 6. 1 is the smallest missing value.\n- 3: The subtree contains nodes [3,4,5] with values [2,1,3]. 4 is the smallest missing value.\n- 4: The subtree contains only node 4 with value 1. 2 is the smallest missing value.\n- 5: The subtree contains only node 5 with value 3. 1 is the smallest missing value." + }, + { + "example_num": 3, + "expected_input": "parents = [-1,2,3,0,2,4,1], nums = [2,3,4,5,6,7,8]", + "expected_output": "[1,1,1,1,1,1,1]", + "explanation": "The value 1 is missing from all the subtrees." + } + ], + "solution": "/**\n * @param {number[]} parents\n * @param {number[]} nums\n * @return {number[]}\n */\nfunction smallestMissingValueSubtree(parent, nums) {\n const graph = {},\n n = parent.length\n const res = Array(n).fill(1)\n const visited = new Set()\n let miss = 1\n for (let i = 0; i < n; i++) {\n if (graph[parent[i]] == null) graph[parent[i]] = []\n graph[parent[i]].push(i)\n }\n let idx = -1\n for (let i = 0; i < n; i++) {\n if (nums[i] === 1) {\n idx = i\n break\n }\n }\n\n if (idx === -1) return res\n let cur = idx,\n pre = -1\n while (cur !== -1) {\n const chidlren = graph[cur]\n if (chidlren) {\n for (const child of chidlren) {\n if (child === pre) continue\n dfs(child)\n }\n }\n visited.add(nums[cur])\n while (visited.has(miss)) {\n miss++\n }\n // console.log(cur, miss, visited)\n res[cur] = miss\n pre = cur\n cur = parent[cur]\n }\n\n return res\n\n function dfs(node) {\n visited.add(nums[node])\n const chidlren = graph[node]\n if (chidlren) {\n for (const child of chidlren) dfs(child)\n }\n }\n}\n\n// another\n\n\n/**\n * @param {number[]} parents\n * @param {number[]} nums\n * @return {number[]}\n */\nconst smallestMissingValueSubtree = function(parents, nums) {\n let n = parents.length;\n const ans = new Array(n).fill(0);\n const fn = new Array(100010).fill(0);\n const tree = [];\n const nums1 = nums;\n for(let idx=0;idxrec && fn[pos]<=nodeIdx) {\n pos++;\n }\n ans[root] = pos;\n return pos;\n }\n};\n\n" + }, + { + "_id": "66f925defdfb8e1665720eb5", + "questionid": 1002, + "title": "Convert 1D Array Into 2D Array", + "slug": "convert-1d-array-into-2d-array", + "description": "You are given a 0-indexed 1-dimensional (1D) integer array original, and two integers, m and n. You are tasked with creating a 2-dimensional (2D) array with m rows and n columns using all the elements from original. The elements from indices 0 to n - 1 (inclusive) of original should form the first row of the constructed 2D array, the elements from indices n to 2 * n - 1 (inclusive) should form the second row of the constructed 2D array, and so on. Return an m x n 2D array constructed according to the above procedure, or an empty 2D array if it is impossible. ", + "category": [ + "Array", + "Matrix", + "Simulation" + ], + "complexity": "Easy", + "successrate": 59.2, + "totalsubmissions": 49401, + "totalaccepted": 29235, + "likes": 292, + "dislikes": 20, + "hints": "When is it possible to convert original into a 2D array and when is it impossible? It is possible if and only if m * n == original.length If it is possible to convert original to a 2D array, keep an index i such that original[i] is the next element to add to the 2D array.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "original = [1,2,3,4], m = 2, n = 2", + "expected_output": "[[1,2],[3,4]]", + "explanation": "The constructed 2D array should contain 2 rows and 2 columns.\nThe first group of n=2 elements in original, [1,2], becomes the first row in the constructed 2D array.\nThe second group of n=2 elements in original, [3,4], becomes the second row in the constructed 2D array." + }, + { + "example_num": 2, + "expected_input": "original = [1,2,3], m = 1, n = 3", + "expected_output": "[[1,2,3]]", + "explanation": "The constructed 2D array should contain 1 row and 3 columns.\nPut all three elements in original into the first row of the constructed 2D array." + }, + { + "example_num": 3, + "expected_input": "original = [1,2], m = 1, n = 1", + "expected_output": "[]", + "explanation": "There are 2 elements in original.\nIt is impossible to fit 2 elements in a 1x1 2D array, so return an empty 2D array." + } + ], + "solution": null + }, + { + "_id": "66f925defdfb8e1665720eb9", + "questionid": 1006, + "title": "Grid Game", + "slug": "grid-game", + "description": "You are given a 0-indexed 2D array grid of size 2 x n, where grid[r][c] represents the number of points at position (r, c) on the matrix. Two robots are playing a game on this matrix. Both robots initially start at (0, 0) and want to reach (1, n-1). Each robot may only move to the right ((r, c) to (r, c + 1)) or down ((r, c) to (r + 1, c)). At the start of the game, the first robot moves from (0, 0) to (1, n-1), collecting all the points from the cells on its path. For all cells (r, c) traversed on the path, grid[r][c] is set to 0. Then, the second robot moves from (0, 0) to (1, n-1), collecting the points on its path. Note that their paths may intersect with one another. The first robot wants to minimize the number of points collected by the second robot. In contrast, the second robot wants to maximize the number of points it collects. If both robots play optimally, return the number of points collected by the second robot. ", + "category": [ + "Array", + "Matrix", + "Prefix Sum" + ], + "complexity": "Medium", + "successrate": 41.5, + "totalsubmissions": 24373, + "totalaccepted": 10126, + "likes": 430, + "dislikes": 12, + "hints": "There are n choices for when the first robot moves to the second row. Can we use prefix sums to help solve this problem?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "grid = [[2,5,4],[1,5,1]]", + "expected_output": "4", + "explanation": "The optimal path taken by the first robot is shown in red, and the optimal path taken by the second robot is shown in blue.\nThe cells visited by the first robot are set to 0.\nThe second robot will collect 0 + 0 + 4 + 0 = 4 points." + }, + { + "example_num": 2, + "expected_input": "grid = [[3,3,1],[8,5,2]]", + "expected_output": "4", + "explanation": "The optimal path taken by the first robot is shown in red, and the optimal path taken by the second robot is shown in blue.\nThe cells visited by the first robot are set to 0.\nThe second robot will collect 0 + 3 + 1 + 0 = 4 points." + }, + { + "example_num": 3, + "expected_input": "grid = [[1,3,1,15],[1,3,3,1]]", + "expected_output": "7\nExplanation: The optimal path taken by the first robot is shown in red, and the optimal path taken by the second robot is shown in blue.\nThe cells visited by the first robot are set to 0.\nThe second robot will collect 0 + 1 + 3 + 3 + 0 = 7 points.", + "explanation": "" + } + ], + "solution": null + }, + { + "_id": "66f925defdfb8e1665720eba", + "questionid": 1007, + "title": "Remove Colored Pieces if Both Neighbors are the Same Color", + "slug": "remove-colored-pieces-if-both-neighbors-are-the-same-color", + "description": "There are n pieces arranged in a line, and each piece is colored either by 'A' or by 'B'. You are given a string colors of length n where colors[i] is the color of the ith piece. Alice and Bob are playing a game where they take alternating turns removing pieces from the line. In this game, Alice moves first. Assuming Alice and Bob play optimally, return true if Alice wins, or return false if Bob wins. ", + "category": [ + "Math", + "String", + "Greedy", + "Game Theory" + ], + "complexity": "Medium", + "successrate": 56.1, + "totalsubmissions": 20174, + "totalaccepted": 11320, + "likes": 209, + "dislikes": 18, + "hints": "Does the number of moves a player can make depend on what the other player does? No How many moves can Alice make if colors == \"AAAAAA\" If a group of n consecutive pieces has the same color, the player can take n - 2 of those pieces if n is greater than or equal to 3", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "colors = "AAABABB"", + "expected_output": "true", + "explanation": "AAABABB -> AABABB\nAlice moves first.\nShe removes the second 'A' from the left since that is the only 'A' whose neighbors are both 'A'.\n\nNow it's Bob's turn.\nBob cannot make a move on his turn since there are no 'B's whose neighbors are both 'B'.\nThus, Alice wins, so return true." + }, + { + "example_num": 2, + "expected_input": "colors = "AA"", + "expected_output": "false", + "explanation": "Alice has her turn first.\nThere are only two 'A's and both are on the edge of the line, so she cannot move on her turn.\nThus, Bob wins, so return false." + }, + { + "example_num": 3, + "expected_input": "colors = "ABBBBBBBAAA"", + "expected_output": "false", + "explanation": "ABBBBBBBAAA -> ABBBBBBBAA\nAlice moves first.\nHer only option is to remove the second to last 'A' from the right.\n\nABBBBBBBAA -> ABBBBBBAA\nNext is Bob's turn.\nHe has many options for which 'B' piece to remove. He can pick any.\n\nOn Alice's second turn, she has no more pieces that she can remove.\nThus, Bob wins, so return false." + } + ], + "solution": "/**\n * @param {string} colors\n * @return {boolean}\n */\nconst winnerOfGame = function(colors) {\n let ac = 0, bc = 0\n for(let i = 1, n = colors.length; i < n - 1; i++) {\n if(colors[i] === 'A' && colors[i - 1] === 'A' && colors[i + 1] === 'A') ac++\n if(colors[i] === 'B' && colors[i - 1] === 'B' && colors[i + 1] === 'B') bc++\n }\n return ac > bc\n};\n" + }, + { + "_id": "66f925defdfb8e1665720ec0", + "questionid": 1013, + "title": "Partition Array Into Two Arrays to Minimize Sum Difference", + "slug": "partition-array-into-two-arrays-to-minimize-sum-difference", + "description": "You are given an integer array nums of 2 * n integers. You need to partition nums into two arrays of length n to minimize the absolute difference of the sums of the arrays. To partition nums, put each element of nums into one of the two arrays. Return the minimum possible absolute difference. ", + "category": [ + "Array", + "Two Pointers", + "Binary Search", + "Dynamic Programming", + "Bit Manipulation", + "Ordered Set", + "Bitmask" + ], + "complexity": "Hard", + "successrate": 21.7, + "totalsubmissions": 24142, + "totalaccepted": 5249, + "likes": 579, + "dislikes": 36, + "hints": "The target sum for the two partitions is sum(nums) / 2. Could you reduce the time complexity if you arbitrarily divide nums into two halves (two arrays)? Meet-in-the-Middle? For both halves, pre-calculate a 2D array where the kth index will store all possible sum values if only k elements from this half are added. For each sum of k elements in the first half, find the best sum of n-k elements in the second half such that the two sums add up to a value closest to the target sum from hint 1. These two subsets will form one array of the partition.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [3,9,7,3]", + "expected_output": "2", + "explanation": "One optimal partition is: [3,9] and [7,3].\nThe absolute difference between the sums of the arrays is abs((3 + 9) - (7 + 3)) = 2." + }, + { + "example_num": 2, + "expected_input": "nums = [-36,36]", + "expected_output": "72", + "explanation": "One optimal partition is: [-36] and [36].\nThe absolute difference between the sums of the arrays is abs((-36) - (36)) = 72." + }, + { + "example_num": 3, + "expected_input": "nums = [2,-1,0,4,-2,-9]", + "expected_output": "0", + "explanation": "One optimal partition is: [2,4,-9] and [-1,0,-2].\nThe absolute difference between the sums of the arrays is abs((2 + 4 + -9) - (-1 + 0 + -2)) = 0." + } + ], + "solution": "/**\n * @param {number[]} nums\n * @return {number}\n */\nconst mi = Math.min,\n abs = Math.abs\nconst minimumDifference = (nums) => {\n let m = nums.length,\n n = m >> 1\n let a = initializeGraph(n + 1)\n let b = initializeGraph(n + 1)\n for (let i = 0; i < 1 << n; i++) {\n // mask\n let sum = 0,\n cnt = 0\n for (let j = 0; j < n; j++) {\n if (i & (1 << j)) {\n // bit of 1's\n sum += nums[j]\n cnt++ // bit count\n } else {\n sum -= nums[j]\n }\n }\n a[cnt].push(sum)\n ;(sum = 0), (cnt = 0)\n for (let j = 0; j < n; j++) {\n if (i & (1 << j)) {\n sum += nums[n + j]\n cnt++\n } else {\n sum -= nums[n + j]\n }\n }\n b[cnt].push(sum)\n }\n for (let i = 0; i < n; i++) {\n a[i].sort((x, y) => x - y)\n b[i].sort((x, y) => x - y)\n }\n let res = Number.MAX_SAFE_INTEGER\n let bi = new Bisect()\n for (let i = 0; i <= n; i++) {\n for (const x of a[i]) {\n let idx = bi.bisect_left(b[n - i], -x) // binary search lower_bound\n if (idx != b[n - i].length) res = mi(res, abs(x + b[n - i][idx]))\n if (idx != 0) {\n idx--\n res = mi(res, abs(x + b[n - i][idx]))\n }\n }\n }\n return res\n}\n\n//////////////////////////////////////// Template ////////////////////////////////////////////////////////\nfunction Bisect() {\n return { insort_right, insort_left, bisect_left, bisect_right }\n function insort_right(a, x, lo = 0, hi = null) {\n lo = bisect_right(a, x, lo, hi)\n a.splice(lo, 0, x)\n }\n function bisect_right(a, x, lo = 0, hi = null) {\n // > upper_bound\n if (lo < 0) throw new Error('lo must be non-negative')\n if (hi == null) hi = a.length\n while (lo < hi) {\n let mid = (lo + hi) >> 1\n x < a[mid] ? (hi = mid) : (lo = mid + 1)\n }\n return lo\n }\n function insort_left(a, x, lo = 0, hi = null) {\n lo = bisect_left(a, x, lo, hi)\n a.splice(lo, 0, x)\n }\n function bisect_left(a, x, lo = 0, hi = null) {\n // >= lower_bound\n if (lo < 0) throw new Error('lo must be non-negative')\n if (hi == null) hi = a.length\n while (lo < hi) {\n let mid = (lo + hi) >> 1\n a[mid] < x ? (lo = mid + 1) : (hi = mid)\n }\n return lo\n }\n}\n\nconst initializeGraph = (n) => {\n let G = []\n for (let i = 0; i < n; i++) {\n G.push([])\n }\n return G\n}\n/////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n" + }, + { + "_id": "66f925defdfb8e1665720ec3", + "questionid": 1016, + "title": "Check if Numbers Are Ascending in a Sentence", + "slug": "check-if-numbers-are-ascending-in-a-sentence", + "description": "A sentence is a list of tokens separated by a single space with no leading or trailing spaces. Every token is either a positive number consisting of digits 0-9 with no leading zeros, or a word consisting of lowercase English letters. Given a string s representing a sentence, you need to check if all the numbers in s are strictly increasing from left to right (i.e., other than the last number, each number is strictly smaller than the number on its right in s). Return true if so, or false otherwise. ", + "category": [ + "String" + ], + "complexity": "Easy", + "successrate": 67.8, + "totalsubmissions": 33814, + "totalaccepted": 22931, + "likes": 236, + "dislikes": 11, + "hints": "Use string tokenization of your language to extract all the tokens of the string easily. For each token extracted, how can you tell if it is a number? Does the first letter being a digit mean something? Compare the number with the previously occurring number to check if ascending order is maintained.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "1 box has 3 blue 4 red 6 green and 12 yellow marbles"", + "expected_output": "true", + "explanation": "The numbers in s are: 1, 3, 4, 6, 12.\nThey are strictly increasing from left to right: 1 < 3 < 4 < 6 < 12." + }, + { + "example_num": 2, + "expected_input": "s = "hello world 5 x 5"", + "expected_output": "false", + "explanation": "The numbers in s are: 5, 5. They are not strictly increasing." + }, + { + "example_num": 3, + "expected_input": "s = "sunset is at 7 51 pm overnight lows will be in the low 50 and 60 s"", + "expected_output": "false", + "explanation": "The numbers in s are: 7, 51, 50, 60. They are not strictly increasing." + } + ], + "solution": "/**\n * @param {string} s\n * @return {boolean}\n */\nconst areNumbersAscending = function(s) {\n const arr =s.split(' ')\n const f = arr.filter(e => !Number.isNaN(+e)).map(e => +e)\n let res = true\n for(let i = 1; i < f.length; i++) {\n if(f[i] <= f[i - 1]) return false\n }\n \n return res\n};\n" + }, + { + "_id": "66f925defdfb8e1665720ec6", + "questionid": 1019, + "title": "Count Nodes With the Highest Score", + "slug": "count-nodes-with-the-highest-score", + "description": "There is a binary tree rooted at 0 consisting of n nodes. The nodes are labeled from 0 to n - 1. You are given a 0-indexed integer array parents representing the tree, where parents[i] is the parent of node i. Since node 0 is the root, parents[0] == -1. Each node has a score. To find the score of a node, consider if the node and the edges connected to it were removed. The tree would become one or more non-empty subtrees. The size of a subtree is the number of the nodes in it. The score of the node is the product of the sizes of all those subtrees. Return the number of nodes that have the highest score. ", + "category": [ + "Array", + "Tree", + "Depth-First Search", + "Binary Tree" + ], + "complexity": "Medium", + "successrate": 46.3, + "totalsubmissions": 20564, + "totalaccepted": 9513, + "likes": 389, + "dislikes": 24, + "hints": "For each node, you need to find the sizes of the subtrees rooted in each of its children. Maybe DFS? How to determine the number of nodes in the rest of the tree? Can you subtract the size of the subtree rooted at the node from the total number of nodes of the tree? Use these values to compute the score of the node. Track the maximum score, and how many nodes achieve such score.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "parents = [-1,2,0,2,0]", + "expected_output": "3", + "explanation": "- The score of node 0 is: 3 * 1 = 3\n- The score of node 1 is: 4 = 4\n- The score of node 2 is: 1 * 1 * 2 = 2\n- The score of node 3 is: 4 = 4\n- The score of node 4 is: 4 = 4\nThe highest score is 4, and three nodes (node 1, node 3, and node 4) have the highest score." + }, + { + "example_num": 2, + "expected_input": "parents = [-1,2,0]", + "expected_output": "2", + "explanation": "- The score of node 0 is: 2 = 2\n- The score of node 1 is: 2 = 2\n- The score of node 2 is: 1 * 1 = 1\nThe highest score is 2, and two nodes (node 0 and node 1) have the highest score." + } + ], + "solution": "/**\n * @param {number[]} parents\n * @return {number}\n */\nconst countHighestScoreNodes = function(parents) {\n const n = parents.length, graph = {}, hash = {}\n for(let i = 1; i < n; i++) {\n if(graph[parents[i]] == null) graph[parents[i]] = []\n graph[parents[i]].push(i)\n }\n dfs(0)\n \n function dfs(node) {\n let product = 1, num = 0\n for(let child of (graph[node] || [])) {\n const tmp = dfs(child)\n product *= tmp\n num += tmp\n }\n if(n - 1 - num > 0) product *= (n - 1 - num)\n hash[product] = (hash[product] || 0) + 1\n return num + 1\n }\n const maxKey = Math.max(...Object.keys(hash))\n return hash[maxKey]\n};\n\n// another\n\n/**\n * @param {number[]} parents\n * @return {number}\n */\nconst countHighestScoreNodes = function(parents) {\n const n = parents.length, hash = {}, graph = {}\n for(let i = 1; i < n; i++) {\n if(graph[parents[i]] == null) graph[parents[i]] = []\n graph[parents[i]].push(i)\n }\n\n dfs(0)\n const mk = Math.max(...Object.keys(hash))\n return hash[mk]\n \n function dfs(i) {\n let num = 0, prod = 1\n for(const e of (graph[i] || []) ) {\n const tmp = dfs(e)\n num += tmp\n prod *= tmp\n }\n \n if(n - 1 - num > 0) prod *= (n - 1 - num)\n hash[prod] = (hash[prod] || 0) + 1\n\n return num + 1\n }\n};\n" + }, + { + "_id": "66f925defdfb8e1665720ec8", + "questionid": 1021, + "title": "Most Beautiful Item for Each Query", + "slug": "most-beautiful-item-for-each-query", + "description": "You are given a 2D integer array items where items[i] = [pricei, beautyi] denotes the price and beauty of an item respectively. You are also given a 0-indexed integer array queries. For each queries[j], you want to determine the maximum beauty of an item whose price is less than or equal to queries[j]. If no such item exists, then the answer to this query is 0. Return an array answer of the same length as queries where answer[j] is the answer to the jth query. ", + "category": [ + "Array", + "Binary Search", + "Sorting" + ], + "complexity": "Medium", + "successrate": 48.4, + "totalsubmissions": 16619, + "totalaccepted": 8040, + "likes": 290, + "dislikes": 8, + "hints": "Can we process the queries in a smart order to avoid repeatedly checking the same items? How can we use the answer to a query for other queries?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "items = [[1,2],[3,2],[2,4],[5,6],[3,5]], queries = [1,2,3,4,5,6]", + "expected_output": "[2,4,5,5,6,6]", + "explanation": "- For queries[0]=1, [1,2] is the only item which has price <= 1. Hence, the answer for this query is 2.\n- For queries[1]=2, the items which can be considered are [1,2] and [2,4]. \n The maximum beauty among them is 4.\n- For queries[2]=3 and queries[3]=4, the items which can be considered are [1,2], [3,2], [2,4], and [3,5].\n The maximum beauty among them is 5.\n- For queries[4]=5 and queries[5]=6, all items can be considered.\n Hence, the answer for them is the maximum beauty of all items, i.e., 6." + }, + { + "example_num": 2, + "expected_input": "items = [[1,2],[1,2],[1,3],[1,4]], queries = [1]", + "expected_output": "[4]", + "explanation": "The price of every item is equal to 1, so we choose the item with the maximum beauty 4. \nNote that multiple items can have the same price and/or beauty." + }, + { + "example_num": 3, + "expected_input": "items = [[10,1000]], queries = [5]", + "expected_output": "[0]", + "explanation": "No item has a price less than or equal to 5, so no item can be chosen.\nHence, the answer to the query is 0." + } + ], + "solution": null + }, + { + "_id": "66f925defdfb8e1665720ec9", + "questionid": 1022, + "title": "Maximum Number of Tasks You Can Assign", + "slug": "maximum-number-of-tasks-you-can-assign", + "description": "You have n tasks and m workers. Each task has a strength requirement stored in a 0-indexed integer array tasks, with the ith task requiring tasks[i] strength to complete. The strength of each worker is stored in a 0-indexed integer array workers, with the jth worker having workers[j] strength. Each worker can only be assigned to a single task and must have a strength greater than or equal to the task's strength requirement (i.e., workers[j] >= tasks[i]). Additionally, you have pills magical pills that will increase a worker's strength by strength. You can decide which workers receive the magical pills, however, you may only give each worker at most one magical pill. Given the 0-indexed integer arrays tasks and workers and the integers pills and strength, return the maximum number of tasks that can be completed. ", + "category": [ + "Array", + "Binary Search", + "Greedy", + "Queue", + "Sorting", + "Monotonic Queue" + ], + "complexity": "Hard", + "successrate": 36.9, + "totalsubmissions": 12449, + "totalaccepted": 4592, + "likes": 233, + "dislikes": 12, + "hints": "Is it possible to assign the first k smallest tasks to the workers? How can you efficiently try every k?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "tasks = [3,2,1], workers = [0,3,3], pills = 1, strength = 1", + "expected_output": "3", + "explanation": "We can assign the magical pill and tasks as follows:\n- Give the magical pill to worker 0.\n- Assign worker 0 to task 2 (0 + 1 >= 1)\n- Assign worker 1 to task 1 (3 >= 2)\n- Assign worker 2 to task 0 (3 >= 3)" + }, + { + "example_num": 2, + "expected_input": "tasks = [5,4], workers = [0,0,0], pills = 1, strength = 5", + "expected_output": "1", + "explanation": "We can assign the magical pill and tasks as follows:\n- Give the magical pill to worker 0.\n- Assign worker 0 to task 0 (0 + 5 >= 5)" + }, + { + "example_num": 3, + "expected_input": "tasks = [10,15,30], workers = [0,10,10,10,10], pills = 3, strength = 10", + "expected_output": "2", + "explanation": "We can assign the magical pills and tasks as follows:\n- Give the magical pill to worker 0 and worker 1.\n- Assign worker 0 to task 0 (0 + 10 >= 10)\n- Assign worker 1 to task 1 (10 + 10 >= 15)\nThe last pill is not given because it will not make any worker strong enough for the last task." + } + ], + "solution": "//////////////////////////////////////////////Template/////////////////////////////////////////////////////////////\nfunction Bisect() {\n return { insort_right, insort_left, bisect_left, bisect_right }\n function insort_right(a, x, lo = 0, hi = null) {\n lo = bisect_right(a, x, lo, hi)\n a.splice(lo, 0, x)\n }\n function bisect_right(a, x, lo = 0, hi = null) {\n // > upper_bound\n if (lo < 0) throw new Error('lo must be non-negative')\n if (hi == null) hi = a.length\n while (lo < hi) {\n let mid = parseInt((lo + hi) / 2)\n x < a[mid] ? (hi = mid) : (lo = mid + 1)\n }\n return lo\n }\n function insort_left(a, x, lo = 0, hi = null) {\n lo = bisect_left(a, x, lo, hi)\n a.splice(lo, 0, x)\n }\n function bisect_left(a, x, lo = 0, hi = null) {\n // >= lower_bound\n if (lo < 0) throw new Error('lo must be non-negative')\n if (hi == null) hi = a.length\n while (lo < hi) {\n let mid = parseInt((lo + hi) / 2)\n a[mid] < x ? (lo = mid + 1) : (hi = mid)\n }\n return lo\n }\n}\n/**\n * @param {number[]} tasks\n * @param {number[]} workers\n * @param {number} pills\n * @param {number} strength\n * @return {number}\n */\nconst maxTaskAssign = function(tasks, workers, pills, strength) {\n tasks.sort((a, b) => a - b)\n workers.sort((a, b) => b - a)\n const m = tasks.length, n = workers.length\n const { min, floor } = Math\n let l = 0, r = min(n, m)\n while (l < r) {\n const mid = r - floor((r - l) / 2)\n if (check(mid)) l = mid\n else r = mid - 1\n }\n\n return l\n\n function check(k){\n const wArr = workers.slice(0, k), tArr = tasks.slice(0, k)\n let tries = pills, bs = new Bisect()\n wArr.reverse()\n tArr.reverse()\n \n for (let elem of tArr) {\n const place = bs.bisect_left(wArr, elem)\n if (place < wArr.length) {\n wArr.pop()\n } else if (tries > 0) {\n const place2 = bs.bisect_left(wArr, elem - strength)\n if (place2 < wArr.length) {\n wArr.splice(place2, 1)\n tries -= 1\n }\n } else return false\n }\n \n return wArr.length === 0\n }\n};\n" + }, + { + "_id": "66f925defdfb8e1665720ecc", + "questionid": 1025, + "title": "Count Vowel Substrings of a String", + "slug": "count-vowel-substrings-of-a-string", + "description": "A substring is a contiguous (non-empty) sequence of characters within a string. A vowel substring is a substring that only consists of vowels ('a', 'e', 'i', 'o', and 'u') and has all five vowels present in it. Given a string word, return the number of vowel substrings in word. ", + "category": [ + "Hash Table", + "String" + ], + "complexity": "Easy", + "successrate": 65.8, + "totalsubmissions": 24749, + "totalaccepted": 16283, + "likes": 362, + "dislikes": 109, + "hints": "While generating substrings starting at any index, do you need to continue generating larger substrings if you encounter a consonant? Can you store the count of characters to avoid generating substrings altogether?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "word = "aeiouu"", + "expected_output": "2", + "explanation": "The vowel substrings of word are as follows (underlined):\n- "aeiouu"\n- "aeiouu"" + }, + { + "example_num": 2, + "expected_input": "word = "unicornarihan"", + "expected_output": "0", + "explanation": "Not all 5 vowels are present, so there are no vowel substrings." + }, + { + "example_num": 3, + "expected_input": "word = "cuaieuouac"", + "expected_output": "7", + "explanation": "The vowel substrings of word are as follows (underlined):\n- "cuaieuouac"\n- "cuaieuouac"\n- "cuaieuouac"\n- "cuaieuouac"\n- "cuaieuouac"\n- "cuaieuouac"\n- "cuaieuouac"" + } + ], + "solution": "/**\n * @param {string} word\n * @return {number}\n */\nconst countVowelSubstrings = function(word) {\n let res = 0, n= word.length\n for(let i = 0; i < n - 1;i++) {\n for(let j = i + 1;j < n; j++) {\n if(valid(word, i, j)) res++\n }\n }\n \n return res\n \n function valid(s, i, j) {\n const set = new Set(['a', 'e', 'i', 'o','u'])\n const vis = new Set()\n for(let idx = i; idx <= j; idx++) {\n if(!set.has(s[idx])) return false\n else {\n vis.add(s[idx])\n }\n }\n // console.log(vis)\n return vis.size === 5\n }\n};\n" + }, + { + "_id": "66f925defdfb8e1665720ed0", + "questionid": 1029, + "title": "Reverse Nodes in Even Length Groups", + "slug": "reverse-nodes-in-even-length-groups", + "description": "You are given the head of a linked list. The nodes in the linked list are sequentially assigned to non-empty groups whose lengths form the sequence of the natural numbers (1, 2, 3, 4, ...). The length of a group is the number of nodes assigned to it. In other words, Note that the length of the last group may be less than or equal to 1 + the length of the second to last group. Reverse the nodes in each group with an even length, and return the head of the modified linked list. ", + "category": [ + "Linked List" + ], + "complexity": "Medium", + "successrate": 50.3, + "totalsubmissions": 18680, + "totalaccepted": 9388, + "likes": 177, + "dislikes": 189, + "hints": "Consider the list structure ...A \u2020\u2019 (B \u2020\u2019 ... \u2020\u2019 C) \u2020\u2019 D..., where the nodes between B and C (inclusive) form a group, A is the last node of the previous group, and D is the first node of the next group. How can you utilize this structure? Suppose you have B \u2020\u2019 ... \u2020\u2019 C reversed (because it was of even length) so that it is now C \u2020\u2019 ... \u2020\u2019 B. What references do you need to fix so that the transitions between the previous, current, and next groups are correct? A.next should be set to C, and B.next should be set to D. Once the current group is finished being modified, you need to find the new A, B, C, and D nodes for the next group. How can you use the old A, B, C, and D nodes to find the new ones? The new A is either the old B or old C depending on if the group was of even or odd length. The new B is always the old D. The new C and D can be found based on the new B and the next group's length. You can set the initial values of A, B, C, and D to A = null, B = head, C = head, D = head.next. Repeat the steps from the previous hints until D is null.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "head = [5,2,6,3,9,1,7,3,8,4]", + "expected_output": "[5,6,2,3,9,1,4,8,3,7]", + "explanation": "- The length of the first group is 1, which is odd, hence no reversal occurs.\n- The length of the second group is 2, which is even, hence the nodes are reversed.\n- The length of the third group is 3, which is odd, hence no reversal occurs.\n- The length of the last group is 4, which is even, hence the nodes are reversed." + }, + { + "example_num": 2, + "expected_input": "head = [1,1,0,6]", + "expected_output": "[1,0,1,6]", + "explanation": "- The length of the first group is 1. No reversal occurs.\n- The length of the second group is 2. The nodes are reversed.\n- The length of the last group is 1. No reversal occurs." + }, + { + "example_num": 3, + "expected_input": "head = [1,1,0,6,5]", + "expected_output": "[1,0,1,5,6]", + "explanation": "- The length of the first group is 1. No reversal occurs.\n- The length of the second group is 2. The nodes are reversed.\n- The length of the last group is 2. The nodes are reversed." + } + ], + "solution": "/**\n * Definition for singly-linked list.\n * function ListNode(val, next) {\n * this.val = (val===undefined ? 0 : val)\n * this.next = (next===undefined ? null : next)\n * }\n */\n/**\n * @param {ListNode} head\n * @return {ListNode}\n */\nconst reverseEvenLengthGroups = function(head) {\n const arr = []\n let cur = head\n while(cur) {\n arr.push(cur)\n cur = cur.next\n }\n let len = 1, res = []\n for(let i = 0, n = arr.length; i < n; ) {\n let backup = len, tmp = [], rev = len % 2 === 0\n while(len && i < n) {\n tmp.push(arr[i])\n i++\n len--\n }\n if((tmp.length % 2 === 0) ) {\n tmp.reverse()\n }\n res.push(...tmp)\n len = backup + 1\n }\n for(let i = 0; i < res.length; i++) {\n if(i === res.length - 1) res[i].next = null\n else {\n res[i].next = res[i + 1]\n }\n }\n \n return res[0]\n};\n" + }, + { + "_id": "66f925defdfb8e1665720ed3", + "questionid": 1032, + "title": "Find Subsequence of Length K With the Largest Sum", + "slug": "find-subsequence-of-length-k-with-the-largest-sum", + "description": "You are given an integer array nums and an integer k. You want to find a subsequence of nums of length k that has the largest sum. Return any such subsequence as an integer array of length k. A subsequence is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements. ", + "category": [ + "Array", + "Hash Table", + "Sorting", + "Heap (Priority Queue)" + ], + "complexity": "Easy", + "successrate": 43.6, + "totalsubmissions": 34727, + "totalaccepted": 15145, + "likes": 412, + "dislikes": 39, + "hints": "From a greedy perspective, what k elements should you pick? Could you sort the array while maintaining the index?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [2,1,3,3], k = 2", + "expected_output": "[3,3]", + "explanation": "The subsequence has the largest sum of 3 + 3 = 6." + }, + { + "example_num": 2, + "expected_input": "nums = [-1,-2,3,4], k = 3", + "expected_output": "[-1,3,4]", + "explanation": "The subsequence has the largest sum of -1 + 3 + 4 = 6." + }, + { + "example_num": 3, + "expected_input": "nums = [3,4,3,3], k = 2", + "expected_output": "[3,4]", + "explanation": "The subsequence has the largest sum of 3 + 4 = 7. \nAnother possible subsequence is [4, 3]." + } + ], + "solution": null + }, + { + "_id": "66f925defdfb8e1665720ed7", + "questionid": 1036, + "title": "Removing Minimum and Maximum From Array", + "slug": "removing-minimum-and-maximum-from-array", + "description": "You are given a 0-indexed array of distinct integers nums. There is an element in nums that has the lowest value and an element that has the highest value. We call them the minimum and maximum respectively. Your goal is to remove both these elements from the array. A deletion is defined as either removing an element from the front of the array or removing an element from the back of the array. Return the minimum number of deletions it would take to remove both the minimum and maximum element from the array. ", + "category": [ + "Array", + "Greedy" + ], + "complexity": "Medium", + "successrate": 57.6, + "totalsubmissions": 28027, + "totalaccepted": 16157, + "likes": 314, + "dislikes": 16, + "hints": "There can only be three scenarios for deletions such that both minimum and maximum elements are removed: Scenario 1: Both elements are removed by only deleting from the front. Scenario 2: Both elements are removed by only deleting from the back. Scenario 3: Delete from the front to remove one of the elements, and delete from the back to remove the other element. Compare which of the three scenarios results in the minimum number of moves.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [2,10,7,5,4,1,8,6]", + "expected_output": "5", + "explanation": "The minimum element in the array is nums[5], which is 1.\nThe maximum element in the array is nums[1], which is 10.\nWe can remove both the minimum and maximum by removing 2 elements from the front and 3 elements from the back.\nThis results in 2 + 3 = 5 deletions, which is the minimum number possible." + }, + { + "example_num": 2, + "expected_input": "nums = [0,-4,19,1,8,-2,-3,5]", + "expected_output": "3", + "explanation": "The minimum element in the array is nums[1], which is -4.\nThe maximum element in the array is nums[2], which is 19.\nWe can remove both the minimum and maximum by removing 3 elements from the front.\nThis results in only 3 deletions, which is the minimum number possible." + }, + { + "example_num": 3, + "expected_input": "nums = [101]", + "expected_output": "1", + "explanation": "There is only one element in the array, which makes it both the minimum and maximum element.\nWe can remove it with 1 deletion." + } + ], + "solution": "/**\n * @param {number[]} nums\n * @return {number}\n */\nconst minimumDeletions = function(nums) {\n let mi = Infinity, ma = -Infinity\n let mii = -1, mai = -1\n const { max, min, abs } = Math, n = nums.length\n for(let i = 0; i < n; i++) {\n const e = nums[i]\n if(e < mi) {\n mi = e\n mii = i\n }\n if(e > ma) {\n ma = e\n mai = i\n }\n }\n \n const disMi = abs(mii + 1, n - mii)\n const disMa = abs(mai + 1, n - mai)\n let res = 0\n let lmi = min(mii, mai), lma = max(mii, mai)\n \n res += min(lmi + 1 + n - lma, lma + 1, n - lmi)\n \n \n return res\n};\n" + }, + { + "_id": "66f925defdfb8e1665720ed8", + "questionid": 1037, + "title": "Find All People With Secret", + "slug": "find-all-people-with-secret", + "description": "You are given an integer n indicating there are n people numbered from 0 to n - 1. You are also given a 0-indexed 2D integer array meetings where meetings[i] = [xi, yi, timei] indicates that person xi and person yi have a meeting at timei. A person may attend multiple meetings at the same time. Finally, you are given an integer firstPerson. Person 0 has a secret and initially shares the secret with a person firstPerson at time 0. This secret is then shared every time a meeting takes place with a person that has the secret. More formally, for every meeting, if a person xi has the secret at timei, then they will share the secret with person yi, and vice versa. The secrets are shared instantaneously. That is, a person may receive the secret and share it with people in other meetings within the same time frame. Return a list of all the people that have the secret after all the meetings have taken place. You may return the answer in any order. ", + "category": [ + "Depth-First Search", + "Breadth-First Search", + "Union Find", + "Graph", + "Sorting" + ], + "complexity": "Hard", + "successrate": 32.8, + "totalsubmissions": 38441, + "totalaccepted": 12595, + "likes": 423, + "dislikes": 20, + "hints": "Could you model all the meetings happening at the same time as a graph? What data structure can you use to efficiently share the secret? You can use the union-find data structure to quickly determine who knows the secret and share the secret.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 6, meetings = [[1,2,5],[2,3,8],[1,5,10]], firstPerson = 1", + "expected_output": "[0,1,2,3,5]\nExplanation:\nAt time 0, person 0 shares the secret with person 1.\nAt time 5, person 1 shares the secret with person 2.\nAt time 8, person 2 shares the secret with person 3.\nAt time 10, person 1 shares the secret with person 5.\u200b\u200b\u200b\u200b\nThus, people 0, 1, 2, 3, and 5 know the secret after all the meetings.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "n = 4, meetings = [[3,1,3],[1,2,2],[0,3,3]], firstPerson = 3", + "expected_output": "[0,1,3]", + "explanation": "At time 0, person 0 shares the secret with person 3.\nAt time 2, neither person 1 nor person 2 know the secret.\nAt time 3, person 3 shares the secret with person 0 and person 1.\nThus, people 0, 1, and 3 know the secret after all the meetings." + }, + { + "example_num": 3, + "expected_input": "n = 5, meetings = [[3,4,2],[1,2,1],[2,3,1]], firstPerson = 1", + "expected_output": "[0,1,2,3,4]", + "explanation": "At time 0, person 0 shares the secret with person 1.\nAt time 1, person 1 shares the secret with person 2, and person 2 shares the secret with person 3.\nNote that person 2 can share the secret at the same time as receiving it.\nAt time 2, person 3 shares the secret with person 4.\nThus, people 0, 1, 2, 3, and 4 know the secret after all the meetings." + } + ], + "solution": "/**\n * @param {number} n\n * @param {number[][]} meetings\n * @param {number} firstPerson\n * @return {number[]}\n */\nconst findAllPeople = function(n, meetings, firstPerson) {\n meetings.sort((a, b) => a[2] - b[2])\n const uf = new UnionFind(n);\n uf.connect(0, firstPerson);\n let ppl = [];\n for (let i = 0, len = meetings.length; i < len; ) {\n ppl = [];\n let time = meetings[i][2];\n while (i < len && meetings[i][2] === time) {\n uf.connect(meetings[i][0], meetings[i][1]);\n ppl.push(meetings[i][0]);\n ppl.push(meetings[i][1]);\n i++\n }\n for (let n of ppl) {\n if (!uf.connected(0, n)) uf.reset(n);\n }\n }\n let ans = [];\n for (let i = 0; i < n; ++i) {\n if (uf.connected(0, i)) ans.push(i);\n }\n return ans;\n};\n\nclass UnionFind {\n constructor(n) {\n this.arr = Array(n).fill(null)\n this.arr.forEach((e, i, arr) => arr[i] = i)\n }\n connect(a, b) {\n this.arr[this.find(a)] = this.find(this.arr[b])\n }\n find(a) {\n return this.arr[a] === a ? a : (this.arr[a] = this.find(this.arr[a]))\n }\n connected(a, b) {\n return this.find(a) === this.find(b)\n }\n reset(a) {\n this.arr[a] = a\n }\n}\n\n// another\n\n/**\n * @param {number} n\n * @param {number[][]} meetings\n * @param {number} firstPerson\n * @return {number[]}\n */\nconst findAllPeople = function(n, meetings, firstPerson) {\n meetings.sort((a, b) => a[2] - b[2])\n const shared = new Set([0, firstPerson])\n \n let start = new Set(), links = {}\n for(let i = 0, len = meetings.length; i < len; i++) {\n const [x,y,t] = meetings[i]\n if(i > 0 && t !== meetings[i - 1][2]) {\n bfs(start, links)\n start = new Set()\n links = {}\n }\n if(shared.has(x)) start.add(x)\n if(shared.has(y)) start.add(y)\n if(links[x] == null) links[x] = []\n if(links[y] == null) links[y] = []\n links[x].push(y)\n links[y].push(x)\n }\n \n bfs(start, links)\n return Array.from(shared)\n \n function bfs(start, links) {\n const visited = new Set()\n while(start.size) {\n const it = start[Symbol.iterator]()\n const cur = it.next().value\n start.delete(cur)\n visited.add(cur)\n shared.add(cur)\n for(let e of (links[cur] || [])) {\n if(!visited.has(e)) start.add(e)\n }\n }\n }\n};\n" + }, + { + "_id": "66f925defdfb8e1665720ed9", + "questionid": 1038, + "title": "Delete the Middle Node of a Linked List", + "slug": "delete-the-middle-node-of-a-linked-list", + "description": "You are given the head of a linked list. Delete the middle node, and return the head of the modified linked list. The middle node of a linked list of size n is the n / 2 th node from the start using 0-based indexing, where x denotes the largest integer less than or equal to x. ", + "category": [ + "Linked List", + "Two Pointers" + ], + "complexity": "Medium", + "successrate": 57.2, + "totalsubmissions": 72447, + "totalaccepted": 41449, + "likes": 693, + "dislikes": 22, + "hints": "If a point with a speed s moves n units in a given time, a point with speed 2 * s will move 2 * n units at the same time. Can you use this to find the middle node of a linked list? If you are given the middle node, the node before it, and the node after it, how can you modify the linked list?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "head = [1,3,4,7,1,2,6]", + "expected_output": "[1,3,4,1,2,6]", + "explanation": "The above figure represents the given linked list. The indices of the nodes are written below.\nSince n = 7, node 3 with value 7 is the middle node, which is marked in red.\nWe return the new list after removing this node." + }, + { + "example_num": 2, + "expected_input": "head = [1,2,3,4]", + "expected_output": "[1,2,4]", + "explanation": "The above figure represents the given linked list.\nFor n = 4, node 2 with value 3 is the middle node, which is marked in red." + }, + { + "example_num": 3, + "expected_input": "head = [2,1]", + "expected_output": "[2]", + "explanation": "The above figure represents the given linked list.\nFor n = 2, node 1 with value 1 is the middle node, which is marked in red.\nNode 0 with value 2 is the only node remaining after removing node 1." + } + ], + "solution": "/**\n * Definition for singly-linked list.\n * function ListNode(val, next) {\n * this.val = (val===undefined ? 0 : val)\n * this.next = (next===undefined ? null : next)\n * }\n */\n/**\n * @param {ListNode} head\n * @return {ListNode}\n */\nconst deleteMiddle = function(head) {\n if(head == null) return head\n const dummy = new ListNode(null, head)\n let n = 0, cur = head\n while(cur) {\n n++\n cur = cur.next\n }\n if(n === 1) return null\n const mid = Math.floor(n / 2)\n cur = dummy.next\n let pre = dummy \n for(let i = 0; i < n; i++) {\n if(i === mid - 1) {\n pre = cur\n // pre.next = cur.next.next\n }\n if(i === mid) {\n pre.next = cur.next\n }\n if(i > mid) break\n cur = cur.next\n }\n return dummy.next\n};\n" + }, + { + "_id": "66f925defdfb8e1665720edb", + "questionid": 1040, + "title": "Find All Possible Recipes from Given Supplies", + "slug": "find-all-possible-recipes-from-given-supplies", + "description": "You have information about n different recipes. You are given a string array recipes and a 2D string array ingredients. The ith recipe has the name recipes[i], and you can create it if you have all the needed ingredients from ingredients[i]. Ingredients to a recipe may need to be created from other recipes, i.e., ingredients[i] may contain a string that is in recipes. You are also given a string array supplies containing all the ingredients that you initially have, and you have an infinite supply of all of them. Return a list of all the recipes that you can create. You may return the answer in any order. Note that two recipes may contain each other in their ingredients. ", + "category": [ + "Array", + "Hash Table", + "String", + "Graph", + "Topological Sort" + ], + "complexity": "Medium", + "successrate": 42.7, + "totalsubmissions": 49865, + "totalaccepted": 21290, + "likes": 600, + "dislikes": 46, + "hints": "Can we use a data structure to quickly query whether we have a certain ingredient? Once we verify that we can make a recipe, we can add it to our ingredient data structure. We can then check if we can make more recipes as a result of this.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "recipes = ["bread"], ingredients = [["yeast","flour"]], supplies = ["yeast","flour","corn"]", + "expected_output": "["bread"]", + "explanation": "We can create "bread" since we have the ingredients "yeast" and "flour"." + }, + { + "example_num": 2, + "expected_input": "recipes = ["bread","sandwich"], ingredients = [["yeast","flour"],["bread","meat"]], supplies = ["yeast","flour","meat"]", + "expected_output": "["bread","sandwich"]", + "explanation": "We can create "bread" since we have the ingredients "yeast" and "flour".\nWe can create "sandwich" since we have the ingredient "meat" and can create the ingredient "bread"." + }, + { + "example_num": 3, + "expected_input": "recipes = ["bread","sandwich","burger"], ingredients = [["yeast","flour"],["bread","meat"],["sandwich","meat","bread"]], supplies = ["yeast","flour","meat"]", + "expected_output": "["bread","sandwich","burger"]", + "explanation": "We can create "bread" since we have the ingredients "yeast" and "flour".\nWe can create "sandwich" since we have the ingredient "meat" and can create the ingredient "bread".\nWe can create "burger" since we have the ingredient "meat" and can create the ingredients "bread" and "sandwich"." + } + ], + "solution": "/**\n * @param {string[]} recipes\n * @param {string[][]} ingredients\n * @param {string[]} supplies\n * @return {string[]}\n */\nconst findAllRecipes = function(recipes, ingredients, supplies) {\n const set = new Set(supplies), res = [], graph = {}, n = recipes.length\n const inDegree = {}\n for(let x of recipes) inDegree[x] = 0\n for(let i = 0; i < n; i++) {\n for(let j = 0; j < ingredients[i].length; j++) {\n const ing = ingredients[i][j]\n if(!set.has(ing)) {\n if (graph[ing] == null) graph[ing] = []\n graph[ing].push(recipes[i])\n inDegree[recipes[i]]++\n }\n }\n }\n // Kahn's Algorithm\n const q = []\n for(let x in inDegree) {\n if (inDegree[x] === 0) q.push(x)\n }\n while(q.length) {\n const len = q.length\n for(let i = 0; i < len; i++) {\n const cur = q.pop()\n res.push(cur)\n for(let next of (graph[cur] || [])) {\n inDegree[next]--\n if(inDegree[next] === 0) {\n q.push(next)\n }\n }\n }\n }\n return res\n};\n\n// another\n\n/**\n * @param {string[]} recipes\n * @param {string[][]} ingredients\n * @param {string[]} supplies\n * @return {string[]}\n */\nconst findAllRecipes = function(recipes, ingredients, supplies) {\n const graph = {}\n const n = recipes.length\n\n const inDegree = {}\n supplies = new Set(supplies)\n for(const e of recipes) inDegree[e] = 0\n\n let q = []\n for(let i = 0; i < n; i++) {\n const rec = recipes[i]\n for(let e of ingredients[i]) {\n if(!supplies.has(e)) {\n if(graph[e] == null) graph[e] = []\n graph[e].push(rec)\n inDegree[rec]++\n }\n }\n }\n // console.log(inDegree)\n for(let i = 0; i < n; i++) {\n if(inDegree[recipes[i]] === 0) {\n q.push(recipes[i])\n }\n }\n \n // console.log(q)\n const res = [] \n while(q.length) {\n const size = q.length\n const nxt = []\n \n for(let i = 0; i < size; i++) {\n const cur = q[i]\n res.push(cur)\n for(const e of (graph[cur] || [])) {\n inDegree[e]--\n if(inDegree[e] === 0) nxt.push(e)\n }\n }\n \n q = nxt\n }\n\n return res\n};\n" + }, + { + "_id": "66f925defdfb8e1665720edf", + "questionid": 1044, + "title": "Adding Spaces to a String", + "slug": "adding-spaces-to-a-string", + "description": "You are given a 0-indexed string s and a 0-indexed integer array spaces that describes the indices in the original string where spaces will be added. Each space should be inserted before the character at the given index. Return the modified string after the spaces have been added. ", + "category": [ + "Array", + "String", + "Simulation" + ], + "complexity": "Medium", + "successrate": 56, + "totalsubmissions": 36845, + "totalaccepted": 20644, + "likes": 248, + "dislikes": 26, + "hints": "Create a new string, initially empty, as the modified string. Iterate through the original string and append each character of the original string to the new string. However, each time you reach a character that requires a space before it, append a space before appending the character. Since the array of indices for the space locations is sorted, use a pointer to keep track of the next index to place a space. Only increment the pointer once a space has been appended. Ensure that your append operation can be done in O(1).", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "LeetcodeHelpsMeLearn", spaces = [8,13,15]", + "expected_output": ""Leetcode Helps Me Learn"", + "explanation": "The indices 8, 13, and 15 correspond to the underlined characters in "LeetcodeHelpsMeLearn".\nWe then place spaces before those characters." + }, + { + "example_num": 2, + "expected_input": "s = "icodeinpython", spaces = [1,5,7,9]", + "expected_output": ""i code in py thon"", + "explanation": "The indices 1, 5, 7, and 9 correspond to the underlined characters in "icodeinpython".\nWe then place spaces before those characters." + }, + { + "example_num": 3, + "expected_input": "s = "spacing", spaces = [0,1,2,3,4,5,6]", + "expected_output": "" s p a c i n g"", + "explanation": "We are also able to place spaces before the first character of the string." + } + ], + "solution": "/**\n * @param {string} s\n * @param {number[]} spaces\n * @return {string}\n */\nvar addSpaces = function(s, spaces) {\n let res = '', j = 0, idx = spaces[j]\n for(let i = 0, n = s.length; i < n; i++) {\n if(i === idx) {\n res += ' '\n j++\n idx = spaces[j]\n }\n res += s[i]\n }\n \n return res\n};\n" + }, + { + "_id": "66f925defdfb8e1665720ee2", + "questionid": 1047, + "title": "Maximum Twin Sum of a Linked List", + "slug": "maximum-twin-sum-of-a-linked-list", + "description": "In a linked list of size n, where n is even, the ith node (0-indexed) of the linked list is known as the twin of the (n-1-i)th node, if 0 <= i <= (n / 2) - 1. The twin sum is defined as the sum of a node and its twin. Given the head of a linked list with even length, return the maximum twin sum of the linked list. ", + "category": [ + "Linked List", + "Two Pointers", + "Stack" + ], + "complexity": "Medium", + "successrate": 82.2, + "totalsubmissions": 34349, + "totalaccepted": 28247, + "likes": 485, + "dislikes": 21, + "hints": "How can \"reversing\" a part of the linked list help find the answer? We know that the nodes of the first half are twins of nodes in the second half, so try dividing the linked list in half and reverse the second half. How can two pointers be used to find every twin sum optimally? Use two different pointers pointing to the first nodes of the two halves of the linked list. The second pointer will point to the first node of the reversed half, which is the (n-1-i)th node in the original linked list. By moving both pointers forward at the same time, we find all twin sums.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "head = [5,4,2,1]", + "expected_output": "6", + "explanation": "Nodes 0 and 1 are the twins of nodes 3 and 2, respectively. All have twin sum = 6.\nThere are no other nodes with twins in the linked list.\nThus, the maximum twin sum of the linked list is 6." + }, + { + "example_num": 2, + "expected_input": "head = [4,2,2,3]", + "expected_output": "7", + "explanation": "The nodes with twins present in this linked list are:\n- Node 0 is the twin of node 3 having a twin sum of 4 + 3 = 7.\n- Node 1 is the twin of node 2 having a twin sum of 2 + 2 = 4.\nThus, the maximum twin sum of the linked list is max(7, 4) = 7." + }, + { + "example_num": 3, + "expected_input": "head = [1,100000]", + "expected_output": "100001", + "explanation": "There is only one node with a twin in the linked list having twin sum of 1 + 100000 = 100001." + } + ], + "solution": "/**\n * Definition for singly-linked list.\n * function ListNode(val, next) {\n * this.val = (val===undefined ? 0 : val)\n * this.next = (next===undefined ? null : next)\n * }\n */\n/**\n * @param {ListNode} head\n * @return {number}\n */\nconst pairSum = function(head) {\n let slow = head, fast = head\n while(fast && fast.next) {\n slow = slow.next\n fast = fast.next.next\n }\n // reverse\n let next = null, pre = null\n while(slow) {\n next = slow.next\n slow.next = pre\n pre = slow\n slow = next\n }\n\n let res = 0\n while(pre) {\n res = Math.max(res, pre.val + head.val)\n pre = pre.next\n head = head.next\n }\n \n return res\n};\n\n// another\n\n/**\n * Definition for singly-linked list.\n * function ListNode(val, next) {\n * this.val = (val===undefined ? 0 : val)\n * this.next = (next===undefined ? null : next)\n * }\n */\n/**\n * @param {ListNode} head\n * @return {number}\n */\nconst pairSum = function(head) {\n const arr = []\n let cur = head\n \n while(cur) {\n arr.push(cur.val)\n cur = cur.next\n }\n \n let res = 0\n for(let i = 0, n = arr.length; i < n / 2; i++) {\n res = Math.max(res, arr[i] + arr[n - 1 - i])\n }\n \n return res\n};\n" + }, + { + "_id": "66f925defdfb8e1665720ee4", + "questionid": 1049, + "title": "A Number After a Double Reversal", + "slug": "a-number-after-a-double-reversal", + "description": "Reversing an integer means to reverse all its digits. Given an integer num, reverse num to get reversed1, then reverse reversed1 to get reversed2. Return true if reversed2 equals num. Otherwise return false. ", + "category": [ + "Math" + ], + "complexity": "Easy", + "successrate": 76.9, + "totalsubmissions": 34908, + "totalaccepted": 26859, + "likes": 224, + "dislikes": 14, + "hints": "Other than the number 0 itself, any number that ends with 0 would lose some digits permanently when reversed.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "num = 526", + "expected_output": "true", + "explanation": "Reverse num to get 625, then reverse 625 to get 526, which equals num." + }, + { + "example_num": 2, + "expected_input": "num = 1800", + "expected_output": "false", + "explanation": "Reverse num to get 81, then reverse 81 to get 18, which does not equal num." + }, + { + "example_num": 3, + "expected_input": "num = 0", + "expected_output": "true", + "explanation": "Reverse num to get 0, then reverse 0 to get 0, which equals num." + } + ], + "solution": "/**\n * @param {number} num\n * @return {boolean}\n */\nvar isSameAfterReversals = function(num) {\n if(('' +num).length === 1) return true\n const tmp = (''+num).endsWith('0')\n return !tmp\n};\n" + }, + { + "_id": "66f925defdfb8e1665720eea", + "questionid": 1055, + "title": "Number of Ways to Divide a Long Corridor", + "slug": "number-of-ways-to-divide-a-long-corridor", + "description": "Along a long library corridor, there is a line of seats and decorative plants. You are given a 0-indexed string corridor of length n consisting of letters 'S' and 'P' where each 'S' represents a seat and each 'P' represents a plant. One room divider has already been installed to the left of index 0, and another to the right of index n - 1. Additional room dividers can be installed. For each position between indices i - 1 and i (1 <= i <= n - 1), at most one divider can be installed. Divide the corridor into non-overlapping sections, where each section has exactly two seats with any number of plants. There may be multiple ways to perform the division. Two ways are different if there is a position with a room divider installed in the first way but not in the second way. Return the number of ways to divide the corridor. Since the answer may be very large, return it modulo 109 + 7. If there is no way, return 0. ", + "category": [ + "Math", + "String", + "Dynamic Programming" + ], + "complexity": "Hard", + "successrate": 40, + "totalsubmissions": 16228, + "totalaccepted": 6485, + "likes": 178, + "dislikes": 17, + "hints": "Divide the corridor into segments. Each segment has two seats, starts precisely with one seat, and ends precisely with the other seat. How many dividers can you install between two adjacent segments? You must install precisely one. Otherwise, you would have created a section with not exactly two seats. If there are k plants between two adjacent segments, there are k + 1 positions (ways) you could install the divider you must install. The problem now becomes: Find the product of all possible positions between every two adjacent segments.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "corridor = "SSPPSPS"", + "expected_output": "3", + "explanation": "There are 3 different ways to divide the corridor.\nThe black bars in the above image indicate the two room dividers already installed.\nNote that in each of the ways, each section has exactly two seats." + }, + { + "example_num": 2, + "expected_input": "corridor = "PPSPSP"", + "expected_output": "1", + "explanation": "There is only 1 way to divide the corridor, by not installing any additional dividers.\nInstalling any would create some section that does not have exactly two seats." + }, + { + "example_num": 3, + "expected_input": "corridor = "S"", + "expected_output": "0", + "explanation": "There is no way to divide the corridor because there will always be a section that does not have exactly two seats." + } + ], + "solution": null + }, + { + "_id": "66f925defdfb8e1665720eec", + "questionid": 1057, + "title": "Minimum Swaps to Group All 1's Together II", + "slug": "minimum-swaps-to-group-all-1s-together-ii", + "description": "A swap is defined as taking two distinct positions in an array and swapping the values in them. A circular array is defined as an array where we consider the first element and the last element to be adjacent. Given a binary circular array nums, return the minimum number of swaps required to group all 1's present in the array together at any location. ", + "category": [ + "Array", + "Sliding Window" + ], + "complexity": "Medium", + "successrate": 47.6, + "totalsubmissions": 27620, + "totalaccepted": 13137, + "likes": 547, + "dislikes": 6, + "hints": "Notice that the number of 1\u20ac\u2122s to be grouped together is fixed. It is the number of 1's the whole array has. Call this number total. We should then check for every subarray of size total (possibly wrapped around), how many swaps are required to have the subarray be all 1\u20ac\u2122s. The number of swaps required is the number of 0\u20ac\u2122s in the subarray. To eliminate the circular property of the array, we can append the original array to itself. Then, we check each subarray of length total. How do we avoid recounting the number of 0\u20ac\u2122s in the subarray each time? The Sliding Window technique can help.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [0,1,0,1,1,0,0]", + "expected_output": "1", + "explanation": "Here are a few of the ways to group all the 1's together:\n[0,0,1,1,1,0,0] using 1 swap.\n[0,1,1,1,0,0,0] using 1 swap.\n[1,1,0,0,0,0,1] using 2 swaps (using the circular property of the array).\nThere is no way to group all 1's together with 0 swaps.\nThus, the minimum number of swaps required is 1." + }, + { + "example_num": 2, + "expected_input": "nums = [0,1,1,1,0,0,1,1,0]", + "expected_output": "2", + "explanation": "Here are a few of the ways to group all the 1's together:\n[1,1,1,0,0,0,0,1,1] using 2 swaps (using the circular property of the array).\n[1,1,1,1,1,0,0,0,0] using 2 swaps.\nThere is no way to group all 1's together with 0 or 1 swaps.\nThus, the minimum number of swaps required is 2." + }, + { + "example_num": 3, + "expected_input": "nums = [1,1,0,0,1]", + "expected_output": "0", + "explanation": "All the 1's are already grouped together due to the circular property of the array.\nThus, the minimum number of swaps required is 0." + } + ], + "solution": "/**\n * @param {number[]} nums\n * @return {number}\n */\nvar minSwaps = function(nums) {\n let one = 0;\n for (let i = 0; i < nums.length; i++) {\n if (nums[i] == 1)\n one++;\n }\n let maxOne = 0;\n for (let i = 0; i < one; i++) {\n if (nums[i] == 1)\n maxOne++;\n }\n let max = maxOne;\n for (let i = 1; i < nums.length; i++) {\n if (nums[i - 1] == 1)\n maxOne--;\n if (nums[(i + one - 1) % nums.length] == 1)\n maxOne++;\n if (maxOne > max)\n max = maxOne;\n }\n return one - max;\n \n};\n" + }, + { + "_id": "66f925defdfb8e1665720ef9", + "questionid": 1070, + "title": "Counting Words With a Given Prefix", + "slug": "counting-words-with-a-given-prefix", + "description": "You are given an array of strings words and a string pref. Return the number of strings in words that contain pref as a prefix. A prefix of a string s is any leading contiguous substring of s. ", + "category": [ + "Array", + "String" + ], + "complexity": "Easy", + "successrate": 77.7, + "totalsubmissions": 35648, + "totalaccepted": 27707, + "likes": 190, + "dislikes": 3, + "hints": "Go through each word in words and increment the answer if pref is a prefix of the word.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "words = ["pay","attention","practice","attend"], pref = "at"", + "expected_output": "2", + "explanation": "The 2 strings that contain "at" as a prefix are: "attention" and "attend"." + }, + { + "example_num": 2, + "expected_input": "words = ["leetcode","win","loops","success"], pref = "code"", + "expected_output": "0", + "explanation": "There are no strings that contain "code" as a prefix." + } + ], + "solution": null + }, + { + "_id": "66f925defdfb8e1665720efb", + "questionid": 1072, + "title": "Minimum Time to Complete Trips", + "slug": "minimum-time-to-complete-trips", + "description": "You are given an array time where time[i] denotes the time taken by the ith bus to complete one trip. Each bus can make multiple trips successively; that is, the next trip can start immediately after completing the current trip. Also, each bus operates independently; that is, the trips of one bus do not influence the trips of any other bus. You are also given an integer totalTrips, which denotes the number of trips all buses should make in total. Return the minimum time required for all buses to complete at least totalTrips trips. ", + "category": [ + "Array", + "Binary Search" + ], + "complexity": "Medium", + "successrate": 29.6, + "totalsubmissions": 64231, + "totalaccepted": 19043, + "likes": 517, + "dislikes": 24, + "hints": "For a given amount of time, how can we count the total number of trips completed by all buses within that time? Consider using binary search.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "time = [1,2,3], totalTrips = 5", + "expected_output": "3", + "explanation": "- At time t = 1, the number of trips completed by each bus are [1,0,0]. \n The total number of trips completed is 1 + 0 + 0 = 1.\n- At time t = 2, the number of trips completed by each bus are [2,1,0]. \n The total number of trips completed is 2 + 1 + 0 = 3.\n- At time t = 3, the number of trips completed by each bus are [3,1,1]. \n The total number of trips completed is 3 + 1 + 1 = 5.\nSo the minimum time needed for all buses to complete at least 5 trips is 3." + }, + { + "example_num": 2, + "expected_input": "time = [2], totalTrips = 1", + "expected_output": "2", + "explanation": "There is only one bus, and it will complete its first trip at t = 2.\nSo the minimum time needed to complete 1 trip is 2." + } + ], + "solution": null + }, + { + "_id": "66f925defdfb8e1665720efe", + "questionid": 1075, + "title": "Merge Nodes in Between Zeros", + "slug": "merge-nodes-in-between-zeros", + "description": "You are given the head of a linked list, which contains a series of integers separated by 0's. The beginning and end of the linked list will have Node.val == 0. For every two consecutive 0's, merge all the nodes lying in between them into a single node whose value is the sum of all the merged nodes. The modified list should not contain any 0's. Return the head of the modified linked list. ", + "category": [ + "Linked List", + "Simulation" + ], + "complexity": "Medium", + "successrate": 87.1, + "totalsubmissions": 31121, + "totalaccepted": 27114, + "likes": 380, + "dislikes": 9, + "hints": "How can you use two pointers to modify the original list into the new list? Have a pointer traverse the entire linked list, while another pointer looks at a node that is currently being modified. Keep on summing the values of the nodes between the traversal pointer and the modifying pointer until the former comes across a \u20ac\u02dc0\u20ac\u2122. In that case, the modifying pointer is incremented to modify the next node. Do not forget to have the next pointer of the final node of the modified list point to null.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "head = [0,3,1,0,4,5,2,0]", + "expected_output": "[4,11]", + "explanation": "The above figure represents the given linked list. The modified list contains\n- The sum of the nodes marked in green: 3 + 1 = 4.\n- The sum of the nodes marked in red: 4 + 5 + 2 = 11." + }, + { + "example_num": 2, + "expected_input": "head = [0,1,0,3,0,2,2,0]", + "expected_output": "[1,3,4]", + "explanation": "The above figure represents the given linked list. The modified list contains\n- The sum of the nodes marked in green: 1 = 1.\n- The sum of the nodes marked in red: 3 = 3.\n- The sum of the nodes marked in yellow: 2 + 2 = 4." + } + ], + "solution": "/**\n * Definition for singly-linked list.\n * function ListNode(val, next) {\n * this.val = (val===undefined ? 0 : val)\n * this.next = (next===undefined ? null : next)\n * }\n */\n/**\n * @param {ListNode} head\n * @return {ListNode}\n */\nvar mergeNodes = function(head) {\n const dummy = new ListNode()\n const arr = []\n let cur = head\n while(cur) {\n arr.push(cur)\n cur = cur.next\n }\n let tail = dummy\n let lastIdx = 0, sum = 0\n if(arr.length) {\n for(let i = 1; i < arr.length; i++) {\n const tmp = arr[i]\n if(tmp.val === 0 && sum !== 0) {\n lastIdx = i\n tail.next = new ListNode(sum)\n tail = tail.next\n sum = 0\n } else {\n sum += tmp.val\n }\n }\n }\n \n return dummy.next\n};\n" + }, + { + "_id": "66f925defdfb8e1665720f05", + "questionid": 1082, + "title": "Longest Substring of One Repeating Character", + "slug": "longest-substring-of-one-repeating-character", + "description": "You are given a 0-indexed string s. You are also given a 0-indexed string queryCharacters of length k and a 0-indexed array of integer indices queryIndices of length k, both of which are used to describe k queries. The ith query updates the character in s at index queryIndices[i] to the character queryCharacters[i]. Return an array lengths of length k where lengths[i] is the length of the longest substring of s consisting of only one repeating character after the ith query is performed. ", + "category": [ + "Array", + "String", + "Segment Tree", + "Ordered Set" + ], + "complexity": "Hard", + "successrate": 28.5, + "totalsubmissions": 6683, + "totalaccepted": 1906, + "likes": 97, + "dislikes": 66, + "hints": "Use a segment tree to perform fast point updates and range queries. We need each segment tree node to store the length of the longest substring of that segment consisting of only 1 repeating character. We will also have each segment tree node store the leftmost and rightmost character of the segment, the max length of a prefix substring consisting of only 1 repeating character, and the max length of a suffix substring consisting of only 1 repeating character. Use this information to properly merge the two segment tree nodes together.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "babacc", queryCharacters = "bcb", queryIndices = [1,3,3]", + "expected_output": "[3,3,4]", + "explanation": "- 1st query updates s = "bbbacc". The longest substring consisting of one repeating character is "bbb" with length 3.\n- 2nd query updates s = "bbbccc". \n The longest substring consisting of one repeating character can be "bbb" or "ccc" with length 3.\n- 3rd query updates s = "bbbbcc". The longest substring consisting of one repeating character is "bbbb" with length 4.\nThus, we return [3,3,4]." + }, + { + "example_num": 2, + "expected_input": "s = "abyzz", queryCharacters = "aa", queryIndices = [2,1]", + "expected_output": "[2,3]", + "explanation": "- 1st query updates s = "abazz". The longest substring consisting of one repeating character is "zz" with length 2.\n- 2nd query updates s = "aaazz". The longest substring consisting of one repeating character is "aaa" with length 3.\nThus, we return [2,3]." + } + ], + "solution": "/**\n * @param {string} s\n * @param {string} queryCharacters\n * @param {number[]} queryIndices\n * @return {number[]}\n */\nconst longestRepeating = function(s, queryCharacters, queryIndices) {\n let n = queryCharacters.length\n const ans = []\n\n const segmentTree = new SegmentTree(s)\n for (let i = 0; i < n; i++) {\n segmentTree.update(1, 0, s.length - 1, queryIndices[i], queryCharacters[i])\n ans.push(segmentTree.getMax())\n }\n\n return ans\n};\n\nclass TreeNode {\n constructor(max, preStart, preEnd, sufStart, sufEnd) {\n this.max = max\n this.preStart = preStart\n this.preEnd = preEnd\n this.sufStart = sufStart\n this.sufEnd = sufEnd\n }\n}\n\nclass SegmentTree {\n constructor(s) {\n this.n = s.length\n this.s = s.split('')\n this.tree = new Array(4 * s.length)\n this.build(s, 1, 0, s.length - 1)\n }\n\n build(s, treeIndex, left, right) {\n if (left === right) {\n this.tree[treeIndex] = new TreeNode(1, left, left, right, right)\n return\n }\n\n let mid = left + Math.floor((right - left) / 2)\n this.build(s, treeIndex * 2, left, mid)\n this.build(s, treeIndex * 2 + 1, mid + 1, right)\n\n this.tree[treeIndex] = this.merge(\n this.tree[treeIndex * 2],\n this.tree[treeIndex * 2 + 1],\n left,\n mid,\n right\n )\n }\n\n update(treeIndex, left, right, index, val) {\n if (left === right) {\n this.tree[treeIndex] = new TreeNode(1, left, left, right, right)\n this.s[index] = val\n return\n }\n\n let mid = left + Math.floor((right - left) / 2)\n if (mid < index) {\n this.update(treeIndex * 2 + 1, mid + 1, right, index, val)\n } else {\n this.update(treeIndex * 2, left, mid, index, val)\n }\n\n this.tree[treeIndex] = this.merge(\n this.tree[treeIndex * 2],\n this.tree[treeIndex * 2 + 1],\n left,\n mid,\n right\n )\n }\n\n merge(l, r, left, mid, right) {\n let max = Math.max(l.max, r.max)\n let preStart = l.preStart\n let preEnd = l.preEnd\n let sufStart = r.sufStart\n let sufEnd = r.sufEnd\n\n if (this.s[mid] === this.s[mid + 1]) {\n max = Math.max(max, r.preEnd - l.sufStart + 1)\n if (l.preEnd - l.preStart + 1 === mid - left + 1) {\n preEnd = r.preEnd\n }\n if (r.sufEnd - r.sufStart + 1 === right - mid) {\n sufStart = l.sufStart\n }\n }\n\n return new TreeNode(max, preStart, preEnd, sufStart, sufEnd)\n }\n\n getMax() {\n return this.tree[1].max\n }\n}\n\n\n" + }, + { + "_id": "66f925defdfb8e1665720f06", + "questionid": 1083, + "title": "Find All K-Distant Indices in an Array", + "slug": "find-all-k-distant-indices-in-an-array", + "description": "You are given a 0-indexed integer array nums and two integers key and k. A k-distant index is an index i of nums for which there exists at least one index j such that |i - j| <= k and nums[j] == key. Return a list of all k-distant indices sorted in increasing order. ", + "category": [ + "Array" + ], + "complexity": "Easy", + "successrate": 64.4, + "totalsubmissions": 32898, + "totalaccepted": 21198, + "likes": 177, + "dislikes": 26, + "hints": "For every occurrence of key in nums, find all indices within distance k from it. Use a hash table to remove duplicate indices.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [3,4,9,1,3,9,5], key = 9, k = 1", + "expected_output": "[1,2,3,4,5,6]", + "explanation": "Here, nums[2] == key and nums[5] == key.\n- For index 0, |0 - 2| > k and |0 - 5| > k, so there is no j where |0 - j| <= k and nums[j] == key. Thus, 0 is not a k-distant index.\n- For index 1, |1 - 2| <= k and nums[2] == key, so 1 is a k-distant index.\n- For index 2, |2 - 2| <= k and nums[2] == key, so 2 is a k-distant index.\n- For index 3, |3 - 2| <= k and nums[2] == key, so 3 is a k-distant index.\n- For index 4, |4 - 5| <= k and nums[5] == key, so 4 is a k-distant index.\n- For index 5, |5 - 5| <= k and nums[5] == key, so 5 is a k-distant index.\n- For index 6, |6 - 5| <= k and nums[5] == key, so 6 is a k-distant index.\nThus, we return [1,2,3,4,5,6] which is sorted in increasing order." + }, + { + "example_num": 2, + "expected_input": "nums = [2,2,2,2,2], key = 2, k = 2", + "expected_output": "[0,1,2,3,4]", + "explanation": "For all indices i in nums, there exists some index j such that |i - j| <= k and nums[j] == key, so every index is a k-distant index. \nHence, we return [0,1,2,3,4]." + } + ], + "solution": null + }, + { + "_id": "66f925defdfb8e1665720ebd", + "questionid": 1010, + "title": "Stone Game IX", + "slug": "stone-game-ix", + "description": "Alice and Bob continue their games with stones. There is a row of n stones, and each stone has an associated value. You are given an integer array stones, where stones[i] is the value of the ith stone. Alice and Bob take turns, with Alice starting first. On each turn, the player may remove any stone from stones. The player who removes a stone loses if the sum of the values of all removed stones is divisible by 3. Bob will win automatically if there are no remaining stones (even if it is Alice's turn). Assuming both players play optimally, return true if Alice wins and false if Bob wins. ", + "category": [ + "Array", + "Math", + "Greedy", + "Counting", + "Game Theory" + ], + "complexity": "Medium", + "successrate": 24.8, + "totalsubmissions": 19252, + "totalaccepted": 4771, + "likes": 140, + "dislikes": 202, + "hints": "There are limited outcomes given the current sum and the stones remaining. Can we greedily simulate starting with taking a stone with remainder 1 or 2 divided by 3?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "stones = [2,1]", + "expected_output": "true", + "explanation": " The game will be played as follows:\n- Turn 1: Alice can remove either stone.\n- Turn 2: Bob removes the remaining stone. \nThe sum of the removed stones is 1 + 2 = 3 and is divisible by 3. Therefore, Bob loses and Alice wins the game." + }, + { + "example_num": 2, + "expected_input": "stones = [2]", + "expected_output": "false", + "explanation": " Alice will remove the only stone, and the sum of the values on the removed stones is 2. \nSince all the stones are removed and the sum of values is not divisible by 3, Bob wins the game." + }, + { + "example_num": 3, + "expected_input": "stones = [5,1,2,4,3]", + "expected_output": "false", + "explanation": "Bob will always win. One possible way for Bob to win is shown below:\n- Turn 1: Alice can remove the second stone with value 1. Sum of removed stones = 1.\n- Turn 2: Bob removes the fifth stone with value 3. Sum of removed stones = 1 + 3 = 4.\n- Turn 3: Alices removes the fourth stone with value 4. Sum of removed stones = 1 + 3 + 4 = 8.\n- Turn 4: Bob removes the third stone with value 2. Sum of removed stones = 1 + 3 + 4 + 2 = 10.\n- Turn 5: Alice removes the first stone with value 5. Sum of removed stones = 1 + 3 + 4 + 2 + 5 = 15.\nAlice loses the game because the sum of the removed stones (15) is divisible by 3. Bob wins the game." + } + ], + "solution": "/**\n * @param {number[]} stones\n * @return {boolean}\n */\nconst stoneGameIX = function(stones) {\n const cnt = Array(3).fill(0), { abs } = Math \n for (let a of stones) cnt[a % 3]++;\n if (cnt[0] % 2 == 0) return cnt[1] && cnt[2]\n return abs(cnt[1] - cnt[2]) >= 3\n};\n" + }, + { + "_id": "66f925defdfb8e1665720ebe", + "questionid": 1011, + "title": "Smallest K-Length Subsequence With Occurrences of a Letter", + "slug": "smallest-k-length-subsequence-with-occurrences-of-a-letter", + "description": "You are given a string s, an integer k, a letter letter, and an integer repetition. Return the lexicographically smallest subsequence of s of length k that has the letter letter appear at least repetition times. The test cases are generated so that the letter appears in s at least repetition times. A subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters. A string a is lexicographically smaller than a string b if in the first position where a and b differ, string a has a letter that appears earlier in the alphabet than the corresponding letter in b. ", + "category": [ + "String", + "Stack", + "Greedy", + "Monotonic Stack" + ], + "complexity": "Hard", + "successrate": 38.7, + "totalsubmissions": 11283, + "totalaccepted": 4365, + "likes": 244, + "dislikes": 6, + "hints": "Use stack. For every character to be appended, decide how many character(s) from the stack needs to get popped based on the stack length and the count of the required character. Pop the extra characters out from the stack and return the characters in the stack (reversed).", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "leet", k = 3, letter = "e", repetition = 1", + "expected_output": ""eet"", + "explanation": "There are four subsequences of length 3 that have the letter 'e' appear at least 1 time:\n- "lee" (from "leet")\n- "let" (from "leet")\n- "let" (from "leet")\n- "eet" (from "leet")\nThe lexicographically smallest subsequence among them is "eet"." + }, + { + "example_num": 2, + "expected_input": "s = "leetcode", k = 4, letter = "e", repetition = 2", + "expected_output": ""ecde"", + "explanation": ""ecde" is the lexicographically smallest subsequence of length 4 that has the letter "e" appear at least 2 times." + }, + { + "example_num": 3, + "expected_input": "s = "bb", k = 2, letter = "b", repetition = 2", + "expected_output": ""bb"", + "explanation": ""bb" is the only subsequence of length 2 that has the letter "b" appear at least 2 times." + } + ], + "solution": "/**\n * @param {string} s\n * @param {number} k\n * @param {character} letter\n * @param {number} repetition\n * @return {string}\n */\nconst smallestSubsequence = function (s, k, letter, repetition) {\n let n_letters = 0\n for (let i = 0; i < s.length; i++) if (s.charAt(i) == letter) n_letters++\n const stack = []\n for (let i = 0; i < s.length; i++) {\n let c = s.charAt(i)\n while (\n stack.length &&\n stack[stack.length - 1] > c &&\n s.length - i + stack.length > k &&\n (stack[stack.length - 1] != letter || n_letters > repetition)\n ) {\n if (stack.pop() == letter) repetition++\n }\n if (stack.length < k) {\n if (c == letter) {\n stack.push(c)\n repetition--\n } else if (k - stack.length > repetition) {\n stack.push(c)\n }\n }\n if (c == letter) n_letters--\n }\n\n let sb = ''\n for (let c of stack) sb += c\n return sb\n}\n" + }, + { + "_id": "66f925defdfb8e1665720ebf", + "questionid": 1012, + "title": "Minimum Operations to Make a Uni-Value Grid", + "slug": "minimum-operations-to-make-a-uni-value-grid", + "description": "You are given a 2D integer grid of size m x n and an integer x. In one operation, you can add x to or subtract x from any element in the grid. A uni-value grid is a grid where all the elements of it are equal. Return the minimum number of operations to make the grid uni-value. If it is not possible, return -1. ", + "category": [ + "Array", + "Math", + "Sorting", + "Matrix" + ], + "complexity": "Medium", + "successrate": 50.5, + "totalsubmissions": 26429, + "totalaccepted": 13355, + "likes": 304, + "dislikes": 29, + "hints": "Is it possible to make two integers a and b equal if they have different remainders dividing by x? If it is possible, which number should you select to minimize the number of operations? What if the elements are sorted?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "grid = [[2,4],[6,8]], x = 2", + "expected_output": "4", + "explanation": "We can make every element equal to 4 by doing the following: \n- Add x to 2 once.\n- Subtract x from 6 once.\n- Subtract x from 8 twice.\nA total of 4 operations were used." + }, + { + "example_num": 2, + "expected_input": "grid = [[1,5],[2,3]], x = 1", + "expected_output": "5", + "explanation": "We can make every element equal to 3." + }, + { + "example_num": 3, + "expected_input": "grid = [[1,2],[3,4]], x = 2", + "expected_output": "-1", + "explanation": "It is impossible to make every element equal." + } + ], + "solution": "/**\n * @param {number[][]} grid\n * @param {number} x\n * @return {number}\n */\nfunction minOperations(grid, x) {\n const m = grid.length, n = grid[0].length\n const len = m * n, arr = []\n for(let i = 0; i < m; i++) {\n for(let j = 0; j < n; j++) {\n arr.push(grid[i][j])\n }\n }\n arr.sort((a, b) => a - b)\n const mid = arr[Math.floor(len / 2)]\n let res = 0\n for(const e of arr) {\n const d = Math.abs(e - mid)\n if(d % x !== 0) return -1\n res += d / x\n }\n \n return res\n};\n\n// another\n\n/**\n * @param {number[][]} grid\n * @param {number} x\n * @return {number}\n */\nconst minOperations = function (grid, x) {\n const arr = [],\n m = grid.length,\n n = grid[0].length\n const len = m * n\n for (let i = 0; i < m; i++) {\n for (let j = 0; j < n; j++) {\n arr.push(grid[i][j])\n }\n }\n arr.sort((a, b) => a - b)\n const mid = arr[~~(len / 2)], { abs } = Math\n let res = 0\n for(const e of arr) {\n if(abs(mid - e) % x !== 0) return -1\n res += abs(mid - e) / x\n }\n\n return res\n}\n\n// another\n\n/**\n * @param {number[][]} grid\n * @param {number} x\n * @return {number}\n */\nconst minOperations = function(grid, x) {\n const arr = []\n const m = grid.length, n = grid[0].length\n for(let i = 0; i < m; i++) {\n for(let j = 0; j < n; j++) {\n arr.push(grid[i][j])\n }\n }\n arr.sort((a, b) => a - b)\n \n for(let i = 1; i < m * n; i++) {\n if((arr[i] - arr[i - 1]) % x !== 0) return -1\n }\n const sum = arr.reduce((ac, e) => ac + e, 0)\n const pre = []\n pre.push(arr[0])\n for(let i = 1; i < m * n; i++) {\n pre[i] = pre[i - 1] + arr[i]\n }\n \n let res = 0, num = 0, min = sum - arr[0] * m * n, idx = 0\n for(let i = 1; i < m * n; i++) {\n const cur = (i + 1) * arr[i] - pre[i] + (sum - pre[i] - arr[i] * (m * n - i - 1))\n // console.log(cur, (i + 1) * arr[i] - pre[i], sum - pre[i] - arr[i] * (m * n - i - 1))\n // const cur = sum - arr[i] * (m * n - i)\n if(cur < min) {\n idx = i\n min = cur\n }\n }\n \n // console.log(idx)\n \n for(let i = 0; i < m * n; i++) {\n if(i === idx) continue\n res += Math.abs(arr[i] - arr[idx]) / x\n }\n \n return res\n};\n// 20 - 6 - 4 * 2\n// 2 4 6 8\n// 1 2 3 5\n\n// another\n\n/**\n * @param {number[][]} grid\n * @param {number} x\n * @return {number}\n */\nconst minOperations = function(grid, x) {\n const arr = [], m = grid.length, n = grid[0].length\n for(let i = 0; i < m; i++) {\n for(let j = 0; j < n; j++) {\n arr.push(grid[i][j])\n }\n }\n arr.sort((a, b) => a - b)\n const mid = arr[~~((m * n) / 2)]\n let res = 0\n\n for(let e of arr) {\n if (e !== mid) {\n const cur = Math.abs(e - mid)\n if(cur % x !== 0) return -1\n res += cur / x\n }\n }\n return res\n};\n\n// another\n\n/**\n * @param {number[][]} grid\n * @param {number} x\n * @return {number}\n */\nfunction minOperations(grid, x) {\n const m = grid.length, n = grid[0].length, mn = m * n, arr = []\n for(let i = 0; i < m; i++) {\n for(let j = 0; j < n; j++) {\n arr.push(grid[i][j])\n }\n }\n arr.sort((a, b) => a - b)\n const mid = arr[~~(mn / 2)]\n let res = 0\n\n for(let e of arr) {\n if(e !== mid) {\n const delta = Math.abs(e - mid)\n if(delta % x !== 0) return -1\n res += delta / x\n }\n }\n\n return res\n};\n" + }, + { + "_id": "66f925defdfb8e1665720ec5", + "questionid": 1018, + "title": "Next Greater Numerically Balanced Number", + "slug": "next-greater-numerically-balanced-number", + "description": "An integer x is numerically balanced if for every digit d in the number x, there are exactly d occurrences of that digit in x. Given an integer n, return the smallest numerically balanced number strictly greater than n. ", + "category": [ + "Math", + "Backtracking", + "Enumeration" + ], + "complexity": "Medium", + "successrate": 46.2, + "totalsubmissions": 17965, + "totalaccepted": 8293, + "likes": 95, + "dislikes": 218, + "hints": "How far away can the next greater numerically balanced number be from n? With the given constraints, what is the largest numerically balanced number?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "n = 1", + "expected_output": "22", + "explanation": "22 is numerically balanced since:\n- The digit 2 occurs 2 times. \nIt is also the smallest numerically balanced number strictly greater than 1." + }, + { + "example_num": 2, + "expected_input": "n = 1000", + "expected_output": "1333", + "explanation": "1333 is numerically balanced since:\n- The digit 1 occurs 1 time.\n- The digit 3 occurs 3 times. \nIt is also the smallest numerically balanced number strictly greater than 1000.\nNote that 1022 cannot be the answer because 0 appeared more than 0 times." + }, + { + "example_num": 3, + "expected_input": "n = 3000", + "expected_output": "3133", + "explanation": "3133 is numerically balanced since:\n- The digit 1 occurs 1 time.\n- The digit 3 occurs 3 times.\nIt is also the smallest numerically balanced number strictly greater than 3000." + } + ], + "solution": "/**\n * @param {number} n\n * @return {number}\n */\nconst nextBeautifulNumber = function(n) {\n while (true) {\n ++n;\n if (balance(n)) return n;\n } \n function balance(n) {\n let cnt = Array(10).fill(0);\n while (n) {\n if (n % 10 == 0) return false; // no 0 allowed\n cnt[n % 10]++;\n n = ~~(n / 10);\n }\n for (let i = 1; i < 10; ++i) {\n if (cnt[i] && cnt[i] !== i) return false;\n }\n return true;\n }\n};\n\n" + }, + { + "_id": "66f925defdfb8e1665720ec7", + "questionid": 1020, + "title": "Check Whether Two Strings are Almost Equivalent", + "slug": "check-whether-two-strings-are-almost-equivalent", + "description": "Two strings word1 and word2 are considered almost equivalent if the differences between the frequencies of each letter from 'a' to 'z' between word1 and word2 is at most 3. Given two strings word1 and word2, each of length n, return true if word1 and word2 are almost equivalent, or false otherwise. The frequency of a letter x is the number of times it occurs in the string. ", + "category": [ + "Hash Table", + "String", + "Counting" + ], + "complexity": "Easy", + "successrate": 66.4, + "totalsubmissions": 24735, + "totalaccepted": 16420, + "likes": 193, + "dislikes": 6, + "hints": "What data structure can we use to count the frequency of each character? Are there edge cases where a character is present in one string but not the other?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "word1 = "aaaa", word2 = "bccb"", + "expected_output": "false", + "explanation": "There are 4 'a's in "aaaa" but 0 'a's in "bccb".\nThe difference is 4, which is more than the allowed 3." + }, + { + "example_num": 2, + "expected_input": "word1 = "abcdeef", word2 = "abaaacc"", + "expected_output": "true", + "explanation": "The differences between the frequencies of each letter in word1 and word2 are at most 3:\n- 'a' appears 1 time in word1 and 4 times in word2. The difference is 3.\n- 'b' appears 1 time in word1 and 1 time in word2. The difference is 0.\n- 'c' appears 1 time in word1 and 2 times in word2. The difference is 1.\n- 'd' appears 1 time in word1 and 0 times in word2. The difference is 1.\n- 'e' appears 2 times in word1 and 0 times in word2. The difference is 2.\n- 'f' appears 1 time in word1 and 0 times in word2. The difference is 1." + }, + { + "example_num": 3, + "expected_input": "word1 = "cccddabba", word2 = "babababab"", + "expected_output": "true", + "explanation": "The differences between the frequencies of each letter in word1 and word2 are at most 3:\n- 'a' appears 2 times in word1 and 4 times in word2. The difference is 2.\n- 'b' appears 2 times in word1 and 5 times in word2. The difference is 3.\n- 'c' appears 3 times in word1 and 0 times in word2. The difference is 3.\n- 'd' appears 2 times in word1 and 0 times in word2. The difference is 2." + } + ], + "solution": "/**\n * @param {string} word1\n * @param {string} word2\n * @return {boolean}\n */\nconst checkAlmostEquivalent = function(word1, word2) {\n const a = 'a'.charCodeAt(0), n = word1.length\n const arr1 = Array(26).fill(0), arr2 = Array(26).fill(0)\n \n for(const ch of word1) {\n arr1[ch.charCodeAt(0) - a]++\n }\n for(const ch of word2) {\n arr2[ch.charCodeAt(0) - a]++\n }\n for(let i = 0; i < 26; i++) {\n if(Math.abs(arr1[i] - arr2[i]) > 3) return false\n }\n \n return true\n};\n" + }, + { + "_id": "66f925defdfb8e1665720ecd", + "questionid": 1026, + "title": "Count Common Words With One Occurrence", + "slug": "count-common-words-with-one-occurrence", + "description": "Given two string arrays words1 and words2, return the number of strings that appear exactly once in each\u00a0of the two arrays. ", + "category": [ + "Array", + "Hash Table", + "String", + "Counting" + ], + "complexity": "Easy", + "successrate": 70.5, + "totalsubmissions": 31015, + "totalaccepted": 21864, + "likes": 295, + "dislikes": 6, + "hints": "Could you try every word? Could you use a hash map to achieve a good complexity?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "words1 = ["leetcode","is","amazing","as","is"], words2 = ["amazing","leetcode","is"]", + "expected_output": "2", + "explanation": "- "leetcode" appears exactly once in each of the two arrays. We count this string.\n- "amazing" appears exactly once in each of the two arrays. We count this string.\n- "is" appears in each of the two arrays, but there are 2 occurrences of it in words1. We do not count this string.\n- "as" appears once in words1, but does not appear in words2. We do not count this string.\nThus, there are 2 strings that appear exactly once in each of the two arrays." + }, + { + "example_num": 2, + "expected_input": "words1 = ["b","bb","bbb"], words2 = ["a","aa","aaa"]", + "expected_output": "0", + "explanation": "There are no strings that appear in each of the two arrays." + }, + { + "example_num": 3, + "expected_input": "words1 = ["a","ab"], words2 = ["a","a","a","ab"]", + "expected_output": "1", + "explanation": "The only string that appears exactly once in each of the two arrays is "ab"." + } + ], + "solution": null + }, + { + "_id": "66f925defdfb8e1665720ed1", + "questionid": 1030, + "title": "Two Furthest Houses With Different Colors", + "slug": "two-furthest-houses-with-different-colors", + "description": "There are n houses evenly lined up on the street, and each house is beautifully painted. You are given a 0-indexed integer array colors of length n, where colors[i] represents the color of the ith house. Return the maximum distance between two houses with different colors. The distance between the ith and jth houses is abs(i - j), where abs(x) is the absolute value of x. ", + "category": [ + "Array", + "Greedy" + ], + "complexity": "Easy", + "successrate": 68.6, + "totalsubmissions": 33973, + "totalaccepted": 23298, + "likes": 378, + "dislikes": 11, + "hints": "The constraints are small. Can you try the combination of every two houses? Greedily, the maximum distance will come from either the pair of the leftmost house and possibly some house on the right with a different color, or the pair of the rightmost house and possibly some house on the left with a different color.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "colors = [1,1,1,6,1,1,1]", + "expected_output": "3", + "explanation": "In the above image, color 1 is blue, and color 6 is red.\nThe furthest two houses with different colors are house 0 and house 3.\nHouse 0 has color 1, and house 3 has color 6. The distance between them is abs(0 - 3) = 3.\nNote that houses 3 and 6 can also produce the optimal answer." + }, + { + "example_num": 2, + "expected_input": "colors = [1,8,3,8,3]", + "expected_output": "4", + "explanation": "In the above image, color 1 is blue, color 8 is yellow, and color 3 is green.\nThe furthest two houses with different colors are house 0 and house 4.\nHouse 0 has color 1, and house 4 has color 3. The distance between them is abs(0 - 4) = 4." + }, + { + "example_num": 3, + "expected_input": "colors = [0,1]", + "expected_output": "1", + "explanation": "The furthest two houses with different colors are house 0 and house 1.\nHouse 0 has color 0, and house 1 has color 1. The distance between them is abs(0 - 1) = 1." + } + ], + "solution": "/**\n * @param {number[]} colors\n * @return {number}\n */\nconst maxDistance = function(colors) {\n const n = colors.length\n let res = 0\n for(let i = 1; i < n; i++) {\n const cur = colors[i]\n for(let j = 0; j < i; j++) {\n if(colors[i] !== colors[j]) {\n res = Math.max(res, i - j)\n break\n }\n }\n }\n \n return res\n};\n" + }, + { + "_id": "66f925defdfb8e1665720ed2", + "questionid": 1031, + "title": "Sum of k-Mirror Numbers", + "slug": "sum-of-k-mirror-numbers", + "description": "A k-mirror number is a positive integer without leading zeros that reads the same both forward and backward in base-10 as well as in base-k. Given the base k and the number n, return the sum of the n smallest k-mirror numbers. ", + "category": [ + "Math", + "Enumeration" + ], + "complexity": "Hard", + "successrate": 41.2, + "totalsubmissions": 12203, + "totalaccepted": 5030, + "likes": 80, + "dislikes": 117, + "hints": "Since we need to reduce search space, instead of checking if every number is a palindrome in base-10, can we try to \"generate\" the palindromic numbers? If you are provided with a d digit number, how can you generate a palindrome with 2*d or 2*d - 1 digit? Try brute-forcing and checking if the palindrome you generated is a \"k-Mirror\" number.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "k = 2, n = 5", + "expected_output": "25\nExplanation:\nThe 5 smallest 2-mirror numbers and their representations in base-2 are listed as follows:\n base-10 base-2\n 1 1\n 3 11\n 5 101\n 7 111\n 9 1001\nTheir sum = 1 + 3 + 5 + 7 + 9 = 25.", + "explanation": "" + }, + { + "example_num": 2, + "expected_input": "k = 3, n = 7", + "expected_output": "499\nExplanation:\nThe 7 smallest 3-mirror numbers are and their representations in base-3 are listed as follows:\n base-10 base-3\n 1 1\n 2 2\n 4 11\n 8 22\n 121 11111\n 151 12121\n 212 21212\nTheir sum = 1 + 2 + 4 + 8 + 121 + 151 + 212 = 499.", + "explanation": "" + }, + { + "example_num": 3, + "expected_input": "k = 7, n = 17", + "expected_output": "20379000", + "explanation": "The 17 smallest 7-mirror numbers are:\n1, 2, 3, 4, 5, 6, 8, 121, 171, 242, 292, 16561, 65656, 2137312, 4602064, 6597956, 6958596" + } + ], + "solution": "const isPalindrome = (s) => { let n = s.length; let i = 0; let j = n - 1; while (i < j) { if (s[i++] != s[j--]) return false; } return true; };\n\nconst int = parseInt;\n/**\n * @param {number} k\n * @param {number} n\n * @return {number}\n */\nvar kMirror = function(k, n) {\n let res = 0;\n for (let len = 1; ; len++) {\n let min = 10 ** ((len - 1) >> 1), max = 10 ** ((len + 1) >> 1);\n for (let base = min; base < max; base++) {\n let x = base;\n for (let i = len & 1 ? int(base / 10) : base; i > 0; i = int(i / 10)) {\n x = x * 10 + i % 10;\n }\n let s = x.toString(k);\n if (isPalindrome(s)) {\n res += x;\n n--;\n if (!n) return res;\n }\n }\n } \n};\n" + }, + { + "_id": "66f925defdfb8e1665720ed5", + "questionid": 1034, + "title": "Find Target Indices After Sorting Array", + "slug": "find-target-indices-after-sorting-array", + "description": "You are given a 0-indexed integer array nums and a target element target. A target index is an index i such that nums[i] == target. Return a list of the target indices of nums after sorting nums in non-decreasing order. If there are no target indices, return an empty list. The returned list must be sorted in increasing order. ", + "category": [ + "Array", + "Binary Search", + "Sorting" + ], + "complexity": "Easy", + "successrate": 79.1, + "totalsubmissions": 63516, + "totalaccepted": 50251, + "likes": 568, + "dislikes": 28, + "hints": "Try \"sorting\" the array first. Now find all indices in the array whose values are equal to target.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [1,2,5,2,3], target = 2", + "expected_output": "[1,2]", + "explanation": "After sorting, nums is [1,2,2,3,5].\nThe indices where nums[i] == 2 are 1 and 2." + }, + { + "example_num": 2, + "expected_input": "nums = [1,2,5,2,3], target = 3", + "expected_output": "[3]", + "explanation": "After sorting, nums is [1,2,2,3,5].\nThe index where nums[i] == 3 is 3." + }, + { + "example_num": 3, + "expected_input": "nums = [1,2,5,2,3], target = 5", + "expected_output": "[4]", + "explanation": "After sorting, nums is [1,2,2,3,5].\nThe index where nums[i] == 5 is 4." + } + ], + "solution": "/**\n * @param {number[]} nums\n * @param {number} target\n * @return {number[]}\n */\nconst targetIndices = function(nums, target) {\n let res = []\n nums.sort((a, b) => a - b)\n for(let i = 0; i < nums.length; i++) {\n if(nums[i] === target) res.push(i)\n }\n return res\n};\n" + }, + { + "_id": "66f925defdfb8e1665720ed6", + "questionid": 1035, + "title": "K Radius Subarray Averages", + "slug": "k-radius-subarray-averages", + "description": "You are given a 0-indexed array nums of n integers, and an integer k. The k-radius average for a subarray of nums centered at some index i with the radius k is the average of all elements in nums between the indices i - k and i + k (inclusive). If there are less than k elements before or after the index i, then the k-radius average is -1. Build and return an array avgs of length n where avgs[i] is the k-radius average for the subarray centered at index i. The average of x elements is the sum of the x elements divided by x, using integer division. The integer division truncates toward zero, which means losing its fractional part. ", + "category": [ + "Array", + "Sliding Window" + ], + "complexity": "Medium", + "successrate": 40.6, + "totalsubmissions": 34633, + "totalaccepted": 14048, + "likes": 260, + "dislikes": 10, + "hints": "To calculate the average of a subarray, you need the sum and the K. K is already given. How could you quickly calculate the sum of a subarray? Use the Prefix Sums method to calculate the subarray sums. It is possible that the sum of all the elements does not fit in a 32-bit integer type. Be sure to use a 64-bit integer type for the prefix sum array.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [7,4,3,9,1,8,5,2,6], k = 3", + "expected_output": "[-1,-1,-1,5,4,4,-1,-1,-1]", + "explanation": "- avg[0], avg[1], and avg[2] are -1 because there are less than k elements before each index.\n- The sum of the subarray centered at index 3 with radius 3 is: 7 + 4 + 3 + 9 + 1 + 8 + 5 = 37.\n Using integer division, avg[3] = 37 / 7 = 5.\n- For the subarray centered at index 4, avg[4] = (4 + 3 + 9 + 1 + 8 + 5 + 2) / 7 = 4.\n- For the subarray centered at index 5, avg[5] = (3 + 9 + 1 + 8 + 5 + 2 + 6) / 7 = 4.\n- avg[6], avg[7], and avg[8] are -1 because there are less than k elements after each index." + }, + { + "example_num": 2, + "expected_input": "nums = [100000], k = 0", + "expected_output": "[100000]", + "explanation": "- The sum of the subarray centered at index 0 with radius 0 is: 100000.\n avg[0] = 100000 / 1 = 100000." + }, + { + "example_num": 3, + "expected_input": "nums = [8], k = 100000", + "expected_output": "[-1]", + "explanation": "- avg[0] is -1 because there are less than k elements before and after index 0." + } + ], + "solution": "const lowBit = (x) => x & -x\nclass FenwickTree {\n constructor(n) {\n if (n < 1) return\n this.sum = Array(n + 1).fill(0)\n }\n update(i, delta) {\n if (i < 1) return\n while (i < this.sum.length) {\n this.sum[i] += delta\n i += lowBit(i)\n }\n }\n query(i) {\n if (i < 1) return 0\n let sum = 0\n while (i > 0) {\n sum += this.sum[i]\n i -= lowBit(i)\n }\n return sum\n }\n}\n/**\n * @param {number[]} nums\n * @param {number} k\n * @return {number[]}\n */\nconst getAverages = function(nums, k) {\n const n = nums.length\n const bit = new FenwickTree(n)\n for(let i = 0; i < n; i++) {\n bit.update(i + 1, nums[i])\n }\n const res = Array(n).fill(-1)\n // console.log(bit)\n for(let i = k; i < n - k; i++) {\n const pre = bit.query(i + 1 - k - 1), cur = bit.query(i + 1 + k)\n res[i] = ~~((cur - pre) / (k * 2 + 1))\n }\n \n return res\n};\n" + }, + { + "_id": "66f925defdfb8e1665720edd", + "questionid": 1042, + "title": "Maximum Fruits Harvested After at Most K Steps", + "slug": "maximum-fruits-harvested-after-at-most-k-steps", + "description": "Fruits are available at some positions on an infinite x-axis. You are given a 2D integer array fruits where fruits[i] = [positioni, amounti] depicts amounti fruits at the position positioni. fruits is already sorted by positioni in ascending order, and each positioni is unique. You are also given an integer startPos and an integer k. Initially, you are at the position startPos. From any position, you can either walk to the left or right. It takes one step to move one unit on the x-axis, and you can walk at most k steps in total. For every position you reach, you harvest all the fruits at that position, and the fruits will disappear from that position. Return the maximum total number of fruits you can harvest. ", + "category": [ + "Array", + "Binary Search", + "Sliding Window", + "Prefix Sum" + ], + "complexity": "Hard", + "successrate": 35.1, + "totalsubmissions": 17447, + "totalaccepted": 6129, + "likes": 253, + "dislikes": 15, + "hints": "Does an optimal path have very few patterns? For example, could a path that goes left, turns and goes right, then turns again and goes left be any better than a path that simply goes left, turns, and goes right? The optimal path turns at most once. That is, the optimal path is one of these: to go left only; to go right only; to go left, turn and go right; or to go right, turn and go left. Moving x steps left then k-x steps right gives you a range of positions that you can reach. Use prefix sums to get the sum of all fruits for each possible range. Use a similar strategy for all the paths that go right, then turn and go left.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "fruits = [[2,8],[6,3],[8,6]], startPos = 5, k = 4", + "expected_output": "9", + "explanation": "The optimal way is to:\n- Move right to position 6 and harvest 3 fruits\n- Move right to position 8 and harvest 6 fruits\nYou moved 3 steps and harvested 3 + 6 = 9 fruits in total." + }, + { + "example_num": 2, + "expected_input": "fruits = [[0,9],[4,1],[5,7],[6,2],[7,4],[10,9]], startPos = 5, k = 4", + "expected_output": "14", + "explanation": "You can move at most k = 4 steps, so you cannot reach position 0 nor 10.\nThe optimal way is to:\n- Harvest the 7 fruits at the starting position 5\n- Move left to position 4 and harvest 1 fruit\n- Move right to position 6 and harvest 2 fruits\n- Move right to position 7 and harvest 4 fruits\nYou moved 1 + 3 = 4 steps and harvested 7 + 1 + 2 + 4 = 14 fruits in total." + }, + { + "example_num": 3, + "expected_input": "fruits = [[0,3],[6,4],[8,5]], startPos = 3, k = 2", + "expected_output": "0", + "explanation": "You can move at most k = 2 steps and cannot reach any position with fruits." + } + ], + "solution": "/**\n * @param {number[][]} fruits\n * @param {number} startPos\n * @param {number} k\n * @return {number}\n */\nconst maxTotalFruits = function(fruits, startPos, k) {\n let n = fruits.length, { max, min } = Math\n let pos = fruits.map(([p,a]) => p)\n const prefix = Array(n).fill(0)\n\n let curr = 0\n for (let i = 0; i < n; i++) {\n curr += fruits[i][1]\n prefix[i] = curr \n }\n\n function bisect_left(a, x, lo = 0, hi = null) {\n // >= lower_bound\n if (lo < 0) throw new Error('lo must be non-negative')\n if (hi == null) hi = a.length\n while (lo < hi) {\n let mid = parseInt((lo + hi) / 2)\n a[mid] < x ? (lo = mid + 1) : (hi = mid)\n }\n return lo\n }\n function bisect_right(a, x, lo = 0, hi = null) {\n // > upper_bound\n if (lo < 0) throw new Error('lo must be non-negative')\n if (hi == null) hi = a.length\n while (lo < hi) {\n let mid = parseInt((lo + hi) / 2)\n x < a[mid] ? (hi = mid) : (lo = mid + 1)\n }\n return lo\n }\n function query(left, right) {\n left = max(left, 0)\n right = min(right, 200000)\n let l = bisect_left(pos, left)\n let r = bisect_right(pos, right) - 1\n if (l > r) return 0\n if (!l) return prefix[r]\n return prefix[r] - prefix[l - 1] \n }\n\n\n let best = 0\n let idx = 0\n for(let right = startPos + k; right > startPos - 1; right -= 2) {\n let cand = query(startPos - idx, right)\n best = max(best, cand)\n idx += 1 \n }\n\n idx = 0\n for(let left = startPos - k; left < startPos + 1; left += 2) {\n let cand = query(left, startPos + idx)\n best = max(best, cand)\n idx += 1\n }\n\n return best \n};\n\n" + }, + { + "_id": "66f925defdfb8e1665720ede", + "questionid": 1043, + "title": "Find First Palindromic String in the Array", + "slug": "find-first-palindromic-string-in-the-array", + "description": "Given an array of strings words, return the first palindromic string in the array. If there is no such string, return an empty string \"\". A string is palindromic if it reads the same forward and backward. ", + "category": [ + "Array", + "Two Pointers", + "String" + ], + "complexity": "Easy", + "successrate": 79.5, + "totalsubmissions": 50602, + "totalaccepted": 40250, + "likes": 347, + "dislikes": 12, + "hints": "Iterate through the elements in order. As soon as the current element is a palindrome, return it. To check if an element is a palindrome, can you reverse the string?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "words = ["abc","car","ada","racecar","cool"]", + "expected_output": ""ada"", + "explanation": "The first string that is palindromic is "ada".\nNote that "racecar" is also palindromic, but it is not the first." + }, + { + "example_num": 2, + "expected_input": "words = ["notapalindrome","racecar"]", + "expected_output": ""racecar"", + "explanation": "The first and only string that is palindromic is "racecar"." + }, + { + "example_num": 3, + "expected_input": "words = ["def","ghi"]", + "expected_output": """", + "explanation": "There are no palindromic strings, so the empty string is returned." + } + ], + "solution": "/**\n * @param {string[]} words\n * @return {string}\n */\nconst firstPalindrome = function(words) {\n for(let str of words) {\n if(isPa(str)) return str\n }\n \n return ''\n};\n\nfunction isPa(str) {\n let l = 0, r = str.length - 1\n while(l < r) {\n if(str[l] !== str[r]) return false\n l++\n r--\n }\n \n \n return true\n}\n" + }, + { + "_id": "66f925defdfb8e1665720ee7", + "questionid": 1052, + "title": "Maximum Employees to Be Invited to a Meeting", + "slug": "maximum-employees-to-be-invited-to-a-meeting", + "description": "A company is organizing a meeting and has a list of n employees, waiting to be invited. They have arranged for a large circular table, capable of seating any number of employees. The employees are numbered from 0 to n - 1. Each employee has a favorite person and they will attend the meeting only if they can sit next to their favorite person at the table. The favorite person of an employee is not themself. Given a 0-indexed integer array favorite, where favorite[i] denotes the favorite person of the ith employee, return the maximum number of employees that can be invited to the meeting. ", + "category": [ + "Depth-First Search", + "Graph", + "Topological Sort" + ], + "complexity": "Hard", + "successrate": 29.9, + "totalsubmissions": 15292, + "totalaccepted": 4578, + "likes": 471, + "dislikes": 6, + "hints": "From the given array favorite, create a graph where for every index i, there is a directed edge from favorite[i] to i. The graph will be a combination of cycles and chains of acyclic edges. Now, what are the ways in which we can choose employees to sit at the table? The first way by which we can choose employees is by selecting a cycle of the graph. It can be proven that in this case, the employees that do not lie in the cycle can never be seated at the table. The second way is by combining acyclic chains. At most two chains can be combined by a cycle of length 2, where each chain ends on one of the employees in the cycle.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "favorite = [2,2,1,2]", + "expected_output": "3", + "explanation": "The above figure shows how the company can invite employees 0, 1, and 2, and seat them at the round table.\nAll employees cannot be invited because employee 2 cannot sit beside employees 0, 1, and 3, simultaneously.\nNote that the company can also invite employees 1, 2, and 3, and give them their desired seats.\nThe maximum number of employees that can be invited to the meeting is 3." + }, + { + "example_num": 2, + "expected_input": "favorite = [1,2,0]", + "expected_output": "3", + "explanation": "Each employee is the favorite person of at least one other employee, and the only way the company can invite them is if they invite every employee.\nThe seating arrangement will be the same as that in the figure given in example 1:\n- Employee 0 will sit between employees 2 and 1.\n- Employee 1 will sit between employees 0 and 2.\n- Employee 2 will sit between employees 1 and 0.\nThe maximum number of employees that can be invited to the meeting is 3." + }, + { + "example_num": 3, + "expected_input": "favorite = [3,0,1,4,1]", + "expected_output": "4", + "explanation": "The above figure shows how the company will invite employees 0, 1, 3, and 4, and seat them at the round table.\nEmployee 2 cannot be invited because the two spots next to their favorite employee 1 are taken.\nSo the company leaves them out of the meeting.\nThe maximum number of employees that can be invited to the meeting is 4." + } + ], + "solution": "/**\n * @param {number[]} favorite\n * @return {number}\n */\nconst maximumInvitations = function(favorite) {\n const n = favorite.length\n const inDegree = Array(n).fill(0)\n const { max } = Math\n for(let i = 0; i < n; i++) {\n inDegree[favorite[i]]++\n }\n \n let q = []\n const visited = Array(n).fill(0)\n const depth = Array(n).fill(1)\n for(let i = 0; i < n; i++) {\n if(inDegree[i] === 0) {\n q.push(i)\n visited[i] = 1\n depth[i] = 1\n }\n }\n \n while(q.length) {\n const cur = q.pop()\n const nxt = favorite[cur]\n inDegree[nxt]--\n if(inDegree[nxt] === 0) {\n q.push(nxt)\n visited[nxt] = 1\n }\n depth[nxt] = max(depth[nxt], depth[cur] + 1)\n }\n\n let maxLoopSize = 0\n let twoNodesSize = 0\n\n for(let i = 0; i < n; i++) {\n if(visited[i] === 1) continue\n let j = i\n let cnt = 0\n while(visited[j] === 0) {\n cnt++\n visited[j] = 1\n j = favorite[j]\n }\n \n if(cnt > 2) {\n maxLoopSize = max(maxLoopSize, cnt)\n } else if(cnt === 2) {\n twoNodesSize += depth[i] + depth[favorite[i]]\n }\n }\n \n return max(maxLoopSize, twoNodesSize)\n};\n\n// another\n\n/**\n * @param {number[]} favorite\n * @return {number}\n */\nconst maximumInvitations = function (favorite) {\n const n = favorite.length\n const indegree = Array(n).fill(0)\n for (let i = 0; i < n; i++) indegree[favorite[i]]++\n const { max } = Math\n let q = []\n const visited = Array(n).fill(0)\n const depth = Array(n).fill(1)\n for (let i = 0; i < n; i++) {\n if (indegree[i] === 0) {\n depth[i] = 1\n visited[i] = 1\n q.push(i)\n }\n }\n\n while (q.length) {\n const cur = q.shift()\n const nxt = favorite[cur]\n indegree[nxt]--\n if (indegree[nxt] == 0) {\n q.push(nxt)\n visited[nxt] = 1\n }\n depth[nxt] = depth[cur] + 1\n }\n\n let max_circle_size = 0\n let max_link_size = 0\n for (let i = 0; i < n; i++) {\n if (visited[i] === 1) continue\n let j = i\n let count = 0\n while (visited[j] == 0) {\n count++\n visited[j] = 1\n j = favorite[j]\n }\n if (count > 2) max_circle_size = max(max_circle_size, count)\n else if (count == 2) max_link_size += depth[i] + depth[favorite[i]]\n }\n\n return max(max_circle_size, max_link_size)\n}\n\n// another\n\n/**\n * @param {number[]} favorite\n * @return {number}\n */\nvar maximumInvitations = function(favorite) {\n const n = favorite.length, m = Array(n).fill(-1), r = Array.from({ length: n }, () => [])\n for(let i = 0; i < n; i++) r[favorite[i]].push(i)\n \n function dfs(u) {\n if(m[u] !== -1) return m[u]\n let res = 0\n for(let v of r[u]) res = Math.max(res, dfs(v))\n return m[u] = 1 + res\n }\n let res = 0, free = 0\n for(let i = 0; i < n; ++i) {\n if (m[i] != -1) continue; // skip visited nodes\n if (favorite[favorite[i]] == i) {\n m[i] = m[favorite[i]] = 0;\n let a = 0, b = 0; // find the length of the longest arms starting from `i` and `A[i]`\n for (let v of r[i]) {\n if (v == favorite[i]) continue;\n a = Math.max(a, dfs(v));\n }\n for (let v of r[favorite[i]]) {\n if (v == i) continue;\n b = Math.max(b, dfs(v));\n }\n free += a + b + 2; // this free component is of length `a+b+2`\n } \n }\n function dfs2(u) {\n if (m[u] != -1) return[u, m[u], false]; // this is the merge point\n m[u] = 0;\n let [mergePoint, depth, mergePointMet] = dfs2(favorite[u]);\n if (mergePointMet) { // If we've met the merge point again already, this node is outside of the cycle and should be ignored.\n m[u] = 0;\n return [mergePoint, depth, true];\n }\n m[u] = 1 + depth; // If we haven't met the merge point, we increment the depth.\n return [mergePoint, m[u], u == mergePoint];\n }\n \n for(let i = 0; i < n; i++) {\n if(m[i] !== -1) continue\n let [mergePoint, depth, mergePointMet] = dfs2(i)\n if(mergePointMet) res = Math.max(res, depth)\n }\n \n return Math.max(res, free)\n};\n\n" + }, + { + "_id": "66f925defdfb8e1665720ee8", + "questionid": 1053, + "title": "Minimum Cost of Buying Candies With Discount", + "slug": "minimum-cost-of-buying-candies-with-discount", + "description": "A shop is selling candies at a discount. For every two candies sold, the shop gives a third candy for free. The customer can choose any candy to take away for free as long as the cost of the chosen candy is less than or equal to the minimum cost of the two candies bought. Given a 0-indexed integer array cost, where cost[i] denotes the cost of the ith candy, return the minimum cost of buying all the candies. ", + "category": [ + "Array", + "Greedy", + "Sorting" + ], + "complexity": "Easy", + "successrate": 60.6, + "totalsubmissions": 34300, + "totalaccepted": 20777, + "likes": 224, + "dislikes": 8, + "hints": "If we consider costs from high to low, what is the maximum cost of a single candy that we can get for free? How can we generalize this approach to maximize the costs of the candies we get for free? Can \u20ac\u0153sorting\u20ac\u009d the array help us find the minimum cost? If we consider costs from high to low, what is the maximum cost of a single candy that we can get for free? How can we generalize this approach to maximize the costs of the candies we get for free? Can \u20ac\u0153sorting\u20ac\u009d the array help us find the minimum cost?", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "cost = [1,2,3]", + "expected_output": "5", + "explanation": "We buy the candies with costs 2 and 3, and take the candy with cost 1 for free.\nThe total cost of buying all candies is 2 + 3 = 5. This is the only way we can buy the candies.\nNote that we cannot buy candies with costs 1 and 3, and then take the candy with cost 2 for free.\nThe cost of the free candy has to be less than or equal to the minimum cost of the purchased candies." + }, + { + "example_num": 2, + "expected_input": "cost = [6,5,7,9,2,2]", + "expected_output": "23", + "explanation": "The way in which we can get the minimum cost is described below:\n- Buy candies with costs 9 and 7\n- Take the candy with cost 6 for free\n- We buy candies with costs 5 and 2\n- Take the last remaining candy with cost 2 for free\nHence, the minimum cost to buy all candies is 9 + 7 + 5 + 2 = 23." + }, + { + "example_num": 3, + "expected_input": "cost = [5,5]", + "expected_output": "10", + "explanation": "Since there are only 2 candies, we buy both of them. There is not a third candy we can take for free.\nHence, the minimum cost to buy all candies is 5 + 5 = 10." + } + ], + "solution": null + }, + { + "_id": "66f925defdfb8e1665720efa", + "questionid": 1071, + "title": "Minimum Number of Steps to Make Two Strings Anagram II", + "slug": "minimum-number-of-steps-to-make-two-strings-anagram-ii", + "description": "You are given two strings s and t. In one step, you can append any character to either s or t. Return the minimum number of steps to make s and t anagrams of each other. An anagram of a string is a string that contains the same characters with a different (or the same) ordering. ", + "category": [ + "Hash Table", + "String", + "Counting" + ], + "complexity": "Medium", + "successrate": 70.4, + "totalsubmissions": 29879, + "totalaccepted": 21044, + "likes": 223, + "dislikes": 4, + "hints": "Notice that for anagrams, the order of the letters is irrelevant. For each letter, we can count its frequency in s and t. For each letter, its contribution to the answer is the absolute difference between its frequency in s and t.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "leetcode", t = "coats"", + "expected_output": "7", + "explanation": "- In 2 steps, we can append the letters in "as" onto s = "leetcode", forming s = "leetcodeas".\n- In 5 steps, we can append the letters in "leede" onto t = "coats", forming t = "coatsleede".\n"leetcodeas" and "coatsleede" are now anagrams of each other.\nWe used a total of 2 + 5 = 7 steps.\nIt can be shown that there is no way to make them anagrams of each other with less than 7 steps." + }, + { + "example_num": 2, + "expected_input": "s = "night", t = "thing"", + "expected_output": "0", + "explanation": "The given strings are already anagrams of each other. Thus, we do not need any further steps." + } + ], + "solution": null + }, + { + "_id": "66f925defdfb8e1665720eff", + "questionid": 1076, + "title": "Construct String With Repeat Limit", + "slug": "construct-string-with-repeat-limit", + "description": "You are given a string s and an integer repeatLimit. Construct a new string repeatLimitedString using the characters of s such that no letter appears more than repeatLimit times in a row. You do not have to use all characters from s. Return the lexicographically largest repeatLimitedString possible. A string a is lexicographically larger than a string b if in the first position where a and b differ, string a has a letter that appears later in the alphabet than the corresponding letter in b. If the first min(a.length, b.length) characters do not differ, then the longer string is the lexicographically larger one. ", + "category": [ + "String", + "Greedy", + "Heap (Priority Queue)", + "Counting" + ], + "complexity": "Medium", + "successrate": 51, + "totalsubmissions": 24894, + "totalaccepted": 12699, + "likes": 367, + "dislikes": 20, + "hints": "Start constructing the string in descending order of characters. When repeatLimit is reached, pick the next largest character.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "s = "cczazcc", repeatLimit = 3", + "expected_output": ""zzcccac"", + "explanation": "We use all of the characters from s to construct the repeatLimitedString "zzcccac".\nThe letter 'a' appears at most 1 time in a row.\nThe letter 'c' appears at most 3 times in a row.\nThe letter 'z' appears at most 2 times in a row.\nHence, no letter appears more than repeatLimit times in a row and the string is a valid repeatLimitedString.\nThe string is the lexicographically largest repeatLimitedString possible so we return "zzcccac".\nNote that the string "zzcccca" is lexicographically larger but the letter 'c' appears more than 3 times in a row, so it is not a valid repeatLimitedString." + }, + { + "example_num": 2, + "expected_input": "s = "aababab", repeatLimit = 2", + "expected_output": ""bbabaa"", + "explanation": "We use only some of the characters from s to construct the repeatLimitedString "bbabaa". \nThe letter 'a' appears at most 2 times in a row.\nThe letter 'b' appears at most 2 times in a row.\nHence, no letter appears more than repeatLimit times in a row and the string is a valid repeatLimitedString.\nThe string is the lexicographically largest repeatLimitedString possible so we return "bbabaa".\nNote that the string "bbabaaa" is lexicographically larger but the letter 'a' appears more than 2 times in a row, so it is not a valid repeatLimitedString." + } + ], + "solution": "/**\n * @param {string} s\n * @param {number} repeatLimit\n * @return {string}\n */\nvar repeatLimitedString = function(s, repeatLimit) {\n const a = 'a'.charCodeAt(0)\n const ch = Array(26).fill(0)\n for(let e of s) {\n const idx = e.charCodeAt(0)\n ch[idx - a]++\n }\n let res = '', last = ''\n while(true) {\n let len = res.length\n let h = false\n for(let i = 25; i >= 0; i--) {\n if(ch[i] >= repeatLimit && res[res.length - 1] !== String.fromCharCode(a + i)) {\n\n res += String.fromCharCode(a + i).repeat(repeatLimit)\n ch[i] -= repeatLimit\n \n if(ch[i]) {\n for(let j = i - 1; j >= 0; j--) {\n if(ch[j]) {\n res += String.fromCharCode(a + j)\n ch[j]--\n break\n }\n }\n break\n }\n\n }else if(ch[i] > 0 && res[res.length - 1] !== String.fromCharCode(a + i)) {\n \n res += String.fromCharCode(a + i).repeat(ch[i])\n ch[i] = 0\n break\n }\n }\n if(len === res.length) break\n }\n \n \n return res\n};\n" + }, + { + "_id": "66f925defdfb8e1665720f03", + "questionid": 1080, + "title": "Minimum Operations to Halve Array Sum", + "slug": "minimum-operations-to-halve-array-sum", + "description": "You are given an array nums of positive integers. In one operation, you can choose any number from nums and reduce it to exactly half the number. (Note that you may choose this reduced number in future operations.) Return the minimum number of operations to reduce the sum of nums by at least half. ", + "category": [ + "Array", + "Greedy", + "Heap (Priority Queue)" + ], + "complexity": "Medium", + "successrate": 43.3, + "totalsubmissions": 25848, + "totalaccepted": 11199, + "likes": 200, + "dislikes": 9, + "hints": "It is always optimal to halve the largest element. What data structure allows for an efficient query of the maximum element? Use a heap or priority queue to maintain the current elements.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [5,19,8,1]", + "expected_output": "3", + "explanation": "The initial sum of nums is equal to 5 + 19 + 8 + 1 = 33.\nThe following is one of the ways to reduce the sum by at least half:\nPick the number 19 and reduce it to 9.5.\nPick the number 9.5 and reduce it to 4.75.\nPick the number 8 and reduce it to 4.\nThe final array is [5, 4.75, 4, 1] with a total sum of 5 + 4.75 + 4 + 1 = 14.75. \nThe sum of nums has been reduced by 33 - 14.75 = 18.25, which is at least half of the initial sum, 18.25 >= 33/2 = 16.5.\nOverall, 3 operations were used so we return 3.\nIt can be shown that we cannot reduce the sum by at least half in less than 3 operations." + }, + { + "example_num": 2, + "expected_input": "nums = [3,8,20]", + "expected_output": "3", + "explanation": "The initial sum of nums is equal to 3 + 8 + 20 = 31.\nThe following is one of the ways to reduce the sum by at least half:\nPick the number 20 and reduce it to 10.\nPick the number 10 and reduce it to 5.\nPick the number 3 and reduce it to 1.5.\nThe final array is [1.5, 8, 5] with a total sum of 1.5 + 8 + 5 = 14.5. \nThe sum of nums has been reduced by 31 - 14.5 = 16.5, which is at least half of the initial sum, 16.5 >= 31/2 = 15.5.\nOverall, 3 operations were used so we return 3.\nIt can be shown that we cannot reduce the sum by at least half in less than 3 operations." + } + ], + "solution": null + }, + { + "_id": "66f925defdfb8e1665720f08", + "questionid": 1085, + "title": "Minimum Bit Flips to Convert Number", + "slug": "minimum-bit-flips-to-convert-number", + "description": "A bit flip of a number x is choosing a bit in the binary representation of x and flipping it from either 0 to 1 or 1 to 0. Given two integers start and goal, return the minimum number of bit flips to convert start to goal. ", + "category": [ + "Bit Manipulation" + ], + "complexity": "Easy", + "successrate": 81.1, + "totalsubmissions": 17915, + "totalaccepted": 14525, + "likes": 111, + "dislikes": 2, + "hints": "If the value of a bit in start and goal differ, then we need to flip that bit. Consider using the XOR operation to determine which bits need a bit flip.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "start = 10, goal = 7", + "expected_output": "3", + "explanation": "The binary representation of 10 and 7 are 1010 and 0111 respectively. We can convert 10 to 7 in 3 steps:\n- Flip the first bit from the right: 1010 -> 1011.\n- Flip the third bit from the right: 1011 -> 1111.\n- Flip the fourth bit from the right: 1111 -> 0111.\nIt can be shown we cannot convert 10 to 7 in less than 3 steps. Hence, we return 3." + }, + { + "example_num": 2, + "expected_input": "start = 3, goal = 4", + "expected_output": "3", + "explanation": "The binary representation of 3 and 4 are 011 and 100 respectively. We can convert 3 to 4 in 3 steps:\n- Flip the first bit from the right: 011 -> 010.\n- Flip the second bit from the right: 010 -> 000.\n- Flip the third bit from the right: 000 -> 100.\nIt can be shown we cannot convert 3 to 4 in less than 3 steps. Hence, we return 3." + } + ], + "solution": null + }, + { + "_id": "66f925defdfb8e1665720f0c", + "questionid": 1089, + "title": "Maximum Product After K Increments", + "slug": "maximum-product-after-k-increments", + "description": "You are given an array of non-negative integers nums and an integer k. In one operation, you may choose any element from nums and increment it by 1. Return the maximum product of nums after at most k operations. Since the answer may be very large, return it modulo 109 + 7. Note that you should maximize the product before taking the modulo. ", + "category": [ + "Array", + "Greedy", + "Heap (Priority Queue)" + ], + "complexity": "Medium", + "successrate": 39, + "totalsubmissions": 32222, + "totalaccepted": 12569, + "likes": 248, + "dislikes": 23, + "hints": "If you can increment only once, which number should you increment? We should always prioritize the smallest number. What kind of data structure could we use? Use a min heap to hold all the numbers. Each time we do an operation, replace the top of the heap x by x + 1.", + "deleted": false, + "examples": [ + { + "example_num": 1, + "expected_input": "nums = [0,4], k = 5", + "expected_output": "20", + "explanation": "Increment the first number 5 times.\nNow nums = [5, 4], with a product of 5 * 4 = 20.\nIt can be shown that 20 is maximum product possible, so we return 20.\nNote that there may be other ways to increment nums to have the maximum product." + }, + { + "example_num": 2, + "expected_input": "nums = [6,3,3,2], k = 2", + "expected_output": "216", + "explanation": "Increment the second number 1 time and increment the fourth number 1 time.\nNow nums = [6, 4, 3, 3], with a product of 6 * 4 * 3 * 3 = 216.\nIt can be shown that 216 is maximum product possible, so we return 216.\nNote that there may be other ways to increment nums to have the maximum product." + } + ], + "solution": "/**\n * @param {number[]} nums\n * @param {number} k\n * @return {number}\n */\nconst maximumProduct = function (nums, k) {\n const pq = new PriorityQueue((a, b) => a < b)\n let res = 1\n for(const e of nums) pq.push(e)\n const mod = 1e9 + 7\n while(k) {\n const e = pq.pop()\n pq.push(e + 1)\n k--\n }\n while(!pq.isEmpty()) {\n const e = pq.pop()\n res = (res * e) % mod\n }\n \n return res\n}\n\nclass PriorityQueue {\n constructor(comparator = (a, b) => a > b) {\n this.heap = []\n this.top = 0\n this.comparator = comparator\n }\n size() {\n return this.heap.length\n }\n isEmpty() {\n return this.size() === 0\n }\n peek() {\n return this.heap[this.top]\n }\n push(...values) {\n values.forEach((value) => {\n this.heap.push(value)\n this.siftUp()\n })\n return this.size()\n }\n pop() {\n const poppedValue = this.peek()\n const bottom = this.size() - 1\n if (bottom > this.top) {\n this.swap(this.top, bottom)\n }\n this.heap.pop()\n this.siftDown()\n return poppedValue\n }\n replace(value) {\n const replacedValue = this.peek()\n this.heap[this.top] = value\n this.siftDown()\n return replacedValue\n }\n\n parent = (i) => ((i + 1) >>> 1) - 1\n left = (i) => (i << 1) + 1\n right = (i) => (i + 1) << 1\n greater = (i, j) => this.comparator(this.heap[i], this.heap[j])\n swap = (i, j) => ([this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]])\n siftUp = () => {\n let node = this.size() - 1\n while (node > this.top && this.greater(node, this.parent(node))) {\n this.swap(node, this.parent(node))\n node = this.parent(node)\n }\n }\n siftDown = () => {\n let node = this.top\n while (\n (this.left(node) < this.size() && this.greater(this.left(node), node)) ||\n (this.right(node) < this.size() && this.greater(this.right(node), node))\n ) {\n let maxChild =\n this.right(node) < this.size() &&\n this.greater(this.right(node), this.left(node))\n ? this.right(node)\n : this.left(node)\n this.swap(node, maxChild)\n node = maxChild\n }\n }\n}\n" + } +] \ No newline at end of file diff --git a/backend/question/tools/qn_populator.py b/backend/question/tools/qn_populator.py new file mode 100644 index 0000000000..aaae85fce7 --- /dev/null +++ b/backend/question/tools/qn_populator.py @@ -0,0 +1,37 @@ +import json +from typing import List +from pymongo import MongoClient +from dotenv import load_dotenv +import os + +load_dotenv() + +client = MongoClient(os.getenv("MONGODB_URI")) +db = client["questionbank"] +collection = db["questions"] + +TARGET_FILE = "qn_full_with_soln.json" + + +def populate_qns_from_file(): + with open(TARGET_FILE, "r") as f: + data = json.load(f) + for entry in data: + questionid = entry.get("questionid") + examples = entry.get("examples", []) + solution = entry.get("solution") + if questionid is not None: + result = collection.update_one( + {"questionid": questionid}, + {"$set": {"examples": examples, "solution": solution}}, + ) + if result.matched_count > 0: + print(f"Updated document with questionid {questionid}") + else: + print(f"No document found with questionid {questionid}") + else: + print("Entry missing 'questionid' field") + + +if __name__ == "__main__": + populate_qns_from_file() diff --git a/.github/.keep b/backend/question/tools/requirements.txt similarity index 100% rename from .github/.keep rename to backend/question/tools/requirements.txt diff --git a/backend/question/tsconfig.json b/backend/question/tsconfig.json new file mode 100644 index 0000000000..3712b66016 --- /dev/null +++ b/backend/question/tsconfig.json @@ -0,0 +1,111 @@ +{ + "compilerOptions": { + /* Visit https://aka.ms/tsconfig to read more about this file */ + + /* Projects */ + // "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */ + // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */ + // "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */ + // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */ + // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */ + // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */ + + /* Language and Environment */ + "target": "es2016" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */, + // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */ + // "jsx": "preserve", /* Specify what JSX code is generated. */ + // "experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */ + // "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */ + // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */ + // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */ + // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */ + // "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */ + // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */ + // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */ + // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */ + + /* Modules */ + "module": "commonjs" /* Specify what module code is generated. */, + "rootDir": "./src" /* Specify the root folder within your source files. */, + // "moduleResolution": "node10", /* Specify how TypeScript looks up a file from a given module specifier. */ + // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */ + // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */ + // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */ + // "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */ + // "types": [], /* Specify type package names to be included without being referenced in a source file. */ + // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ + // "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */ + // "allowImportingTsExtensions": true, /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */ + // "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */ + // "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */ + // "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */ + // "noUncheckedSideEffectImports": true, /* Check side effect imports. */ + // "resolveJsonModule": true, /* Enable importing .json files. */ + // "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */ + // "noResolve": true, /* Disallow 'import's, 'require's or ''s from expanding the number of files TypeScript should add to a project. */ + + /* JavaScript Support */ + // "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */ + // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */ + // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */ + + /* Emit */ + // "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */ + // "declarationMap": true, /* Create sourcemaps for d.ts files. */ + // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */ + // "sourceMap": true, /* Create source map files for emitted JavaScript files. */ + // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */ + // "noEmit": true, /* Disable emitting files from a compilation. */ + // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */ + "outDir": "./dist" /* Specify an output folder for all emitted files. */, + // "removeComments": true, /* Disable emitting comments. */ + // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */ + // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */ + // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */ + // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ + // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */ + // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */ + // "newLine": "crlf", /* Set the newline character for emitting files. */ + // "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */ + // "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */ + // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */ + // "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */ + // "declarationDir": "./", /* Specify the output directory for generated declaration files. */ + + /* Interop Constraints */ + // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */ + // "verbatimModuleSyntax": true, /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */ + // "isolatedDeclarations": true, /* Require sufficient annotation on exports so other tools can trivially generate declaration files. */ + // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */ + "esModuleInterop": true /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */, + // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */ + "forceConsistentCasingInFileNames": true /* Ensure that casing is correct in imports. */, + + /* Type Checking */ + "strict": true /* Enable all strict type-checking options. */, + // "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */ + // "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */ + // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */ + // "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */ + // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */ + // "strictBuiltinIteratorReturn": true, /* Built-in iterators are instantiated with a 'TReturn' type of 'undefined' instead of 'any'. */ + // "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */ + // "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */ + // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */ + // "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */ + // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */ + // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */ + // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */ + // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */ + // "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */ + // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */ + // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */ + // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */ + // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */ + + /* Completeness */ + // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */ + "skipLibCheck": true /* Skip type checking all .d.ts files. */ + }, + "exclude": ["jest.config.ts"] // Exclude the Jest config from compilation +} diff --git a/backend/signaling/Dockerfile b/backend/signaling/Dockerfile new file mode 100644 index 0000000000..1cd823cc8f --- /dev/null +++ b/backend/signaling/Dockerfile @@ -0,0 +1,38 @@ +FROM debian:bullseye as builder + +ARG NODE_VERSION=19.7.0 + +RUN apt-get update; apt install -y curl +RUN curl https://get.volta.sh | bash +ENV VOLTA_HOME /root/.volta +ENV PATH /root/.volta/bin:$PATH +RUN volta install node@${NODE_VERSION} + +####################################################################### + +RUN mkdir /app +WORKDIR /app + +# NPM will not install any package listed in "devDependencies" when NODE_ENV is set to "production", +# to install all modules: "npm install --production=false". +# Ref: https://docs.npmjs.com/cli/v9/commands/npm-install#description + +ENV NODE_ENV production + +COPY . . + +RUN npm install +FROM debian:bullseye + +LABEL fly_launch_runtime="nodejs" + +COPY --from=builder /root/.volta /root/.volta +COPY --from=builder /app /app + +WORKDIR /app +ENV NODE_ENV production +ENV PATH /root/.volta/bin:$PATH +ENV PORT 4444 +EXPOSE 4444 + +CMD [ "npm", "run", "start" ] \ No newline at end of file diff --git a/backend/signaling/bin/server.js b/backend/signaling/bin/server.js new file mode 100755 index 0000000000..7d9c585020 --- /dev/null +++ b/backend/signaling/bin/server.js @@ -0,0 +1,139 @@ +#!/usr/bin/env node + +import { WebSocketServer } from 'ws' +import http from 'http' +import * as map from 'lib0/map' + +const wsReadyStateConnecting = 0 +const wsReadyStateOpen = 1 +const wsReadyStateClosing = 2 // eslint-disable-line +const wsReadyStateClosed = 3 // eslint-disable-line + +const pingTimeout = 30000 + +const port = process.env.PORT || 4444 +const wss = new WebSocketServer({ noServer: true }) + +const server = http.createServer((request, response) => { + response.writeHead(200, { 'Content-Type': 'text/plain' }) + response.end('okay') +}) + +/** + * Map froms topic-name to set of subscribed clients. + * @type {Map>} + */ +const topics = new Map() + +/** + * @param {any} conn + * @param {object} message + */ +const send = (conn, message) => { + if (conn.readyState !== wsReadyStateConnecting && conn.readyState !== wsReadyStateOpen) { + conn.close() + } + try { + conn.send(JSON.stringify(message)) + } catch (e) { + conn.close() + } +} + +/** + * Setup a new client + * @param {any} conn + */ +const onconnection = conn => { + /** + * @type {Set} + */ + const subscribedTopics = new Set() + let closed = false + // Check if connection is still alive + let pongReceived = true + const pingInterval = setInterval(() => { + if (!pongReceived) { + conn.close() + clearInterval(pingInterval) + } else { + pongReceived = false + try { + conn.ping() + } catch (e) { + conn.close() + } + } + }, pingTimeout) + conn.on('pong', () => { + pongReceived = true + }) + conn.on('close', () => { + subscribedTopics.forEach(topicName => { + const subs = topics.get(topicName) || new Set() + subs.delete(conn) + if (subs.size === 0) { + topics.delete(topicName) + } + }) + subscribedTopics.clear() + closed = true + }) + conn.on('message', /** @param {object} message */ message => { + if (typeof message === 'string' || message instanceof Buffer) { + message = JSON.parse(message) + } + if (message && message.type && !closed) { + switch (message.type) { + case 'subscribe': + /** @type {Array} */ (message.topics || []).forEach(topicName => { + if (typeof topicName === 'string') { + // add conn to topic + const topic = map.setIfUndefined(topics, topicName, () => new Set()) + topic.add(conn) + // add topic to conn + subscribedTopics.add(topicName) + } + }) + break + case 'unsubscribe': + /** @type {Array} */ (message.topics || []).forEach(topicName => { + const subs = topics.get(topicName) + if (subs) { + subs.delete(conn) + } + }) + break + case 'publish': + if (message.topic) { + const receivers = topics.get(message.topic) + if (receivers) { + message.clients = receivers.size + receivers.forEach(receiver => + send(receiver, message) + ) + } + } + break + case 'ping': + send(conn, { type: 'pong' }) + } + } + }) +} +wss.on('connection', onconnection) + +server.on('upgrade', (request, socket, head) => { + // You may check auth of request here.. + /** + * @param {any} ws + */ + const handleAuth = ws => { + wss.emit('connection', ws, request) + } + wss.handleUpgrade(request, socket, head, handleAuth) +}) + +server.listen(port) + +console.log('Signaling server running on localhost:', port) diff --git a/backend/signaling/package-lock.json b/backend/signaling/package-lock.json new file mode 100644 index 0000000000..bb7aad5714 --- /dev/null +++ b/backend/signaling/package-lock.json @@ -0,0 +1,4605 @@ +{ + "name": "y-webrtc", + "version": "10.3.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "y-webrtc", + "version": "10.3.0", + "license": "MIT", + "dependencies": { + "lib0": "^0.2.42", + "simple-peer": "^9.11.0", + "y-protocols": "^1.0.6", + "y-webrtc": "^10.3.0" + }, + "bin": { + "y-webrtc-signaling": "bin/server.js" + }, + "devDependencies": { + "@rollup/plugin-commonjs": "^11.1.0", + "@rollup/plugin-node-resolve": "^7.1.3", + "@types/simple-peer": "^9.11.3", + "concurrently": "^5.3.0", + "http-server": "^0.12.3", + "rollup": "^1.32.1", + "rollup-cli": "^1.0.9", + "rollup-plugin-terser": "^5.3.1", + "standard": "^14.3.4", + "typescript": "^4.4.4", + "yjs": "^13.6.8" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "type": "GitHub Sponsors ❤", + "url": "https://github.com/sponsors/dmonad" + }, + "optionalDependencies": { + "ws": "^8.14.2" + }, + "peerDependencies": { + "yjs": "^13.6.8" + } + }, + "node_modules/@babel/code-frame": { + "version": "7.25.9", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.25.9.tgz", + "integrity": "sha512-z88xeGxnzehn2sqZ8UdGQEvYErF1odv2CftxInpSYJt6uHuPe9YjahKZITGs3l5LeI9d2ROG+obuDAoSlqbNfQ==", + "dev": true, + "dependencies": { + "@babel/highlight": "^7.25.9", + "picocolors": "^1.0.0" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-identifier": { + "version": "7.25.9", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.25.9.tgz", + "integrity": "sha512-Ed61U6XJc3CVRfkERJWDz4dJwKe7iLmmJsbOGu9wSloNSFttHV0I8g6UAgb7qnK5ly5bGLPd4oXZlxCdANBOWQ==", + "dev": true, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/highlight": { + "version": "7.25.9", + "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.25.9.tgz", + "integrity": "sha512-llL88JShoCsth8fF8R4SJnIn+WLvR6ccFxu1H3FlMhDontdcmZWf2HgIZ7AIqV3Xcck1idlohrN4EUBQz6klbw==", + "dev": true, + "dependencies": { + "@babel/helper-validator-identifier": "^7.25.9", + "chalk": "^2.4.2", + "js-tokens": "^4.0.0", + "picocolors": "^1.0.0" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/runtime": { + "version": "7.25.9", + "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.25.9.tgz", + "integrity": "sha512-4zpTHZ9Cm6L9L+uIqghQX8ZXg8HKFcjYO3qHoO8zTmRm6HQUJ8SSJ+KRvbMBZn0EGVlT4DRYeQ/6hjlyXBh+Kg==", + "dev": true, + "dependencies": { + "regenerator-runtime": "^0.14.0" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@rollup/plugin-commonjs": { + "version": "11.1.0", + "resolved": "https://registry.npmjs.org/@rollup/plugin-commonjs/-/plugin-commonjs-11.1.0.tgz", + "integrity": "sha512-Ycr12N3ZPN96Fw2STurD21jMqzKwL9QuFhms3SD7KKRK7oaXUsBU9Zt0jL/rOPHiPYisI21/rXGO3jr9BnLHUA==", + "dev": true, + "dependencies": { + "@rollup/pluginutils": "^3.0.8", + "commondir": "^1.0.1", + "estree-walker": "^1.0.1", + "glob": "^7.1.2", + "is-reference": "^1.1.2", + "magic-string": "^0.25.2", + "resolve": "^1.11.0" + }, + "engines": { + "node": ">= 8.0.0" + }, + "peerDependencies": { + "rollup": "^1.20.0||^2.0.0" + } + }, + "node_modules/@rollup/plugin-node-resolve": { + "version": "7.1.3", + "resolved": "https://registry.npmjs.org/@rollup/plugin-node-resolve/-/plugin-node-resolve-7.1.3.tgz", + "integrity": "sha512-RxtSL3XmdTAE2byxekYLnx+98kEUOrPHF/KRVjLH+DEIHy6kjIw7YINQzn+NXiH/NTrQLAwYs0GWB+csWygA9Q==", + "dev": true, + "dependencies": { + "@rollup/pluginutils": "^3.0.8", + "@types/resolve": "0.0.8", + "builtin-modules": "^3.1.0", + "is-module": "^1.0.0", + "resolve": "^1.14.2" + }, + "engines": { + "node": ">= 8.0.0" + }, + "peerDependencies": { + "rollup": "^1.20.0||^2.0.0" + } + }, + "node_modules/@rollup/pluginutils": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/@rollup/pluginutils/-/pluginutils-3.1.0.tgz", + "integrity": "sha512-GksZ6pr6TpIjHm8h9lSQ8pi8BE9VeubNT0OMJ3B5uZJ8pz73NPiqOtCog/x2/QzM1ENChPKxMDhiQuRHsqc+lg==", + "dev": true, + "dependencies": { + "@types/estree": "0.0.39", + "estree-walker": "^1.0.1", + "picomatch": "^2.2.2" + }, + "engines": { + "node": ">= 8.0.0" + }, + "peerDependencies": { + "rollup": "^1.20.0||^2.0.0" + } + }, + "node_modules/@types/estree": { + "version": "0.0.39", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-0.0.39.tgz", + "integrity": "sha512-EYNwp3bU+98cpU4lAWYYL7Zz+2gryWH1qbdDTidVd6hkiR6weksdbMadyXKXNPEkQFhXM+hVO9ZygomHXp+AIw==", + "dev": true + }, + "node_modules/@types/node": { + "version": "22.7.9", + "resolved": "https://registry.npmjs.org/@types/node/-/node-22.7.9.tgz", + "integrity": "sha512-jrTfRC7FM6nChvU7X2KqcrgquofrWLFDeYC1hKfwNWomVvrn7JIksqf344WN2X/y8xrgqBd2dJATZV4GbatBfg==", + "dev": true, + "dependencies": { + "undici-types": "~6.19.2" + } + }, + "node_modules/@types/resolve": { + "version": "0.0.8", + "resolved": "https://registry.npmjs.org/@types/resolve/-/resolve-0.0.8.tgz", + "integrity": "sha512-auApPaJf3NPfe18hSoJkp8EbZzer2ISk7o8mCC3M9he/a04+gbMF97NkpD2S8riMGvm4BMRI59/SZQSaLTKpsQ==", + "dev": true, + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/simple-peer": { + "version": "9.11.8", + "resolved": "https://registry.npmjs.org/@types/simple-peer/-/simple-peer-9.11.8.tgz", + "integrity": "sha512-rvqefdp2rvIA6wiomMgKWd2UZNPe6LM2EV5AuY3CPQJF+8TbdrL5TjYdMf0VAjGczzlkH4l1NjDkihwbj3Xodw==", + "dev": true, + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/acorn": { + "version": "7.4.1", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-7.4.1.tgz", + "integrity": "sha512-nQyp0o1/mNdbTO1PO6kHkwSrmgZ0MT/jCCpNiwbUjGoRN4dlBhqJtoQuCnEOKzgTVwg0ZWiCoQy6SxMebQVh8A==", + "dev": true, + "bin": { + "acorn": "bin/acorn" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/acorn-jsx": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/acorn-jsx/-/acorn-jsx-5.3.2.tgz", + "integrity": "sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==", + "dev": true, + "peerDependencies": { + "acorn": "^6.0.0 || ^7.0.0 || ^8.0.0" + } + }, + "node_modules/ajv": { + "version": "6.12.6", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.12.6.tgz", + "integrity": "sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==", + "dev": true, + "dependencies": { + "fast-deep-equal": "^3.1.1", + "fast-json-stable-stringify": "^2.0.0", + "json-schema-traverse": "^0.4.1", + "uri-js": "^4.2.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/ansi-escapes": { + "version": "4.3.2", + "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-4.3.2.tgz", + "integrity": "sha512-gKXj5ALrKWQLsYG9jlTRmR/xKluxHV+Z9QEwNIgCfM1/uwPMCuzVVnh5mwTd+OuBZcwSIMbqssNWRm1lE51QaQ==", + "dev": true, + "dependencies": { + "type-fest": "^0.21.3" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/ansi-escapes/node_modules/type-fest": { + "version": "0.21.3", + "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.21.3.tgz", + "integrity": "sha512-t0rzBq87m3fVcduHDUFhKmyyX+9eo6WQjZvf51Ea/M0Q7+T374Jp1aUiyUl0GKxp8M/OETVHSDvmkyPgvX+X2w==", + "dev": true, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/ansi-regex": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.1.1.tgz", + "integrity": "sha512-ILlv4k/3f6vfQ4OoP2AGvirOktlQ98ZEL1k9FaQjxa3L1abBgbuTDAdPOpvbGncC0BTVQrl+OM8xZGK6tWXt7g==", + "dev": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/ansi-styles": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", + "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", + "dev": true, + "dependencies": { + "color-convert": "^1.9.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/argparse": { + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.10.tgz", + "integrity": "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==", + "dev": true, + "dependencies": { + "sprintf-js": "~1.0.2" + } + }, + "node_modules/array-buffer-byte-length": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/array-buffer-byte-length/-/array-buffer-byte-length-1.0.1.tgz", + "integrity": "sha512-ahC5W1xgou+KTXix4sAO8Ki12Q+jf4i0+tmk3sC+zgcynshkHxzpXdImBehiUYKKKDwvfFiJl1tZt6ewscS1Mg==", + "dev": true, + "dependencies": { + "call-bind": "^1.0.5", + "is-array-buffer": "^3.0.4" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/array-includes": { + "version": "3.1.8", + "resolved": "https://registry.npmjs.org/array-includes/-/array-includes-3.1.8.tgz", + "integrity": "sha512-itaWrbYbqpGXkGhZPGUulwnhVf5Hpy1xiCFsGqyIGglbBxmG5vSjxQen3/WGOjPpNEv1RtBLKxbmVXm8HpJStQ==", + "dev": true, + "dependencies": { + "call-bind": "^1.0.7", + "define-properties": "^1.2.1", + "es-abstract": "^1.23.2", + "es-object-atoms": "^1.0.0", + "get-intrinsic": "^1.2.4", + "is-string": "^1.0.7" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/arraybuffer.prototype.slice": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/arraybuffer.prototype.slice/-/arraybuffer.prototype.slice-1.0.3.tgz", + "integrity": "sha512-bMxMKAjg13EBSVscxTaYA4mRc5t1UAXa2kXiGTNfZ079HIWXEkKmkgFrh/nJqamaLSrXO5H4WFFkPEaLJWbs3A==", + "dev": true, + "dependencies": { + "array-buffer-byte-length": "^1.0.1", + "call-bind": "^1.0.5", + "define-properties": "^1.2.1", + "es-abstract": "^1.22.3", + "es-errors": "^1.2.1", + "get-intrinsic": "^1.2.3", + "is-array-buffer": "^3.0.4", + "is-shared-array-buffer": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/astral-regex": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/astral-regex/-/astral-regex-1.0.0.tgz", + "integrity": "sha512-+Ryf6g3BKoRc7jfp7ad8tM4TtMiaWvbF/1/sQcZPkkS7ag3D5nMBCe2UfOTONtAkaG0tO0ij3C5Lwmf1EiyjHg==", + "dev": true, + "engines": { + "node": ">=4" + } + }, + "node_modules/async": { + "version": "2.6.4", + "resolved": "https://registry.npmjs.org/async/-/async-2.6.4.tgz", + "integrity": "sha512-mzo5dfJYwAn29PeiJ0zvwTo04zj8HDJj0Mn8TD7sno7q12prdbnasKJHhkm2c1LgrhlJ0teaea8860oxi51mGA==", + "dev": true, + "dependencies": { + "lodash": "^4.17.14" + } + }, + "node_modules/available-typed-arrays": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/available-typed-arrays/-/available-typed-arrays-1.0.7.tgz", + "integrity": "sha512-wvUjBtSGN7+7SjNpq/9M2Tg350UZD3q62IFZLbRAR1bSMlCo1ZaeW+BJ+D090e4hIIZLBcTDWe4Mh4jvUDajzQ==", + "dev": true, + "dependencies": { + "possible-typed-array-names": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", + "dev": true + }, + "node_modules/base64-js": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", + "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] + }, + "node_modules/basic-auth": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/basic-auth/-/basic-auth-1.1.0.tgz", + "integrity": "sha512-CtGuTyWf3ig+sgRyC7uP6DM3N+5ur/p8L+FPfsd+BbIfIs74TFfCajZTHnCw6K5dqM0bZEbRIqRy1fAdiUJhTA==", + "dev": true, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/brace-expansion": { + "version": "1.1.11", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", + "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", + "dev": true, + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "node_modules/buffer": { + "version": "6.0.3", + "resolved": "https://registry.npmjs.org/buffer/-/buffer-6.0.3.tgz", + "integrity": "sha512-FTiCpNxtwiZZHEZbcbTIcZjERVICn9yq/pDFkTl95/AxzD1naBctN7YO68riM/gLSDY7sdrMby8hofADYuuqOA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "dependencies": { + "base64-js": "^1.3.1", + "ieee754": "^1.2.1" + } + }, + "node_modules/buffer-from": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz", + "integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==", + "dev": true + }, + "node_modules/builtin-modules": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/builtin-modules/-/builtin-modules-3.3.0.tgz", + "integrity": "sha512-zhaCDicdLuWN5UbN5IMnFqNMhNfo919sH85y2/ea+5Yg9TsTkeZxpL+JLbp6cgYFS4sRLp3YV4S6yDuqVWHYOw==", + "dev": true, + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/call-bind": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.7.tgz", + "integrity": "sha512-GHTSNSYICQ7scH7sZ+M2rFopRoLh8t2bLSW6BbgrtLsahOIB5iyAVJf9GjWK3cYTDaMj4XdBpM1cA6pIS0Kv2w==", + "dev": true, + "dependencies": { + "es-define-property": "^1.0.0", + "es-errors": "^1.3.0", + "function-bind": "^1.1.2", + "get-intrinsic": "^1.2.4", + "set-function-length": "^1.2.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/callsites": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz", + "integrity": "sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==", + "dev": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/camelcase": { + "version": "5.3.1", + "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-5.3.1.tgz", + "integrity": "sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg==", + "dev": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/chalk": { + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", + "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", + "dev": true, + "dependencies": { + "ansi-styles": "^3.2.1", + "escape-string-regexp": "^1.0.5", + "supports-color": "^5.3.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/chalk/node_modules/supports-color": { + "version": "5.5.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", + "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", + "dev": true, + "dependencies": { + "has-flag": "^3.0.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/chardet": { + "version": "0.7.0", + "resolved": "https://registry.npmjs.org/chardet/-/chardet-0.7.0.tgz", + "integrity": "sha512-mT8iDcrh03qDGRRmoA2hmBJnxpllMR+0/0qlzjqZES6NdiWDcZkCNAk4rPFZ9Q85r27unkiNNg8ZOiwZXBHwcA==", + "dev": true + }, + "node_modules/cli-cursor": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/cli-cursor/-/cli-cursor-3.1.0.tgz", + "integrity": "sha512-I/zHAwsKf9FqGoXM4WWRACob9+SNukZTd94DWF57E4toouRulbCxcUh6RKUEOQlYTHJnzkPMySvPNaaSLNfLZw==", + "dev": true, + "dependencies": { + "restore-cursor": "^3.1.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/cli-width": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/cli-width/-/cli-width-3.0.0.tgz", + "integrity": "sha512-FxqpkPPwu1HjuN93Omfm4h8uIanXofW0RxVEW3k5RKx+mJJYSthzNhp32Kzxxy3YAEZ/Dc/EWN1vZRY0+kOhbw==", + "dev": true, + "engines": { + "node": ">= 10" + } + }, + "node_modules/cliui": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/cliui/-/cliui-5.0.0.tgz", + "integrity": "sha512-PYeGSEmmHM6zvoef2w8TPzlrnNpXIjTipYK780YswmIP9vjxmd6Y2a3CB2Ks6/AU8NHjZugXvo8w3oWM2qnwXA==", + "dev": true, + "dependencies": { + "string-width": "^3.1.0", + "strip-ansi": "^5.2.0", + "wrap-ansi": "^5.1.0" + } + }, + "node_modules/cliui/node_modules/emoji-regex": { + "version": "7.0.3", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-7.0.3.tgz", + "integrity": "sha512-CwBLREIQ7LvYFB0WyRvwhq5N5qPhc6PMjD6bYggFlI5YyDgl+0vxq5VHbMOFqLg7hfWzmu8T5Z1QofhmTIhItA==", + "dev": true + }, + "node_modules/cliui/node_modules/is-fullwidth-code-point": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-2.0.0.tgz", + "integrity": "sha512-VHskAKYM8RfSFXwee5t5cbN5PZeq1Wrh6qd5bkyiXIf6UQcN6w/A0eXM9r6t8d+GYOh+o6ZhiEnb88LN/Y8m2w==", + "dev": true, + "engines": { + "node": ">=4" + } + }, + "node_modules/cliui/node_modules/string-width": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-3.1.0.tgz", + "integrity": "sha512-vafcv6KjVZKSgz06oM/H6GDBrAtz8vdhQakGjFIvNrHA6y3HCF1CInLy+QLq8dTJPQ1b+KDUqDFctkdRW44e1w==", + "dev": true, + "dependencies": { + "emoji-regex": "^7.0.1", + "is-fullwidth-code-point": "^2.0.0", + "strip-ansi": "^5.1.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/color-convert": { + "version": "1.9.3", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz", + "integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==", + "dev": true, + "dependencies": { + "color-name": "1.1.3" + } + }, + "node_modules/color-name": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz", + "integrity": "sha512-72fSenhMw2HZMTVHeCA9KCmpEIbzWiQsjN+BHcBbS9vr1mtt+vJjPdksIBNUmKAW8TFUDPJK5SUU3QhE9NEXDw==", + "dev": true + }, + "node_modules/colors": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/colors/-/colors-1.4.0.tgz", + "integrity": "sha512-a+UqTh4kgZg/SlGvfbzDHpgRu7AAQOmmqRHJnxhRZICKFUT91brVhNNt58CMWU9PsBbv3PDCZUHbVxuDiH2mtA==", + "dev": true, + "engines": { + "node": ">=0.1.90" + } + }, + "node_modules/commander": { + "version": "2.20.3", + "resolved": "https://registry.npmjs.org/commander/-/commander-2.20.3.tgz", + "integrity": "sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ==", + "dev": true + }, + "node_modules/commondir": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/commondir/-/commondir-1.0.1.tgz", + "integrity": "sha512-W9pAhw0ja1Edb5GVdIF1mjZw/ASI0AlShXM83UUGe2DVr5TdAPEA1OA8m/g8zWp9x6On7gqufY+FatDbC3MDQg==", + "dev": true + }, + "node_modules/concat-map": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", + "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==", + "dev": true + }, + "node_modules/concurrently": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/concurrently/-/concurrently-5.3.0.tgz", + "integrity": "sha512-8MhqOB6PWlBfA2vJ8a0bSFKATOdWlHiQlk11IfmQBPaHVP8oP2gsh2MObE6UR3hqDHqvaIvLTyceNW6obVuFHQ==", + "dev": true, + "dependencies": { + "chalk": "^2.4.2", + "date-fns": "^2.0.1", + "lodash": "^4.17.15", + "read-pkg": "^4.0.1", + "rxjs": "^6.5.2", + "spawn-command": "^0.0.2-1", + "supports-color": "^6.1.0", + "tree-kill": "^1.2.2", + "yargs": "^13.3.0" + }, + "bin": { + "concurrently": "bin/concurrently.js" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/contains-path": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/contains-path/-/contains-path-0.1.0.tgz", + "integrity": "sha512-OKZnPGeMQy2RPaUIBPFFd71iNf4791H12MCRuVQDnzGRwCYNYmTDy5pdafo2SLAcEMKzTOQnLWG4QdcjeJUMEg==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/corser": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/corser/-/corser-2.0.1.tgz", + "integrity": "sha512-utCYNzRSQIZNPIcGZdQc92UVJYAhtGAteCFg0yRaFm8f0P+CPtyGyHXJcGXnffjCybUCEx3FQ2G7U3/o9eIkVQ==", + "dev": true, + "engines": { + "node": ">= 0.4.0" + } + }, + "node_modules/cross-spawn": { + "version": "6.0.5", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-6.0.5.tgz", + "integrity": "sha512-eTVLrBSt7fjbDygz805pMnstIs2VTBNkRm0qxZd+M7A5XDdxVRWO5MxGBXZhjY4cqLYLdtrGqRf8mBPmzwSpWQ==", + "dev": true, + "dependencies": { + "nice-try": "^1.0.4", + "path-key": "^2.0.1", + "semver": "^5.5.0", + "shebang-command": "^1.2.0", + "which": "^1.2.9" + }, + "engines": { + "node": ">=4.8" + } + }, + "node_modules/data-view-buffer": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/data-view-buffer/-/data-view-buffer-1.0.1.tgz", + "integrity": "sha512-0lht7OugA5x3iJLOWFhWK/5ehONdprk0ISXqVFn/NFrDu+cuc8iADFrGQz5BnRK7LLU3JmkbXSxaqX+/mXYtUA==", + "dev": true, + "dependencies": { + "call-bind": "^1.0.6", + "es-errors": "^1.3.0", + "is-data-view": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/data-view-byte-length": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/data-view-byte-length/-/data-view-byte-length-1.0.1.tgz", + "integrity": "sha512-4J7wRJD3ABAzr8wP+OcIcqq2dlUKp4DVflx++hs5h5ZKydWMI6/D/fAot+yh6g2tHh8fLFTvNOaVN357NvSrOQ==", + "dev": true, + "dependencies": { + "call-bind": "^1.0.7", + "es-errors": "^1.3.0", + "is-data-view": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/data-view-byte-offset": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/data-view-byte-offset/-/data-view-byte-offset-1.0.0.tgz", + "integrity": "sha512-t/Ygsytq+R995EJ5PZlD4Cu56sWa8InXySaViRzw9apusqsOO2bQP+SbYzAhR0pFKoB+43lYy8rWban9JSuXnA==", + "dev": true, + "dependencies": { + "call-bind": "^1.0.6", + "es-errors": "^1.3.0", + "is-data-view": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/date-fns": { + "version": "2.30.0", + "resolved": "https://registry.npmjs.org/date-fns/-/date-fns-2.30.0.tgz", + "integrity": "sha512-fnULvOpxnC5/Vg3NCiWelDsLiUc9bRwAPs/+LfTLNvetFCtCTN+yQz15C/fs4AwX1R9K5GLtLfn8QW+dWisaAw==", + "dev": true, + "dependencies": { + "@babel/runtime": "^7.21.0" + }, + "engines": { + "node": ">=0.11" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/date-fns" + } + }, + "node_modules/debug": { + "version": "3.2.7", + "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.7.tgz", + "integrity": "sha512-CFjzYYAi4ThfiQvizrFQevTTXHtnCqWfe7x1AhgEscTz6ZbLbfoLRLPugTQyBth6f8ZERVUSyWHFD/7Wu4t1XQ==", + "dev": true, + "dependencies": { + "ms": "^2.1.1" + } + }, + "node_modules/debug-log": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/debug-log/-/debug-log-1.0.1.tgz", + "integrity": "sha512-gV/pe1YIaKNgLYnd1g9VNW80tcb7oV5qvNUxG7NM8rbDpnl6RGunzlAtlGSb0wEs3nesu2vHNiX9TSsZ+Y+RjA==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/decamelize": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/decamelize/-/decamelize-1.2.0.tgz", + "integrity": "sha512-z2S+W9X73hAUUki+N+9Za2lBlun89zigOyGrsax+KUQ6wKW4ZoWpEYBkGhQjwAjjDCkWxhY0VKEhk8wzY7F5cA==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/deep-is": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.4.tgz", + "integrity": "sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ==", + "dev": true + }, + "node_modules/define-data-property": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/define-data-property/-/define-data-property-1.1.4.tgz", + "integrity": "sha512-rBMvIzlpA8v6E+SJZoo++HAYqsLrkg7MSfIinMPFhmkorw7X+dOXVJQs+QT69zGkzMyfDnIMN2Wid1+NbL3T+A==", + "dev": true, + "dependencies": { + "es-define-property": "^1.0.0", + "es-errors": "^1.3.0", + "gopd": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/define-properties": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/define-properties/-/define-properties-1.2.1.tgz", + "integrity": "sha512-8QmQKqEASLd5nx0U1B1okLElbUuuttJ/AnYmRXbbbGDWh6uS208EjD4Xqq/I9wK7u0v6O08XhTWnt5XtEbR6Dg==", + "dev": true, + "dependencies": { + "define-data-property": "^1.0.1", + "has-property-descriptors": "^1.0.0", + "object-keys": "^1.1.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/deglob": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/deglob/-/deglob-4.0.1.tgz", + "integrity": "sha512-/g+RDZ7yf2HvoW+E5Cy+K94YhgcFgr6C8LuHZD1O5HoNPkf3KY6RfXJ0DBGlB/NkLi5gml+G9zqRzk9S0mHZCg==", + "dev": true, + "dependencies": { + "find-root": "^1.0.0", + "glob": "^7.0.5", + "ignore": "^5.0.0", + "pkg-config": "^1.1.0", + "run-parallel": "^1.1.2", + "uniq": "^1.0.1" + } + }, + "node_modules/deglob/node_modules/ignore": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz", + "integrity": "sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==", + "dev": true, + "engines": { + "node": ">= 4" + } + }, + "node_modules/doctrine": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/doctrine/-/doctrine-3.0.0.tgz", + "integrity": "sha512-yS+Q5i3hBf7GBkd4KG8a7eBNNWNGLTaEwwYWUijIYM7zrlYDM0BFXHjjPWlWZ1Rg7UaddZeIDmi9jF3HmqiQ2w==", + "dev": true, + "dependencies": { + "esutils": "^2.0.2" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/ecstatic": { + "version": "3.3.2", + "resolved": "https://registry.npmjs.org/ecstatic/-/ecstatic-3.3.2.tgz", + "integrity": "sha512-fLf9l1hnwrHI2xn9mEDT7KIi22UDqA2jaCwyCbSUJh9a1V+LEUSL/JO/6TIz/QyuBURWUHrFL5Kg2TtO1bkkog==", + "deprecated": "This package is unmaintained and deprecated. See the GH Issue 259.", + "dev": true, + "dependencies": { + "he": "^1.1.1", + "mime": "^1.6.0", + "minimist": "^1.1.0", + "url-join": "^2.0.5" + }, + "bin": { + "ecstatic": "lib/ecstatic.js" + } + }, + "node_modules/emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", + "dev": true + }, + "node_modules/err-code": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/err-code/-/err-code-3.0.1.tgz", + "integrity": "sha512-GiaH0KJUewYok+eeY05IIgjtAe4Yltygk9Wqp1V5yVWLdhf0hYZchRjNIT9bb0mSwRcIusT3cx7PJUf3zEIfUA==" + }, + "node_modules/error-ex": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/error-ex/-/error-ex-1.3.2.tgz", + "integrity": "sha512-7dFHNmqeFSEt2ZBsCriorKnn3Z2pj+fd9kmI6QoWw4//DL+icEBfc0U7qJCisqrTsKTjw4fNFy2pW9OqStD84g==", + "dev": true, + "dependencies": { + "is-arrayish": "^0.2.1" + } + }, + "node_modules/es-abstract": { + "version": "1.23.3", + "resolved": "https://registry.npmjs.org/es-abstract/-/es-abstract-1.23.3.tgz", + "integrity": "sha512-e+HfNH61Bj1X9/jLc5v1owaLYuHdeHHSQlkhCBiTK8rBvKaULl/beGMxwrMXjpYrv4pz22BlY570vVePA2ho4A==", + "dev": true, + "dependencies": { + "array-buffer-byte-length": "^1.0.1", + "arraybuffer.prototype.slice": "^1.0.3", + "available-typed-arrays": "^1.0.7", + "call-bind": "^1.0.7", + "data-view-buffer": "^1.0.1", + "data-view-byte-length": "^1.0.1", + "data-view-byte-offset": "^1.0.0", + "es-define-property": "^1.0.0", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.0.0", + "es-set-tostringtag": "^2.0.3", + "es-to-primitive": "^1.2.1", + "function.prototype.name": "^1.1.6", + "get-intrinsic": "^1.2.4", + "get-symbol-description": "^1.0.2", + "globalthis": "^1.0.3", + "gopd": "^1.0.1", + "has-property-descriptors": "^1.0.2", + "has-proto": "^1.0.3", + "has-symbols": "^1.0.3", + "hasown": "^2.0.2", + "internal-slot": "^1.0.7", + "is-array-buffer": "^3.0.4", + "is-callable": "^1.2.7", + "is-data-view": "^1.0.1", + "is-negative-zero": "^2.0.3", + "is-regex": "^1.1.4", + "is-shared-array-buffer": "^1.0.3", + "is-string": "^1.0.7", + "is-typed-array": "^1.1.13", + "is-weakref": "^1.0.2", + "object-inspect": "^1.13.1", + "object-keys": "^1.1.1", + "object.assign": "^4.1.5", + "regexp.prototype.flags": "^1.5.2", + "safe-array-concat": "^1.1.2", + "safe-regex-test": "^1.0.3", + "string.prototype.trim": "^1.2.9", + "string.prototype.trimend": "^1.0.8", + "string.prototype.trimstart": "^1.0.8", + "typed-array-buffer": "^1.0.2", + "typed-array-byte-length": "^1.0.1", + "typed-array-byte-offset": "^1.0.2", + "typed-array-length": "^1.0.6", + "unbox-primitive": "^1.0.2", + "which-typed-array": "^1.1.15" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/es-define-property": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.0.tgz", + "integrity": "sha512-jxayLKShrEqqzJ0eumQbVhTYQM27CfT1T35+gCgDFoL82JLsXqTJ76zv6A0YLOgEnLUMvLzsDsGIrl8NFpT2gQ==", + "dev": true, + "dependencies": { + "get-intrinsic": "^1.2.4" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "dev": true, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-object-atoms": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.0.0.tgz", + "integrity": "sha512-MZ4iQ6JwHOBQjahnjwaC1ZtIBH+2ohjamzAO3oaHcXYup7qxjF2fixyH+Q71voWHeOkI2q/TnJao/KfXYIZWbw==", + "dev": true, + "dependencies": { + "es-errors": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-set-tostringtag": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.0.3.tgz", + "integrity": "sha512-3T8uNMC3OQTHkFUsFq8r/BwAXLHvU/9O9mE0fBc/MY5iq/8H7ncvO947LmYA6ldWw9Uh8Yhf25zu6n7nML5QWQ==", + "dev": true, + "dependencies": { + "get-intrinsic": "^1.2.4", + "has-tostringtag": "^1.0.2", + "hasown": "^2.0.1" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-to-primitive": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/es-to-primitive/-/es-to-primitive-1.2.1.tgz", + "integrity": "sha512-QCOllgZJtaUo9miYBcLChTUaHNjJF3PYs1VidD7AwiEj1kYxKeQTctLAezAOH5ZKRH0g2IgPn6KwB4IT8iRpvA==", + "dev": true, + "dependencies": { + "is-callable": "^1.1.4", + "is-date-object": "^1.0.1", + "is-symbol": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/escape-string-regexp": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", + "integrity": "sha512-vbRorB5FUQWvla16U8R/qgaFIya2qGzwDrNmCZuYKrbdSUMG6I1ZCGQRefkRVhuOkIGVne7BQ35DSfo1qvJqFg==", + "dev": true, + "engines": { + "node": ">=0.8.0" + } + }, + "node_modules/eslint": { + "version": "6.8.0", + "resolved": "https://registry.npmjs.org/eslint/-/eslint-6.8.0.tgz", + "integrity": "sha512-K+Iayyo2LtyYhDSYwz5D5QdWw0hCacNzyq1Y821Xna2xSJj7cijoLLYmLxTQgcgZ9mC61nryMy9S7GRbYpI5Ig==", + "deprecated": "This version is no longer supported. Please see https://eslint.org/version-support for other options.", + "dev": true, + "dependencies": { + "@babel/code-frame": "^7.0.0", + "ajv": "^6.10.0", + "chalk": "^2.1.0", + "cross-spawn": "^6.0.5", + "debug": "^4.0.1", + "doctrine": "^3.0.0", + "eslint-scope": "^5.0.0", + "eslint-utils": "^1.4.3", + "eslint-visitor-keys": "^1.1.0", + "espree": "^6.1.2", + "esquery": "^1.0.1", + "esutils": "^2.0.2", + "file-entry-cache": "^5.0.1", + "functional-red-black-tree": "^1.0.1", + "glob-parent": "^5.0.0", + "globals": "^12.1.0", + "ignore": "^4.0.6", + "import-fresh": "^3.0.0", + "imurmurhash": "^0.1.4", + "inquirer": "^7.0.0", + "is-glob": "^4.0.0", + "js-yaml": "^3.13.1", + "json-stable-stringify-without-jsonify": "^1.0.1", + "levn": "^0.3.0", + "lodash": "^4.17.14", + "minimatch": "^3.0.4", + "mkdirp": "^0.5.1", + "natural-compare": "^1.4.0", + "optionator": "^0.8.3", + "progress": "^2.0.0", + "regexpp": "^2.0.1", + "semver": "^6.1.2", + "strip-ansi": "^5.2.0", + "strip-json-comments": "^3.0.1", + "table": "^5.2.3", + "text-table": "^0.2.0", + "v8-compile-cache": "^2.0.3" + }, + "bin": { + "eslint": "bin/eslint.js" + }, + "engines": { + "node": "^8.10.0 || ^10.13.0 || >=11.10.1" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/eslint-config-standard": { + "version": "14.1.1", + "resolved": "https://registry.npmjs.org/eslint-config-standard/-/eslint-config-standard-14.1.1.tgz", + "integrity": "sha512-Z9B+VR+JIXRxz21udPTL9HpFMyoMUEeX1G251EQ6e05WD9aPVtVBn09XUmZ259wCMlCDmYDSZG62Hhm+ZTJcUg==", + "dev": true, + "peerDependencies": { + "eslint": ">=6.2.2", + "eslint-plugin-import": ">=2.18.0", + "eslint-plugin-node": ">=9.1.0", + "eslint-plugin-promise": ">=4.2.1", + "eslint-plugin-standard": ">=4.0.0" + } + }, + "node_modules/eslint-config-standard-jsx": { + "version": "8.1.0", + "resolved": "https://registry.npmjs.org/eslint-config-standard-jsx/-/eslint-config-standard-jsx-8.1.0.tgz", + "integrity": "sha512-ULVC8qH8qCqbU792ZOO6DaiaZyHNS/5CZt3hKqHkEhVlhPEPN3nfBqqxJCyp59XrjIBZPu1chMYe9T2DXZ7TMw==", + "dev": true, + "peerDependencies": { + "eslint": ">=6.2.2", + "eslint-plugin-react": ">=7.14.2" + } + }, + "node_modules/eslint-import-resolver-node": { + "version": "0.3.9", + "resolved": "https://registry.npmjs.org/eslint-import-resolver-node/-/eslint-import-resolver-node-0.3.9.tgz", + "integrity": "sha512-WFj2isz22JahUv+B788TlO3N6zL3nNJGU8CcZbPZvVEkBPaJdCV4vy5wyghty5ROFbCRnm132v8BScu5/1BQ8g==", + "dev": true, + "dependencies": { + "debug": "^3.2.7", + "is-core-module": "^2.13.0", + "resolve": "^1.22.4" + } + }, + "node_modules/eslint-module-utils": { + "version": "2.12.0", + "resolved": "https://registry.npmjs.org/eslint-module-utils/-/eslint-module-utils-2.12.0.tgz", + "integrity": "sha512-wALZ0HFoytlyh/1+4wuZ9FJCD/leWHQzzrxJ8+rebyReSLk7LApMyd3WJaLVoN+D5+WIdJyDK1c6JnE65V4Zyg==", + "dev": true, + "dependencies": { + "debug": "^3.2.7" + }, + "engines": { + "node": ">=4" + }, + "peerDependenciesMeta": { + "eslint": { + "optional": true + } + } + }, + "node_modules/eslint-plugin-es": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/eslint-plugin-es/-/eslint-plugin-es-2.0.0.tgz", + "integrity": "sha512-f6fceVtg27BR02EYnBhgWLFQfK6bN4Ll0nQFrBHOlCsAyxeZkn0NHns5O0YZOPrV1B3ramd6cgFwaoFLcSkwEQ==", + "dev": true, + "dependencies": { + "eslint-utils": "^1.4.2", + "regexpp": "^3.0.0" + }, + "engines": { + "node": ">=8.10.0" + }, + "peerDependencies": { + "eslint": ">=4.19.1" + } + }, + "node_modules/eslint-plugin-es/node_modules/regexpp": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/regexpp/-/regexpp-3.2.0.tgz", + "integrity": "sha512-pq2bWo9mVD43nbts2wGv17XLiNLya+GklZ8kaDLV2Z08gDCsGpnKn9BFMepvWuHCbyVvY7J5o5+BVvoQbmlJLg==", + "dev": true, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/mysticatea" + } + }, + "node_modules/eslint-plugin-import": { + "version": "2.18.2", + "resolved": "https://registry.npmjs.org/eslint-plugin-import/-/eslint-plugin-import-2.18.2.tgz", + "integrity": "sha512-5ohpsHAiUBRNaBWAF08izwUGlbrJoJJ+W9/TBwsGoR1MnlgfwMIKrFeSjWbt6moabiXW9xNvtFz+97KHRfI4HQ==", + "dev": true, + "dependencies": { + "array-includes": "^3.0.3", + "contains-path": "^0.1.0", + "debug": "^2.6.9", + "doctrine": "1.5.0", + "eslint-import-resolver-node": "^0.3.2", + "eslint-module-utils": "^2.4.0", + "has": "^1.0.3", + "minimatch": "^3.0.4", + "object.values": "^1.1.0", + "read-pkg-up": "^2.0.0", + "resolve": "^1.11.0" + }, + "engines": { + "node": ">=4" + }, + "peerDependencies": { + "eslint": "2.x - 6.x" + } + }, + "node_modules/eslint-plugin-import/node_modules/debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "dev": true, + "dependencies": { + "ms": "2.0.0" + } + }, + "node_modules/eslint-plugin-import/node_modules/doctrine": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/doctrine/-/doctrine-1.5.0.tgz", + "integrity": "sha512-lsGyRuYr4/PIB0txi+Fy2xOMI2dGaTguCaotzFGkVZuKR5usKfcRWIFKNM3QNrU7hh/+w2bwTW+ZeXPK5l8uVg==", + "dev": true, + "dependencies": { + "esutils": "^2.0.2", + "isarray": "^1.0.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/eslint-plugin-import/node_modules/isarray": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", + "integrity": "sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ==", + "dev": true + }, + "node_modules/eslint-plugin-import/node_modules/ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==", + "dev": true + }, + "node_modules/eslint-plugin-node": { + "version": "10.0.0", + "resolved": "https://registry.npmjs.org/eslint-plugin-node/-/eslint-plugin-node-10.0.0.tgz", + "integrity": "sha512-1CSyM/QCjs6PXaT18+zuAXsjXGIGo5Rw630rSKwokSs2jrYURQc4R5JZpoanNCqwNmepg+0eZ9L7YiRUJb8jiQ==", + "dev": true, + "dependencies": { + "eslint-plugin-es": "^2.0.0", + "eslint-utils": "^1.4.2", + "ignore": "^5.1.1", + "minimatch": "^3.0.4", + "resolve": "^1.10.1", + "semver": "^6.1.0" + }, + "engines": { + "node": ">=8.10.0" + }, + "peerDependencies": { + "eslint": ">=5.16.0" + } + }, + "node_modules/eslint-plugin-node/node_modules/ignore": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz", + "integrity": "sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==", + "dev": true, + "engines": { + "node": ">= 4" + } + }, + "node_modules/eslint-plugin-node/node_modules/semver": { + "version": "6.3.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", + "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", + "dev": true, + "bin": { + "semver": "bin/semver.js" + } + }, + "node_modules/eslint-plugin-promise": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/eslint-plugin-promise/-/eslint-plugin-promise-4.2.1.tgz", + "integrity": "sha512-VoM09vT7bfA7D+upt+FjeBO5eHIJQBUWki1aPvB+vbNiHS3+oGIJGIeyBtKQTME6UPXXy3vV07OL1tHd3ANuDw==", + "dev": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/eslint-plugin-react": { + "version": "7.14.3", + "resolved": "https://registry.npmjs.org/eslint-plugin-react/-/eslint-plugin-react-7.14.3.tgz", + "integrity": "sha512-EzdyyBWC4Uz2hPYBiEJrKCUi2Fn+BJ9B/pJQcjw5X+x/H2Nm59S4MJIvL4O5NEE0+WbnQwEBxWY03oUk+Bc3FA==", + "dev": true, + "dependencies": { + "array-includes": "^3.0.3", + "doctrine": "^2.1.0", + "has": "^1.0.3", + "jsx-ast-utils": "^2.1.0", + "object.entries": "^1.1.0", + "object.fromentries": "^2.0.0", + "object.values": "^1.1.0", + "prop-types": "^15.7.2", + "resolve": "^1.10.1" + }, + "engines": { + "node": ">=4" + }, + "peerDependencies": { + "eslint": "^3.0.0 || ^4.0.0 || ^5.0.0 || ^6.0.0" + } + }, + "node_modules/eslint-plugin-react/node_modules/doctrine": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/doctrine/-/doctrine-2.1.0.tgz", + "integrity": "sha512-35mSku4ZXK0vfCuHEDAwt55dg2jNajHZ1odvF+8SSr82EsZY4QmXfuWso8oEd8zRhVObSN18aM0CjSdoBX7zIw==", + "dev": true, + "dependencies": { + "esutils": "^2.0.2" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/eslint-plugin-standard": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/eslint-plugin-standard/-/eslint-plugin-standard-4.0.2.tgz", + "integrity": "sha512-nKptN8l7jksXkwFk++PhJB3cCDTcXOEyhISIN86Ue2feJ1LFyY3PrY3/xT2keXlJSY5bpmbiTG0f885/YKAvTA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "peerDependencies": { + "eslint": ">=5.0.0" + } + }, + "node_modules/eslint-scope": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-5.1.1.tgz", + "integrity": "sha512-2NxwbF/hZ0KpepYN0cNbo+FN6XoK7GaHlQhgx/hIZl6Va0bF45RQOOwhLIy8lQDbuCiadSLCBnH2CFYquit5bw==", + "dev": true, + "dependencies": { + "esrecurse": "^4.3.0", + "estraverse": "^4.1.1" + }, + "engines": { + "node": ">=8.0.0" + } + }, + "node_modules/eslint-utils": { + "version": "1.4.3", + "resolved": "https://registry.npmjs.org/eslint-utils/-/eslint-utils-1.4.3.tgz", + "integrity": "sha512-fbBN5W2xdY45KulGXmLHZ3c3FHfVYmKg0IrAKGOkT/464PQsx2UeIzfz1RmEci+KLm1bBaAzZAh8+/E+XAeZ8Q==", + "dev": true, + "dependencies": { + "eslint-visitor-keys": "^1.1.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/eslint-visitor-keys": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-1.3.0.tgz", + "integrity": "sha512-6J72N8UNa462wa/KFODt/PJ3IU60SDpC3QXC1Hjc1BXXpfL2C9R5+AU7jhe0F6GREqVMh4Juu+NY7xn+6dipUQ==", + "dev": true, + "engines": { + "node": ">=4" + } + }, + "node_modules/eslint/node_modules/debug": { + "version": "4.3.7", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.7.tgz", + "integrity": "sha512-Er2nc/H7RrMXZBFCEim6TCmMk02Z8vLC2Rbi1KEBggpo0fS6l0S1nnapwmIi3yW/+GOJap1Krg4w0Hg80oCqgQ==", + "dev": true, + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/eslint/node_modules/semver": { + "version": "6.3.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", + "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", + "dev": true, + "bin": { + "semver": "bin/semver.js" + } + }, + "node_modules/espree": { + "version": "6.2.1", + "resolved": "https://registry.npmjs.org/espree/-/espree-6.2.1.tgz", + "integrity": "sha512-ysCxRQY3WaXJz9tdbWOwuWr5Y/XrPTGX9Kiz3yoUXwW0VZ4w30HTkQLaGx/+ttFjF8i+ACbArnB4ce68a9m5hw==", + "dev": true, + "dependencies": { + "acorn": "^7.1.1", + "acorn-jsx": "^5.2.0", + "eslint-visitor-keys": "^1.1.0" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/esprima": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.1.tgz", + "integrity": "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==", + "dev": true, + "bin": { + "esparse": "bin/esparse.js", + "esvalidate": "bin/esvalidate.js" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/esquery": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/esquery/-/esquery-1.6.0.tgz", + "integrity": "sha512-ca9pw9fomFcKPvFLXhBKUK90ZvGibiGOvRJNbjljY7s7uq/5YO4BOzcYtJqExdx99rF6aAcnRxHmcUHcz6sQsg==", + "dev": true, + "dependencies": { + "estraverse": "^5.1.0" + }, + "engines": { + "node": ">=0.10" + } + }, + "node_modules/esquery/node_modules/estraverse": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz", + "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==", + "dev": true, + "engines": { + "node": ">=4.0" + } + }, + "node_modules/esrecurse": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/esrecurse/-/esrecurse-4.3.0.tgz", + "integrity": "sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag==", + "dev": true, + "dependencies": { + "estraverse": "^5.2.0" + }, + "engines": { + "node": ">=4.0" + } + }, + "node_modules/esrecurse/node_modules/estraverse": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz", + "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==", + "dev": true, + "engines": { + "node": ">=4.0" + } + }, + "node_modules/estraverse": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-4.3.0.tgz", + "integrity": "sha512-39nnKffWz8xN1BU/2c79n9nB9HDzo0niYUqx6xyqUnyoAnQyyWpOTdZEeiCch8BBu515t4wp9ZmgVfVhn9EBpw==", + "dev": true, + "engines": { + "node": ">=4.0" + } + }, + "node_modules/estree-walker": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-1.0.1.tgz", + "integrity": "sha512-1fMXF3YP4pZZVozF8j/ZLfvnR8NSIljt56UhbZ5PeeDmmGHpgpdwQt7ITlGvYaQukCvuBRMLEiKiYC+oeIg4cg==", + "dev": true + }, + "node_modules/esutils": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.3.tgz", + "integrity": "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/eventemitter3": { + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-4.0.7.tgz", + "integrity": "sha512-8guHBZCwKnFhYdHr2ysuRWErTwhoN2X8XELRlrRwpmfeY2jjuUN4taQMsULKUVo1K4DvZl+0pgfyoysHxvmvEw==", + "dev": true + }, + "node_modules/external-editor": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/external-editor/-/external-editor-3.1.0.tgz", + "integrity": "sha512-hMQ4CX1p1izmuLYyZqLMO/qGNw10wSv9QDCPfzXfyFrOaCSSoRfqE1Kf1s5an66J5JZC62NewG+mK49jOCtQew==", + "dev": true, + "dependencies": { + "chardet": "^0.7.0", + "iconv-lite": "^0.4.24", + "tmp": "^0.0.33" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/fast-deep-equal": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", + "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", + "dev": true + }, + "node_modules/fast-json-stable-stringify": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz", + "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==", + "dev": true + }, + "node_modules/fast-levenshtein": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz", + "integrity": "sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw==", + "dev": true + }, + "node_modules/figures": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/figures/-/figures-3.2.0.tgz", + "integrity": "sha512-yaduQFRKLXYOGgEn6AZau90j3ggSOyiqXU0F9JZfeXYhNa+Jk4X+s45A2zg5jns87GAFa34BBm2kXw4XpNcbdg==", + "dev": true, + "dependencies": { + "escape-string-regexp": "^1.0.5" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/file-entry-cache": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-5.0.1.tgz", + "integrity": "sha512-bCg29ictuBaKUwwArK4ouCaqDgLZcysCFLmM/Yn/FDoqndh/9vNuQfXRDvTuXKLxfD/JtZQGKFT8MGcJBK644g==", + "dev": true, + "dependencies": { + "flat-cache": "^2.0.1" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/find-root": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/find-root/-/find-root-1.1.0.tgz", + "integrity": "sha512-NKfW6bec6GfKc0SGx1e07QZY9PE99u0Bft/0rzSD5k3sO/vwkVUpDUKVm5Gpp5Ue3YfShPFTX2070tDs5kB9Ng==", + "dev": true + }, + "node_modules/find-up": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-2.1.0.tgz", + "integrity": "sha512-NWzkk0jSJtTt08+FBFMvXoeZnOJD+jTtsRmBYbAIzJdX6l7dLgR7CTubCM5/eDdPUBvLCeVasP1brfVR/9/EZQ==", + "dev": true, + "dependencies": { + "locate-path": "^2.0.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/flat-cache": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/flat-cache/-/flat-cache-2.0.1.tgz", + "integrity": "sha512-LoQe6yDuUMDzQAEH8sgmh4Md6oZnc/7PjtwjNFSzveXqSHt6ka9fPBuso7IGf9Rz4uqnSnWiFH2B/zj24a5ReA==", + "dev": true, + "dependencies": { + "flatted": "^2.0.0", + "rimraf": "2.6.3", + "write": "1.0.3" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/flatted": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/flatted/-/flatted-2.0.2.tgz", + "integrity": "sha512-r5wGx7YeOwNWNlCA0wQ86zKyDLMQr+/RB8xy74M4hTphfmjlijTSSXGuH8rnvKZnfT9i+75zmd8jcKdMR4O6jA==", + "dev": true + }, + "node_modules/follow-redirects": { + "version": "1.15.9", + "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.9.tgz", + "integrity": "sha512-gew4GsXizNgdoRyqmyfMHyAmXsZDk6mHkSxZFCzW9gwlbtOW44CDtYavM+y+72qD/Vq2l550kMF52DT8fOLJqQ==", + "dev": true, + "funding": [ + { + "type": "individual", + "url": "https://github.com/sponsors/RubenVerborgh" + } + ], + "engines": { + "node": ">=4.0" + }, + "peerDependenciesMeta": { + "debug": { + "optional": true + } + } + }, + "node_modules/for-each": { + "version": "0.3.3", + "resolved": "https://registry.npmjs.org/for-each/-/for-each-0.3.3.tgz", + "integrity": "sha512-jqYfLp7mo9vIyQf8ykW2v7A+2N4QjeCeI5+Dz9XraiO1ign81wjiH7Fb9vSOWvQfNtmSa4H2RoQTrrXivdUZmw==", + "dev": true, + "dependencies": { + "is-callable": "^1.1.3" + } + }, + "node_modules/fs.realpath": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", + "integrity": "sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==", + "dev": true + }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "dev": true, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/function.prototype.name": { + "version": "1.1.6", + "resolved": "https://registry.npmjs.org/function.prototype.name/-/function.prototype.name-1.1.6.tgz", + "integrity": "sha512-Z5kx79swU5P27WEayXM1tBi5Ze/lbIyiNgU3qyXUOf9b2rgXYyF9Dy9Cx+IQv/Lc8WCG6L82zwUPpSS9hGehIg==", + "dev": true, + "dependencies": { + "call-bind": "^1.0.2", + "define-properties": "^1.2.0", + "es-abstract": "^1.22.1", + "functions-have-names": "^1.2.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/functional-red-black-tree": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/functional-red-black-tree/-/functional-red-black-tree-1.0.1.tgz", + "integrity": "sha512-dsKNQNdj6xA3T+QlADDA7mOSlX0qiMINjn0cgr+eGHGsbSHzTabcIogz2+p/iqP1Xs6EP/sS2SbqH+brGTbq0g==", + "dev": true + }, + "node_modules/functions-have-names": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/functions-have-names/-/functions-have-names-1.2.3.tgz", + "integrity": "sha512-xckBUXyTIqT97tq2x2AMb+g163b5JFysYk0x4qxNFwbfQkmNZoiRHb6sPzI9/QV33WeuvVYBUIiD4NzNIyqaRQ==", + "dev": true, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-browser-rtc": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/get-browser-rtc/-/get-browser-rtc-1.1.0.tgz", + "integrity": "sha512-MghbMJ61EJrRsDe7w1Bvqt3ZsBuqhce5nrn/XAwgwOXhcsz53/ltdxOse1h/8eKXj5slzxdsz56g5rzOFSGwfQ==" + }, + "node_modules/get-caller-file": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", + "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==", + "dev": true, + "engines": { + "node": "6.* || 8.* || >= 10.*" + } + }, + "node_modules/get-intrinsic": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.2.4.tgz", + "integrity": "sha512-5uYhsJH8VJBTv7oslg4BznJYhDoRI6waYCxMmCdnTrcCrHA/fCFKoTFz2JKKE0HdDFUF7/oQuhzumXJK7paBRQ==", + "dev": true, + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2", + "has-proto": "^1.0.1", + "has-symbols": "^1.0.3", + "hasown": "^2.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-stdin": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/get-stdin/-/get-stdin-7.0.0.tgz", + "integrity": "sha512-zRKcywvrXlXsA0v0i9Io4KDRaAw7+a1ZpjRwl9Wox8PFlVCCHra7E9c4kqXCoCM9nR5tBkaTTZRBoCm60bFqTQ==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/get-symbol-description": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/get-symbol-description/-/get-symbol-description-1.0.2.tgz", + "integrity": "sha512-g0QYk1dZBxGwk+Ngc+ltRH2IBp2f7zBkBMBJZCDerh6EhlhSR6+9irMCuT/09zD6qkarHUSn529sK/yL4S27mg==", + "dev": true, + "dependencies": { + "call-bind": "^1.0.5", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.4" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/glob": { + "version": "7.2.3", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz", + "integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==", + "deprecated": "Glob versions prior to v9 are no longer supported", + "dev": true, + "dependencies": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.1.1", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + }, + "engines": { + "node": "*" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/glob-parent": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz", + "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==", + "dev": true, + "dependencies": { + "is-glob": "^4.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/globals": { + "version": "12.4.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-12.4.0.tgz", + "integrity": "sha512-BWICuzzDvDoH54NHKCseDanAhE3CeDorgDL5MT6LMXXj2WCnd9UC2szdk4AWLfjdgNBCXLUanXYcpBBKOSWGwg==", + "dev": true, + "dependencies": { + "type-fest": "^0.8.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/globalthis": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/globalthis/-/globalthis-1.0.4.tgz", + "integrity": "sha512-DpLKbNU4WylpxJykQujfCcwYWiV/Jhm50Goo0wrVILAv5jOr9d+H+UR3PhSCD2rCCEIg0uc+G+muBTwD54JhDQ==", + "dev": true, + "dependencies": { + "define-properties": "^1.2.1", + "gopd": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/gopd": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.0.1.tgz", + "integrity": "sha512-d65bNlIadxvpb/A2abVdlqKqV563juRnZ1Wtk6s1sIR8uNsXR70xqIzVqxVf1eTqDunwT2MkczEeaezCKTZhwA==", + "dev": true, + "dependencies": { + "get-intrinsic": "^1.1.3" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/graceful-fs": { + "version": "4.2.11", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz", + "integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==", + "dev": true + }, + "node_modules/has": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/has/-/has-1.0.4.tgz", + "integrity": "sha512-qdSAmqLF6209RFj4VVItywPMbm3vWylknmB3nvNiUIs72xAimcM8nVYxYr7ncvZq5qzk9MKIZR8ijqD/1QuYjQ==", + "dev": true, + "engines": { + "node": ">= 0.4.0" + } + }, + "node_modules/has-bigints": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-bigints/-/has-bigints-1.0.2.tgz", + "integrity": "sha512-tSvCKtBr9lkF0Ex0aQiP9N+OpV4zi2r/Nee5VkRDbaqv35RLYMzbwQfFSZZH0kR+Rd6302UJZ2p/bJCEoR3VoQ==", + "dev": true, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-flag": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", + "integrity": "sha512-sKJf1+ceQBr4SMkvQnBDNDtf4TXpVhVGateu0t918bl30FnbE2m4vNLX+VWe/dpjlb+HugGYzW7uQXH98HPEYw==", + "dev": true, + "engines": { + "node": ">=4" + } + }, + "node_modules/has-property-descriptors": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-property-descriptors/-/has-property-descriptors-1.0.2.tgz", + "integrity": "sha512-55JNKuIW+vq4Ke1BjOTjM2YctQIvCT7GFzHwmfZPGo5wnrgkid0YQtnAleFSqumZm4az3n2BS+erby5ipJdgrg==", + "dev": true, + "dependencies": { + "es-define-property": "^1.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-proto": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/has-proto/-/has-proto-1.0.3.tgz", + "integrity": "sha512-SJ1amZAJUiZS+PhsVLf5tGydlaVB8EdFpaSO4gmiUKUOxk8qzn5AIy4ZeJUmh22znIdk/uMAUT2pl3FxzVUH+Q==", + "dev": true, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-symbols": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.3.tgz", + "integrity": "sha512-l3LCuF6MgDNwTDKkdYGEihYjt5pRPbEg46rtlmnSPlUbgmB8LOIrKJbYYFBSbnPaJexMKtiPO8hmeRjRz2Td+A==", + "dev": true, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-tostringtag": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz", + "integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==", + "dev": true, + "dependencies": { + "has-symbols": "^1.0.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/hasown": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz", + "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==", + "dev": true, + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/he": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/he/-/he-1.2.0.tgz", + "integrity": "sha512-F/1DnUGPopORZi0ni+CvrCgHQ5FyEAHRLSApuYWMmrbSwoN2Mn/7k+Gl38gJnR7yyDZk6WLXwiGod1JOWNDKGw==", + "dev": true, + "bin": { + "he": "bin/he" + } + }, + "node_modules/hosted-git-info": { + "version": "2.8.9", + "resolved": "https://registry.npmjs.org/hosted-git-info/-/hosted-git-info-2.8.9.tgz", + "integrity": "sha512-mxIDAb9Lsm6DoOJ7xH+5+X4y1LU/4Hi50L9C5sIswK3JzULS4bwk1FvjdBgvYR4bzT4tuUQiC15FE2f5HbLvYw==", + "dev": true + }, + "node_modules/http-proxy": { + "version": "1.18.1", + "resolved": "https://registry.npmjs.org/http-proxy/-/http-proxy-1.18.1.tgz", + "integrity": "sha512-7mz/721AbnJwIVbnaSv1Cz3Am0ZLT/UBwkC92VlxhXv/k/BBQfM2fXElQNC27BVGr0uwUpplYPQM9LnaBMR5NQ==", + "dev": true, + "dependencies": { + "eventemitter3": "^4.0.0", + "follow-redirects": "^1.0.0", + "requires-port": "^1.0.0" + }, + "engines": { + "node": ">=8.0.0" + } + }, + "node_modules/http-server": { + "version": "0.12.3", + "resolved": "https://registry.npmjs.org/http-server/-/http-server-0.12.3.tgz", + "integrity": "sha512-be0dKG6pni92bRjq0kvExtj/NrrAd28/8fCXkaI/4piTwQMSDSLMhWyW0NI1V+DBI3aa1HMlQu46/HjVLfmugA==", + "dev": true, + "dependencies": { + "basic-auth": "^1.0.3", + "colors": "^1.4.0", + "corser": "^2.0.1", + "ecstatic": "^3.3.2", + "http-proxy": "^1.18.0", + "minimist": "^1.2.5", + "opener": "^1.5.1", + "portfinder": "^1.0.25", + "secure-compare": "3.0.1", + "union": "~0.5.0" + }, + "bin": { + "hs": "bin/http-server", + "http-server": "bin/http-server" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/iconv-lite": { + "version": "0.4.24", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz", + "integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==", + "dev": true, + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/ieee754": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz", + "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] + }, + "node_modules/ignore": { + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/ignore/-/ignore-4.0.6.tgz", + "integrity": "sha512-cyFDKrqc/YdcWFniJhzI42+AzS+gNwmUzOSFcRCQYwySuBBBy/KjuxWLZ/FHEH6Moq1NizMOBWyTcv8O4OZIMg==", + "dev": true, + "engines": { + "node": ">= 4" + } + }, + "node_modules/import-fresh": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/import-fresh/-/import-fresh-3.3.0.tgz", + "integrity": "sha512-veYYhQa+D1QBKznvhUHxb8faxlrwUnxseDAbAp457E0wLNio2bOSKnjYDhMj+YiAq61xrMGhQk9iXVk5FzgQMw==", + "dev": true, + "dependencies": { + "parent-module": "^1.0.0", + "resolve-from": "^4.0.0" + }, + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/imurmurhash": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz", + "integrity": "sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==", + "dev": true, + "engines": { + "node": ">=0.8.19" + } + }, + "node_modules/inflight": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", + "integrity": "sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA==", + "deprecated": "This module is not supported, and leaks memory. Do not use it. Check out lru-cache if you want a good and tested way to coalesce async requests by a key value, which is much more comprehensive and powerful.", + "dev": true, + "dependencies": { + "once": "^1.3.0", + "wrappy": "1" + } + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==" + }, + "node_modules/inquirer": { + "version": "7.3.3", + "resolved": "https://registry.npmjs.org/inquirer/-/inquirer-7.3.3.tgz", + "integrity": "sha512-JG3eIAj5V9CwcGvuOmoo6LB9kbAYT8HXffUl6memuszlwDC/qvFAJw49XJ5NROSFNPxp3iQg1GqkFhaY/CR0IA==", + "dev": true, + "dependencies": { + "ansi-escapes": "^4.2.1", + "chalk": "^4.1.0", + "cli-cursor": "^3.1.0", + "cli-width": "^3.0.0", + "external-editor": "^3.0.3", + "figures": "^3.0.0", + "lodash": "^4.17.19", + "mute-stream": "0.0.8", + "run-async": "^2.4.0", + "rxjs": "^6.6.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0", + "through": "^2.3.6" + }, + "engines": { + "node": ">=8.0.0" + } + }, + "node_modules/inquirer/node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/inquirer/node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "dev": true, + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/inquirer/node_modules/chalk": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", + "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", + "dev": true, + "dependencies": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/inquirer/node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/inquirer/node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true + }, + "node_modules/inquirer/node_modules/has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/inquirer/node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "dev": true, + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/inquirer/node_modules/supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dev": true, + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/internal-slot": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/internal-slot/-/internal-slot-1.0.7.tgz", + "integrity": "sha512-NGnrKwXzSms2qUUih/ILZ5JBqNTSa1+ZmP6flaIp6KmSElgE9qdndzS3cqjrDovwFdmwsGsLdeFgB6suw+1e9g==", + "dev": true, + "dependencies": { + "es-errors": "^1.3.0", + "hasown": "^2.0.0", + "side-channel": "^1.0.4" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/is-array-buffer": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/is-array-buffer/-/is-array-buffer-3.0.4.tgz", + "integrity": "sha512-wcjaerHw0ydZwfhiKbXJWLDY8A7yV7KhjQOpb83hGgGfId/aQa4TOvwyzn2PuswW2gPCYEL/nEAiSVpdOj1lXw==", + "dev": true, + "dependencies": { + "call-bind": "^1.0.2", + "get-intrinsic": "^1.2.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-arrayish": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.2.1.tgz", + "integrity": "sha512-zz06S8t0ozoDXMG+ube26zeCTNXcKIPJZJi8hBrF4idCLms4CG9QtK7qBl1boi5ODzFpjswb5JPmHCbMpjaYzg==", + "dev": true + }, + "node_modules/is-bigint": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/is-bigint/-/is-bigint-1.0.4.tgz", + "integrity": "sha512-zB9CruMamjym81i2JZ3UMn54PKGsQzsJeo6xvN3HJJ4CAsQNB6iRutp2To77OfCNuoxspsIhzaPoO1zyCEhFOg==", + "dev": true, + "dependencies": { + "has-bigints": "^1.0.1" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-boolean-object": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/is-boolean-object/-/is-boolean-object-1.1.2.tgz", + "integrity": "sha512-gDYaKHJmnj4aWxyj6YHyXVpdQawtVLHU5cb+eztPGczf6cjuTdwve5ZIEfgXqH4e57An1D1AKf8CZ3kYrQRqYA==", + "dev": true, + "dependencies": { + "call-bind": "^1.0.2", + "has-tostringtag": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-callable": { + "version": "1.2.7", + "resolved": "https://registry.npmjs.org/is-callable/-/is-callable-1.2.7.tgz", + "integrity": "sha512-1BC0BVFhS/p0qtw6enp8e+8OD0UrK0oFLztSjNzhcKA3WDuJxxAPXzPuPtKkjEY9UUoEWlX/8fgKeu2S8i9JTA==", + "dev": true, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-core-module": { + "version": "2.15.1", + "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.15.1.tgz", + "integrity": "sha512-z0vtXSwucUJtANQWldhbtbt7BnL0vxiFjIdDLAatwhDYty2bad6s+rijD6Ri4YuYJubLzIJLUidCh09e1djEVQ==", + "dev": true, + "dependencies": { + "hasown": "^2.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-data-view": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/is-data-view/-/is-data-view-1.0.1.tgz", + "integrity": "sha512-AHkaJrsUVW6wq6JS8y3JnM/GJF/9cf+k20+iDzlSaJrinEo5+7vRiteOSwBhHRiAyQATN1AmY4hwzxJKPmYf+w==", + "dev": true, + "dependencies": { + "is-typed-array": "^1.1.13" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-date-object": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/is-date-object/-/is-date-object-1.0.5.tgz", + "integrity": "sha512-9YQaSxsAiSwcvS33MBk3wTCVnWK+HhF8VZR2jRxehM16QcVOdHqPn4VPHmRK4lSr38n9JriurInLcP90xsYNfQ==", + "dev": true, + "dependencies": { + "has-tostringtag": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-extglob": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", + "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-fullwidth-code-point": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/is-glob": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", + "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", + "dev": true, + "dependencies": { + "is-extglob": "^2.1.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-module": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-module/-/is-module-1.0.0.tgz", + "integrity": "sha512-51ypPSPCoTEIN9dy5Oy+h4pShgJmPCygKfyRCISBI+JoWT/2oJvK8QPxmwv7b/p239jXrm9M1mlQbyKJ5A152g==", + "dev": true + }, + "node_modules/is-negative-zero": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/is-negative-zero/-/is-negative-zero-2.0.3.tgz", + "integrity": "sha512-5KoIu2Ngpyek75jXodFvnafB6DJgr3u8uuK0LEZJjrU19DrMD3EVERaR8sjz8CCGgpZvxPl9SuE1GMVPFHx1mw==", + "dev": true, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-number-object": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/is-number-object/-/is-number-object-1.0.7.tgz", + "integrity": "sha512-k1U0IRzLMo7ZlYIfzRu23Oh6MiIFasgpb9X76eqfFZAqwH44UI4KTBvBYIZ1dSL9ZzChTB9ShHfLkR4pdW5krQ==", + "dev": true, + "dependencies": { + "has-tostringtag": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-reference": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/is-reference/-/is-reference-1.2.1.tgz", + "integrity": "sha512-U82MsXXiFIrjCK4otLT+o2NA2Cd2g5MLoOVXUZjIOhLurrRxpEXzI8O0KZHr3IjLvlAH1kTPYSuqer5T9ZVBKQ==", + "dev": true, + "dependencies": { + "@types/estree": "*" + } + }, + "node_modules/is-regex": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/is-regex/-/is-regex-1.1.4.tgz", + "integrity": "sha512-kvRdxDsxZjhzUX07ZnLydzS1TU/TJlTUHHY4YLL87e37oUA49DfkLqgy+VjFocowy29cKvcSiu+kIv728jTTVg==", + "dev": true, + "dependencies": { + "call-bind": "^1.0.2", + "has-tostringtag": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-shared-array-buffer": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/is-shared-array-buffer/-/is-shared-array-buffer-1.0.3.tgz", + "integrity": "sha512-nA2hv5XIhLR3uVzDDfCIknerhx8XUKnstuOERPNNIinXG7v9u+ohXF67vxm4TPTEPU6lm61ZkwP3c9PCB97rhg==", + "dev": true, + "dependencies": { + "call-bind": "^1.0.7" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-string": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/is-string/-/is-string-1.0.7.tgz", + "integrity": "sha512-tE2UXzivje6ofPW7l23cjDOMa09gb7xlAqG6jG5ej6uPV32TlWP3NKPigtaGeHNu9fohccRYvIiZMfOOnOYUtg==", + "dev": true, + "dependencies": { + "has-tostringtag": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-symbol": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/is-symbol/-/is-symbol-1.0.4.tgz", + "integrity": "sha512-C/CPBqKWnvdcxqIARxyOh4v1UUEOCHpgDa0WYgpKDFMszcrPcffg5uhwSgPCLD2WWxmq6isisz87tzT01tuGhg==", + "dev": true, + "dependencies": { + "has-symbols": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-typed-array": { + "version": "1.1.13", + "resolved": "https://registry.npmjs.org/is-typed-array/-/is-typed-array-1.1.13.tgz", + "integrity": "sha512-uZ25/bUAlUY5fR4OKT4rZQEBrzQWYV9ZJYGGsUmEJ6thodVJ1HX64ePQ6Z0qPWP+m+Uq6e9UugrE38jeYsDSMw==", + "dev": true, + "dependencies": { + "which-typed-array": "^1.1.14" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-weakref": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/is-weakref/-/is-weakref-1.0.2.tgz", + "integrity": "sha512-qctsuLZmIQ0+vSSMfoVvyFe2+GSEvnmZ2ezTup1SBse9+twCCeial6EEi3Nc2KFcf6+qz2FBPnjXsk8xhKSaPQ==", + "dev": true, + "dependencies": { + "call-bind": "^1.0.2" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/isarray": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-2.0.5.tgz", + "integrity": "sha512-xHjhDr3cNBK0BzdUJSPXZntQUx/mwMS5Rw4A7lPJ90XGAO6ISP/ePDNuo0vhqOZU+UD5JoodwCAAoZQd3FeAKw==", + "dev": true + }, + "node_modules/isexe": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", + "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==", + "dev": true + }, + "node_modules/isomorphic.js": { + "version": "0.2.5", + "resolved": "https://registry.npmjs.org/isomorphic.js/-/isomorphic.js-0.2.5.tgz", + "integrity": "sha512-PIeMbHqMt4DnUP3MA/Flc0HElYjMXArsw1qwJZcm9sqR8mq3l8NYizFMty0pWwE/tzIGH3EKK5+jes5mAr85yw==", + "funding": { + "type": "GitHub Sponsors ❤", + "url": "https://github.com/sponsors/dmonad" + } + }, + "node_modules/jest-worker": { + "version": "24.9.0", + "resolved": "https://registry.npmjs.org/jest-worker/-/jest-worker-24.9.0.tgz", + "integrity": "sha512-51PE4haMSXcHohnSMdM42anbvZANYTqMrr52tVKPqqsPJMzoP6FYYDVqahX/HrAoKEKz3uUPzSvKs9A3qR4iVw==", + "dev": true, + "dependencies": { + "merge-stream": "^2.0.0", + "supports-color": "^6.1.0" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/js-tokens": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", + "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", + "dev": true + }, + "node_modules/js-yaml": { + "version": "3.14.1", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.14.1.tgz", + "integrity": "sha512-okMH7OXXJ7YrN9Ok3/SXrnu4iX9yOk+25nqX4imS2npuvTYDmo/QEZoqwZkYaIDk3jVvBOTOIEgEhaLOynBS9g==", + "dev": true, + "dependencies": { + "argparse": "^1.0.7", + "esprima": "^4.0.0" + }, + "bin": { + "js-yaml": "bin/js-yaml.js" + } + }, + "node_modules/json-parse-better-errors": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/json-parse-better-errors/-/json-parse-better-errors-1.0.2.tgz", + "integrity": "sha512-mrqyZKfX5EhL7hvqcV6WG1yYjnjeuYDzDhhcAAUrq8Po85NBQBJP+ZDUT75qZQ98IkUoBqdkExkukOU7Ts2wrw==", + "dev": true + }, + "node_modules/json-schema-traverse": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", + "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==", + "dev": true + }, + "node_modules/json-stable-stringify-without-jsonify": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/json-stable-stringify-without-jsonify/-/json-stable-stringify-without-jsonify-1.0.1.tgz", + "integrity": "sha512-Bdboy+l7tA3OGW6FjyFHWkP5LuByj1Tk33Ljyq0axyzdk9//JSi2u3fP1QSmd1KNwq6VOKYGlAu87CisVir6Pw==", + "dev": true + }, + "node_modules/jsx-ast-utils": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/jsx-ast-utils/-/jsx-ast-utils-2.4.1.tgz", + "integrity": "sha512-z1xSldJ6imESSzOjd3NNkieVJKRlKYSOtMG8SFyCj2FIrvSaSuli/WjpBkEzCBoR9bYYYFgqJw61Xhu7Lcgk+w==", + "dev": true, + "dependencies": { + "array-includes": "^3.1.1", + "object.assign": "^4.1.0" + }, + "engines": { + "node": ">=4.0" + } + }, + "node_modules/levn": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/levn/-/levn-0.3.0.tgz", + "integrity": "sha512-0OO4y2iOHix2W6ujICbKIaEQXvFQHue65vUG3pb5EUomzPI90z9hsA1VsO/dbIIpC53J8gxM9Q4Oho0jrCM/yA==", + "dev": true, + "dependencies": { + "prelude-ls": "~1.1.2", + "type-check": "~0.3.2" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/lib0": { + "version": "0.2.98", + "resolved": "https://registry.npmjs.org/lib0/-/lib0-0.2.98.tgz", + "integrity": "sha512-XteTiNO0qEXqqweWx+b21p/fBnNHUA1NwAtJNJek1oPrewEZs2uiT4gWivHKr9GqCjDPAhchz0UQO8NwU3bBNA==", + "dependencies": { + "isomorphic.js": "^0.2.4" + }, + "bin": { + "0ecdsa-generate-keypair": "bin/0ecdsa-generate-keypair.js", + "0gentesthtml": "bin/gentesthtml.js", + "0serve": "bin/0serve.js" + }, + "engines": { + "node": ">=16" + }, + "funding": { + "type": "GitHub Sponsors ❤", + "url": "https://github.com/sponsors/dmonad" + } + }, + "node_modules/load-json-file": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/load-json-file/-/load-json-file-5.3.0.tgz", + "integrity": "sha512-cJGP40Jc/VXUsp8/OrnyKyTZ1y6v/dphm3bioS+RrKXjK2BB6wHUd6JptZEFDGgGahMT+InnZO5i1Ei9mpC8Bw==", + "dev": true, + "dependencies": { + "graceful-fs": "^4.1.15", + "parse-json": "^4.0.0", + "pify": "^4.0.1", + "strip-bom": "^3.0.0", + "type-fest": "^0.3.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/load-json-file/node_modules/pify": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/pify/-/pify-4.0.1.tgz", + "integrity": "sha512-uB80kBFb/tfd68bVleG9T5GGsGPjJrLAUpR5PZIrhBnIaRTQRjqdJSsIKkOP6OAIFbj7GOrcudc5pNjZ+geV2g==", + "dev": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/load-json-file/node_modules/type-fest": { + "version": "0.3.1", + "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.3.1.tgz", + "integrity": "sha512-cUGJnCdr4STbePCgqNFbpVNCepa+kAVohJs1sLhxzdH+gnEoOd8VhbYa7pD3zZYGiURWM2xzEII3fQcRizDkYQ==", + "dev": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/locate-path": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-2.0.0.tgz", + "integrity": "sha512-NCI2kiDkyR7VeEKm27Kda/iQHyKJe1Bu0FlTbYp3CqJu+9IFe9bLyAjMxf5ZDDbEg+iMPzB5zYyUTSm8wVTKmA==", + "dev": true, + "dependencies": { + "p-locate": "^2.0.0", + "path-exists": "^3.0.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/lodash": { + "version": "4.17.21", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz", + "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==", + "dev": true + }, + "node_modules/loose-envify": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz", + "integrity": "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==", + "dev": true, + "dependencies": { + "js-tokens": "^3.0.0 || ^4.0.0" + }, + "bin": { + "loose-envify": "cli.js" + } + }, + "node_modules/magic-string": { + "version": "0.25.9", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.25.9.tgz", + "integrity": "sha512-RmF0AsMzgt25qzqqLc1+MbHmhdx0ojF2Fvs4XnOqz2ZOBXzzkEwc/dJQZCYHAn7v1jbVOjAZfK8msRn4BxO4VQ==", + "dev": true, + "dependencies": { + "sourcemap-codec": "^1.4.8" + } + }, + "node_modules/merge-stream": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/merge-stream/-/merge-stream-2.0.0.tgz", + "integrity": "sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==", + "dev": true + }, + "node_modules/mime": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/mime/-/mime-1.6.0.tgz", + "integrity": "sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg==", + "dev": true, + "bin": { + "mime": "cli.js" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/mimic-fn": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-2.1.0.tgz", + "integrity": "sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg==", + "dev": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/minimatch": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", + "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", + "dev": true, + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, + "node_modules/minimist": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz", + "integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==", + "dev": true, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/mkdirp": { + "version": "0.5.6", + "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.6.tgz", + "integrity": "sha512-FP+p8RB8OWpF3YZBCrP5gtADmtXApB5AMLn+vdyA+PyxCjrCs00mjyUozssO33cwDeT3wNGdLxJ5M//YqtHAJw==", + "dev": true, + "dependencies": { + "minimist": "^1.2.6" + }, + "bin": { + "mkdirp": "bin/cmd.js" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==" + }, + "node_modules/mute-stream": { + "version": "0.0.8", + "resolved": "https://registry.npmjs.org/mute-stream/-/mute-stream-0.0.8.tgz", + "integrity": "sha512-nnbWWOkoWyUsTjKrhgD0dcz22mdkSnpYqbEjIm2nhwhuxlSkpywJmBo8h0ZqJdkp73mb90SssHkN4rsRaBAfAA==", + "dev": true + }, + "node_modules/natural-compare": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz", + "integrity": "sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==", + "dev": true + }, + "node_modules/nice-try": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/nice-try/-/nice-try-1.0.5.tgz", + "integrity": "sha512-1nh45deeb5olNY7eX82BkPO7SSxR5SSYJiPTrTdFUVYwAl8CKMA5N9PjTYkHiRjisVcxcQ1HXdLhx2qxxJzLNQ==", + "dev": true + }, + "node_modules/normalize-package-data": { + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/normalize-package-data/-/normalize-package-data-2.5.0.tgz", + "integrity": "sha512-/5CMN3T0R4XTj4DcGaexo+roZSdSFW/0AOOTROrjxzCG1wrWXEsGbRKevjlIL+ZDE4sZlJr5ED4YW0yqmkK+eA==", + "dev": true, + "dependencies": { + "hosted-git-info": "^2.1.4", + "resolve": "^1.10.0", + "semver": "2 || 3 || 4 || 5", + "validate-npm-package-license": "^3.0.1" + } + }, + "node_modules/object-assign": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", + "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/object-inspect": { + "version": "1.13.2", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.2.tgz", + "integrity": "sha512-IRZSRuzJiynemAXPYtPe5BoI/RESNYR7TYm50MC5Mqbd3Jmw5y790sErYw3V6SryFJD64b74qQQs9wn5Bg/k3g==", + "dev": true, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/object-keys": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/object-keys/-/object-keys-1.1.1.tgz", + "integrity": "sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA==", + "dev": true, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/object.assign": { + "version": "4.1.5", + "resolved": "https://registry.npmjs.org/object.assign/-/object.assign-4.1.5.tgz", + "integrity": "sha512-byy+U7gp+FVwmyzKPYhW2h5l3crpmGsxl7X2s8y43IgxvG4g3QZ6CffDtsNQy1WsmZpQbO+ybo0AlW7TY6DcBQ==", + "dev": true, + "dependencies": { + "call-bind": "^1.0.5", + "define-properties": "^1.2.1", + "has-symbols": "^1.0.3", + "object-keys": "^1.1.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/object.entries": { + "version": "1.1.8", + "resolved": "https://registry.npmjs.org/object.entries/-/object.entries-1.1.8.tgz", + "integrity": "sha512-cmopxi8VwRIAw/fkijJohSfpef5PdN0pMQJN6VC/ZKvn0LIknWD8KtgY6KlQdEc4tIjcQ3HxSMmnvtzIscdaYQ==", + "dev": true, + "dependencies": { + "call-bind": "^1.0.7", + "define-properties": "^1.2.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/object.fromentries": { + "version": "2.0.8", + "resolved": "https://registry.npmjs.org/object.fromentries/-/object.fromentries-2.0.8.tgz", + "integrity": "sha512-k6E21FzySsSK5a21KRADBd/NGneRegFO5pLHfdQLpRDETUNJueLXs3WCzyQ3tFRDYgbq3KHGXfTbi2bs8WQ6rQ==", + "dev": true, + "dependencies": { + "call-bind": "^1.0.7", + "define-properties": "^1.2.1", + "es-abstract": "^1.23.2", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/object.values": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/object.values/-/object.values-1.2.0.tgz", + "integrity": "sha512-yBYjY9QX2hnRmZHAjG/f13MzmBzxzYgQhFrke06TTyKY5zSTEqkOeukBzIdVA3j3ulu8Qa3MbVFShV7T2RmGtQ==", + "dev": true, + "dependencies": { + "call-bind": "^1.0.7", + "define-properties": "^1.2.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", + "dev": true, + "dependencies": { + "wrappy": "1" + } + }, + "node_modules/onetime": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/onetime/-/onetime-5.1.2.tgz", + "integrity": "sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg==", + "dev": true, + "dependencies": { + "mimic-fn": "^2.1.0" + }, + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/opener": { + "version": "1.5.2", + "resolved": "https://registry.npmjs.org/opener/-/opener-1.5.2.tgz", + "integrity": "sha512-ur5UIdyw5Y7yEj9wLzhqXiy6GZ3Mwx0yGI+5sMn2r0N0v3cKJvUmFH5yPP+WXh9e0xfyzyJX95D8l088DNFj7A==", + "dev": true, + "bin": { + "opener": "bin/opener-bin.js" + } + }, + "node_modules/optionator": { + "version": "0.8.3", + "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.8.3.tgz", + "integrity": "sha512-+IW9pACdk3XWmmTXG8m3upGUJst5XRGzxMRjXzAuJ1XnIFNvfhjjIuYkDvysnPQ7qzqVzLt78BCruntqRhWQbA==", + "dev": true, + "dependencies": { + "deep-is": "~0.1.3", + "fast-levenshtein": "~2.0.6", + "levn": "~0.3.0", + "prelude-ls": "~1.1.2", + "type-check": "~0.3.2", + "word-wrap": "~1.2.3" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/os-tmpdir": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/os-tmpdir/-/os-tmpdir-1.0.2.tgz", + "integrity": "sha512-D2FR03Vir7FIu45XBY20mTb+/ZSWB00sjU9jdQXt83gDrI4Ztz5Fs7/yy74g2N5SVQY4xY1qDr4rNddwYRVX0g==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/p-limit": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-1.3.0.tgz", + "integrity": "sha512-vvcXsLAJ9Dr5rQOPk7toZQZJApBl2K4J6dANSsEuh6QI41JYcsS/qhTGa9ErIUUgK3WNQoJYvylxvjqmiqEA9Q==", + "dev": true, + "dependencies": { + "p-try": "^1.0.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/p-locate": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-2.0.0.tgz", + "integrity": "sha512-nQja7m7gSKuewoVRen45CtVfODR3crN3goVQ0DDZ9N3yHxgpkuBhZqsaiotSQRrADUrne346peY7kT3TSACykg==", + "dev": true, + "dependencies": { + "p-limit": "^1.1.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/p-try": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/p-try/-/p-try-1.0.0.tgz", + "integrity": "sha512-U1etNYuMJoIz3ZXSrrySFjsXQTWOx2/jdi86L+2pRvph/qMKL6sbcCYdH23fqsbm8TH2Gn0OybpT4eSFlCVHww==", + "dev": true, + "engines": { + "node": ">=4" + } + }, + "node_modules/parent-module": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/parent-module/-/parent-module-1.0.1.tgz", + "integrity": "sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g==", + "dev": true, + "dependencies": { + "callsites": "^3.0.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/parse-json": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-4.0.0.tgz", + "integrity": "sha512-aOIos8bujGN93/8Ox/jPLh7RwVnPEysynVFE+fQZyg6jKELEHwzgKdLRFHUgXJL6kylijVSBC4BvN9OmsB48Rw==", + "dev": true, + "dependencies": { + "error-ex": "^1.3.1", + "json-parse-better-errors": "^1.0.1" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/path-exists": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-3.0.0.tgz", + "integrity": "sha512-bpC7GYwiDYQ4wYLe+FA8lhRjhQCMcQGuSgGGqDkg/QerRWw9CmGRT0iSOVRSZJ29NMLZgIzqaljJ63oaL4NIJQ==", + "dev": true, + "engines": { + "node": ">=4" + } + }, + "node_modules/path-is-absolute": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", + "integrity": "sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/path-key": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-2.0.1.tgz", + "integrity": "sha512-fEHGKCSmUSDPv4uoj8AlD+joPlq3peND+HRYyxFz4KPw4z926S/b8rIuFs2FYJg3BwsxJf6A9/3eIdLaYC+9Dw==", + "dev": true, + "engines": { + "node": ">=4" + } + }, + "node_modules/path-parse": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz", + "integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==", + "dev": true + }, + "node_modules/path-type": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/path-type/-/path-type-2.0.0.tgz", + "integrity": "sha512-dUnb5dXUf+kzhC/W/F4e5/SkluXIFf5VUHolW1Eg1irn1hGWjPGdsRcvYJ1nD6lhk8Ir7VM0bHJKsYTx8Jx9OQ==", + "dev": true, + "dependencies": { + "pify": "^2.0.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/path-type/node_modules/pify": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/pify/-/pify-2.3.0.tgz", + "integrity": "sha512-udgsAY+fTnvv7kI7aaxbqwWNb0AHiB0qBO89PZKPkoTmGOgdbrHDKD+0B2X4uTfJ/FT1R09r9gTsjUjNJotuog==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "dev": true + }, + "node_modules/picomatch": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz", + "integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==", + "dev": true, + "engines": { + "node": ">=8.6" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/pify": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/pify/-/pify-3.0.0.tgz", + "integrity": "sha512-C3FsVNH1udSEX48gGX1xfvwTWfsYWj5U+8/uK15BGzIGrKoUpghX8hWZwa/OFnakBiiVNmBvemTJR5mcy7iPcg==", + "dev": true, + "engines": { + "node": ">=4" + } + }, + "node_modules/pkg-conf": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/pkg-conf/-/pkg-conf-3.1.0.tgz", + "integrity": "sha512-m0OTbR/5VPNPqO1ph6Fqbj7Hv6QU7gR/tQW40ZqrL1rjgCU85W6C1bJn0BItuJqnR98PWzw7Z8hHeChD1WrgdQ==", + "dev": true, + "dependencies": { + "find-up": "^3.0.0", + "load-json-file": "^5.2.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/pkg-conf/node_modules/find-up": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-3.0.0.tgz", + "integrity": "sha512-1yD6RmLI1XBfxugvORwlck6f75tYL+iR0jqwsOrOxMZyGYqUuDhJ0l4AXdO1iX/FTs9cBAMEk1gWSEx1kSbylg==", + "dev": true, + "dependencies": { + "locate-path": "^3.0.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/pkg-conf/node_modules/locate-path": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-3.0.0.tgz", + "integrity": "sha512-7AO748wWnIhNqAuaty2ZWHkQHRSNfPVIsPIfwEOWO22AmaoVrWavlOcMR5nzTLNYvp36X220/maaRsrec1G65A==", + "dev": true, + "dependencies": { + "p-locate": "^3.0.0", + "path-exists": "^3.0.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/pkg-conf/node_modules/p-limit": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz", + "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==", + "dev": true, + "dependencies": { + "p-try": "^2.0.0" + }, + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/pkg-conf/node_modules/p-locate": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-3.0.0.tgz", + "integrity": "sha512-x+12w/To+4GFfgJhBEpiDcLozRJGegY+Ei7/z0tSLkMmxGZNybVMSfWj9aJn8Z5Fc7dBUNJOOVgPv2H7IwulSQ==", + "dev": true, + "dependencies": { + "p-limit": "^2.0.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/pkg-conf/node_modules/p-try": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/p-try/-/p-try-2.2.0.tgz", + "integrity": "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==", + "dev": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/pkg-config": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/pkg-config/-/pkg-config-1.1.1.tgz", + "integrity": "sha512-ft/WI9YK6FuTuw4Ql+QUaNXtm/ASQNqDUUsZEgFZKyFpW6amyP8Gx01xrRs8KdiNbbqXfYxkOXplpq1euWbOjw==", + "dev": true, + "dependencies": { + "debug-log": "^1.0.0", + "find-root": "^1.0.0", + "xtend": "^4.0.1" + }, + "engines": { + "node": ">=0.10" + } + }, + "node_modules/portfinder": { + "version": "1.0.32", + "resolved": "https://registry.npmjs.org/portfinder/-/portfinder-1.0.32.tgz", + "integrity": "sha512-on2ZJVVDXRADWE6jnQaX0ioEylzgBpQk8r55NE4wjXW1ZxO+BgDlY6DXwj20i0V8eB4SenDQ00WEaxfiIQPcxg==", + "dev": true, + "dependencies": { + "async": "^2.6.4", + "debug": "^3.2.7", + "mkdirp": "^0.5.6" + }, + "engines": { + "node": ">= 0.12.0" + } + }, + "node_modules/possible-typed-array-names": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/possible-typed-array-names/-/possible-typed-array-names-1.0.0.tgz", + "integrity": "sha512-d7Uw+eZoloe0EHDIYoe+bQ5WXnGMOpmiZFTuMWCwpjzzkL2nTjcKiAk4hh8TjnGye2TwWOk3UXucZ+3rbmBa8Q==", + "dev": true, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/prelude-ls": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.1.2.tgz", + "integrity": "sha512-ESF23V4SKG6lVSGZgYNpbsiaAkdab6ZgOxe52p7+Kid3W3u3bxR4Vfd/o21dmN7jSt0IwgZ4v5MUd26FEtXE9w==", + "dev": true, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/progress": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/progress/-/progress-2.0.3.tgz", + "integrity": "sha512-7PiHtLll5LdnKIMw100I+8xJXR5gW2QwWYkT6iJva0bXitZKa/XMrSbdmg3r2Xnaidz9Qumd0VPaMrZlF9V9sA==", + "dev": true, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/prop-types": { + "version": "15.8.1", + "resolved": "https://registry.npmjs.org/prop-types/-/prop-types-15.8.1.tgz", + "integrity": "sha512-oj87CgZICdulUohogVAR7AjlC0327U4el4L6eAvOqCeudMDVU0NThNaV+b9Df4dXgSP1gXMTnPdhfe/2qDH5cg==", + "dev": true, + "dependencies": { + "loose-envify": "^1.4.0", + "object-assign": "^4.1.1", + "react-is": "^16.13.1" + } + }, + "node_modules/punycode": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", + "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==", + "dev": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/qs": { + "version": "6.13.0", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.13.0.tgz", + "integrity": "sha512-+38qI9SOr8tfZ4QmJNplMUxqjbe7LKvvZgWdExBOmd+egZTtjLB67Gu0HRX3u/XOq7UU2Nx6nsjvS16Z9uwfpg==", + "dev": true, + "dependencies": { + "side-channel": "^1.0.6" + }, + "engines": { + "node": ">=0.6" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/queue-microtask": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/queue-microtask/-/queue-microtask-1.2.3.tgz", + "integrity": "sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] + }, + "node_modules/randombytes": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/randombytes/-/randombytes-2.1.0.tgz", + "integrity": "sha512-vYl3iOX+4CKUWuxGi9Ukhie6fsqXqS9FE2Zaic4tNFD2N2QQaXOMFbuKK4QmDHC0JO6B1Zp41J0LpT0oR68amQ==", + "dependencies": { + "safe-buffer": "^5.1.0" + } + }, + "node_modules/react-is": { + "version": "16.13.1", + "resolved": "https://registry.npmjs.org/react-is/-/react-is-16.13.1.tgz", + "integrity": "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==", + "dev": true + }, + "node_modules/read-pkg": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/read-pkg/-/read-pkg-4.0.1.tgz", + "integrity": "sha512-+UBirHHDm5J+3WDmLBZYSklRYg82nMlz+enn+GMZ22nSR2f4bzxmhso6rzQW/3mT2PVzpzDTiYIZahk8UmZ44w==", + "dev": true, + "dependencies": { + "normalize-package-data": "^2.3.2", + "parse-json": "^4.0.0", + "pify": "^3.0.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/read-pkg-up": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/read-pkg-up/-/read-pkg-up-2.0.0.tgz", + "integrity": "sha512-1orxQfbWGUiTn9XsPlChs6rLie/AV9jwZTGmu2NZw/CUDJQchXJFYE0Fq5j7+n558T1JhDWLdhyd1Zj+wLY//w==", + "dev": true, + "dependencies": { + "find-up": "^2.0.0", + "read-pkg": "^2.0.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/read-pkg-up/node_modules/load-json-file": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/load-json-file/-/load-json-file-2.0.0.tgz", + "integrity": "sha512-3p6ZOGNbiX4CdvEd1VcE6yi78UrGNpjHO33noGwHCnT/o2fyllJDepsm8+mFFv/DvtwFHht5HIHSyOy5a+ChVQ==", + "dev": true, + "dependencies": { + "graceful-fs": "^4.1.2", + "parse-json": "^2.2.0", + "pify": "^2.0.0", + "strip-bom": "^3.0.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/read-pkg-up/node_modules/parse-json": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-2.2.0.tgz", + "integrity": "sha512-QR/GGaKCkhwk1ePQNYDRKYZ3mwU9ypsKhB0XyFnLQdomyEqk3e8wpW3V5Jp88zbxK4n5ST1nqo+g9juTpownhQ==", + "dev": true, + "dependencies": { + "error-ex": "^1.2.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/read-pkg-up/node_modules/pify": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/pify/-/pify-2.3.0.tgz", + "integrity": "sha512-udgsAY+fTnvv7kI7aaxbqwWNb0AHiB0qBO89PZKPkoTmGOgdbrHDKD+0B2X4uTfJ/FT1R09r9gTsjUjNJotuog==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/read-pkg-up/node_modules/read-pkg": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/read-pkg/-/read-pkg-2.0.0.tgz", + "integrity": "sha512-eFIBOPW7FGjzBuk3hdXEuNSiTZS/xEMlH49HxMyzb0hyPfu4EhVjT2DH32K1hSSmVq4sebAWnZuuY5auISUTGA==", + "dev": true, + "dependencies": { + "load-json-file": "^2.0.0", + "normalize-package-data": "^2.3.2", + "path-type": "^2.0.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/readable-stream": { + "version": "3.6.2", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", + "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", + "dependencies": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/regenerator-runtime": { + "version": "0.14.1", + "resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.14.1.tgz", + "integrity": "sha512-dYnhHh0nJoMfnkZs6GmmhFknAGRrLznOu5nc9ML+EJxGvrx6H7teuevqVqCuPcPK//3eDrrjQhehXVx9cnkGdw==", + "dev": true + }, + "node_modules/regexp.prototype.flags": { + "version": "1.5.3", + "resolved": "https://registry.npmjs.org/regexp.prototype.flags/-/regexp.prototype.flags-1.5.3.tgz", + "integrity": "sha512-vqlC04+RQoFalODCbCumG2xIOvapzVMHwsyIGM/SIE8fRhFFsXeH8/QQ+s0T0kDAhKc4k30s73/0ydkHQz6HlQ==", + "dev": true, + "dependencies": { + "call-bind": "^1.0.7", + "define-properties": "^1.2.1", + "es-errors": "^1.3.0", + "set-function-name": "^2.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/regexpp": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/regexpp/-/regexpp-2.0.1.tgz", + "integrity": "sha512-lv0M6+TkDVniA3aD1Eg0DVpfU/booSu7Eev3TDO/mZKHBfVjgCGTV4t4buppESEYDtkArYFOxTJWv6S5C+iaNw==", + "dev": true, + "engines": { + "node": ">=6.5.0" + } + }, + "node_modules/require-directory": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", + "integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/require-main-filename": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/require-main-filename/-/require-main-filename-2.0.0.tgz", + "integrity": "sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg==", + "dev": true + }, + "node_modules/requires-port": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/requires-port/-/requires-port-1.0.0.tgz", + "integrity": "sha512-KigOCHcocU3XODJxsu8i/j8T9tzT4adHiecwORRQ0ZZFcp7ahwXuRU1m+yuO90C5ZUyGeGfocHDI14M3L3yDAQ==", + "dev": true + }, + "node_modules/resolve": { + "version": "1.22.8", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.8.tgz", + "integrity": "sha512-oKWePCxqpd6FlLvGV1VU0x7bkPmmCNolxzjMf4NczoDnQcIWrAF+cPtZn5i6n+RfD2d9i0tzpKnG6Yk168yIyw==", + "dev": true, + "dependencies": { + "is-core-module": "^2.13.0", + "path-parse": "^1.0.7", + "supports-preserve-symlinks-flag": "^1.0.0" + }, + "bin": { + "resolve": "bin/resolve" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/resolve-from": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-4.0.0.tgz", + "integrity": "sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==", + "dev": true, + "engines": { + "node": ">=4" + } + }, + "node_modules/restore-cursor": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/restore-cursor/-/restore-cursor-3.1.0.tgz", + "integrity": "sha512-l+sSefzHpj5qimhFSE5a8nufZYAM3sBSVMAPtYkmC+4EH2anSGaEMXSD0izRQbu9nfyQ9y5JrVmp7E8oZrUjvA==", + "dev": true, + "dependencies": { + "onetime": "^5.1.0", + "signal-exit": "^3.0.2" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/rimraf": { + "version": "2.6.3", + "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-2.6.3.tgz", + "integrity": "sha512-mwqeW5XsA2qAejG46gYdENaxXjx9onRNCfn7L0duuP4hCuTIi/QO7PDK07KJfp1d+izWPrzEJDcSqBa0OZQriA==", + "deprecated": "Rimraf versions prior to v4 are no longer supported", + "dev": true, + "dependencies": { + "glob": "^7.1.3" + }, + "bin": { + "rimraf": "bin.js" + } + }, + "node_modules/rollup": { + "version": "1.32.1", + "resolved": "https://registry.npmjs.org/rollup/-/rollup-1.32.1.tgz", + "integrity": "sha512-/2HA0Ec70TvQnXdzynFffkjA6XN+1e2pEv/uKS5Ulca40g2L7KuOE3riasHoNVHOsFD5KKZgDsMk1CP3Tw9s+A==", + "dev": true, + "dependencies": { + "@types/estree": "*", + "@types/node": "*", + "acorn": "^7.1.0" + }, + "bin": { + "rollup": "dist/bin/rollup" + } + }, + "node_modules/rollup-cli": { + "version": "1.0.9", + "resolved": "https://registry.npmjs.org/rollup-cli/-/rollup-cli-1.0.9.tgz", + "integrity": "sha512-7Uu9tgSELjUdeA4/aAQEva01kuMyl1O2JS44prE5O3WMBtWTujHlUWoyuaI7S7fROtdO5ml+yvZi32ZLsIhvIg==", + "deprecated": "outdated", + "dev": true, + "bin": { + "roller": "bin/roller" + }, + "engines": { + "node": ">=5.0.0" + } + }, + "node_modules/rollup-plugin-terser": { + "version": "5.3.1", + "resolved": "https://registry.npmjs.org/rollup-plugin-terser/-/rollup-plugin-terser-5.3.1.tgz", + "integrity": "sha512-1pkwkervMJQGFYvM9nscrUoncPwiKR/K+bHdjv6PFgRo3cgPHoRT83y2Aa3GvINj4539S15t/tpFPb775TDs6w==", + "deprecated": "This package has been deprecated and is no longer maintained. Please use @rollup/plugin-terser", + "dev": true, + "dependencies": { + "@babel/code-frame": "^7.5.5", + "jest-worker": "^24.9.0", + "rollup-pluginutils": "^2.8.2", + "serialize-javascript": "^4.0.0", + "terser": "^4.6.2" + }, + "peerDependencies": { + "rollup": ">=0.66.0 <3" + } + }, + "node_modules/rollup-pluginutils": { + "version": "2.8.2", + "resolved": "https://registry.npmjs.org/rollup-pluginutils/-/rollup-pluginutils-2.8.2.tgz", + "integrity": "sha512-EEp9NhnUkwY8aif6bxgovPHMoMoNr2FulJziTndpt5H9RdwC47GSGuII9XxpSdzVGM0GWrNPHV6ie1LTNJPaLQ==", + "dev": true, + "dependencies": { + "estree-walker": "^0.6.1" + } + }, + "node_modules/rollup-pluginutils/node_modules/estree-walker": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-0.6.1.tgz", + "integrity": "sha512-SqmZANLWS0mnatqbSfRP5g8OXZC12Fgg1IwNtLsyHDzJizORW4khDfjPqJZsemPWBB2uqykUah5YpQ6epsqC/w==", + "dev": true + }, + "node_modules/run-async": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/run-async/-/run-async-2.4.1.tgz", + "integrity": "sha512-tvVnVv01b8c1RrA6Ep7JkStj85Guv/YrMcwqYQnwjsAS2cTmmPGBBjAjpCW7RrSodNSoE2/qg9O4bceNvUuDgQ==", + "dev": true, + "engines": { + "node": ">=0.12.0" + } + }, + "node_modules/run-parallel": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/run-parallel/-/run-parallel-1.2.0.tgz", + "integrity": "sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "dependencies": { + "queue-microtask": "^1.2.2" + } + }, + "node_modules/rxjs": { + "version": "6.6.7", + "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-6.6.7.tgz", + "integrity": "sha512-hTdwr+7yYNIT5n4AMYp85KA6yw2Va0FLa3Rguvbpa4W3I5xynaBZo41cM3XM+4Q6fRMj3sBYIR1VAmZMXYJvRQ==", + "dev": true, + "dependencies": { + "tslib": "^1.9.0" + }, + "engines": { + "npm": ">=2.0.0" + } + }, + "node_modules/safe-array-concat": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/safe-array-concat/-/safe-array-concat-1.1.2.tgz", + "integrity": "sha512-vj6RsCsWBCf19jIeHEfkRMw8DPiBb+DMXklQ/1SGDHOMlHdPUkZXFQ2YdplS23zESTijAcurb1aSgJA3AgMu1Q==", + "dev": true, + "dependencies": { + "call-bind": "^1.0.7", + "get-intrinsic": "^1.2.4", + "has-symbols": "^1.0.3", + "isarray": "^2.0.5" + }, + "engines": { + "node": ">=0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] + }, + "node_modules/safe-regex-test": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/safe-regex-test/-/safe-regex-test-1.0.3.tgz", + "integrity": "sha512-CdASjNJPvRa7roO6Ra/gLYBTzYzzPyyBXxIMdGW3USQLyjWEls2RgW5UBTXaQVp+OrpeCK3bLem8smtmheoRuw==", + "dev": true, + "dependencies": { + "call-bind": "^1.0.6", + "es-errors": "^1.3.0", + "is-regex": "^1.1.4" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "dev": true + }, + "node_modules/secure-compare": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/secure-compare/-/secure-compare-3.0.1.tgz", + "integrity": "sha512-AckIIV90rPDcBcglUwXPF3kg0P0qmPsPXAj6BBEENQE1p5yA1xfmDJzfi1Tappj37Pv2mVbKpL3Z1T+Nn7k1Qw==", + "dev": true + }, + "node_modules/semver": { + "version": "5.7.2", + "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.2.tgz", + "integrity": "sha512-cBznnQ9KjJqU67B52RMC65CMarK2600WFnbkcaiwWq3xy/5haFJlshgnpjovMVJ+Hff49d8GEn0b87C5pDQ10g==", + "dev": true, + "bin": { + "semver": "bin/semver" + } + }, + "node_modules/serialize-javascript": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/serialize-javascript/-/serialize-javascript-4.0.0.tgz", + "integrity": "sha512-GaNA54380uFefWghODBWEGisLZFj00nS5ACs6yHa9nLqlLpVLO8ChDGeKRjZnV4Nh4n0Qi7nhYZD/9fCPzEqkw==", + "dev": true, + "dependencies": { + "randombytes": "^2.1.0" + } + }, + "node_modules/set-blocking": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/set-blocking/-/set-blocking-2.0.0.tgz", + "integrity": "sha512-KiKBS8AnWGEyLzofFfmvKwpdPzqiy16LvQfK3yv/fVH7Bj13/wl3JSR1J+rfgRE9q7xUJK4qvgS8raSOeLUehw==", + "dev": true + }, + "node_modules/set-function-length": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/set-function-length/-/set-function-length-1.2.2.tgz", + "integrity": "sha512-pgRc4hJ4/sNjWCSS9AmnS40x3bNMDTknHgL5UaMBTMyJnU90EgWh1Rz+MC9eFu4BuN/UwZjKQuY/1v3rM7HMfg==", + "dev": true, + "dependencies": { + "define-data-property": "^1.1.4", + "es-errors": "^1.3.0", + "function-bind": "^1.1.2", + "get-intrinsic": "^1.2.4", + "gopd": "^1.0.1", + "has-property-descriptors": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/set-function-name": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/set-function-name/-/set-function-name-2.0.2.tgz", + "integrity": "sha512-7PGFlmtwsEADb0WYyvCMa1t+yke6daIG4Wirafur5kcf+MhUnPms1UeR0CKQdTZD81yESwMHbtn+TR+dMviakQ==", + "dev": true, + "dependencies": { + "define-data-property": "^1.1.4", + "es-errors": "^1.3.0", + "functions-have-names": "^1.2.3", + "has-property-descriptors": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/shebang-command": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-1.2.0.tgz", + "integrity": "sha512-EV3L1+UQWGor21OmnvojK36mhg+TyIKDh3iFBKBohr5xeXIhNBcx8oWdgkTEEQ+BEFFYdLRuqMfd5L84N1V5Vg==", + "dev": true, + "dependencies": { + "shebang-regex": "^1.0.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/shebang-regex": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-1.0.0.tgz", + "integrity": "sha512-wpoSFAxys6b2a2wHZ1XpDSgD7N9iVjg29Ph9uV/uaP9Ex/KXlkTZTeddxDPSYQpgvzKLGJke2UU0AzoGCjNIvQ==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/side-channel": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.0.6.tgz", + "integrity": "sha512-fDW/EZ6Q9RiO8eFG8Hj+7u/oW+XrPTIChwCOM2+th2A6OblDtYYIpve9m+KvI9Z4C9qSEXlaGR6bTEYHReuglA==", + "dev": true, + "dependencies": { + "call-bind": "^1.0.7", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.4", + "object-inspect": "^1.13.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/signal-exit": { + "version": "3.0.7", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz", + "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==", + "dev": true + }, + "node_modules/simple-peer": { + "version": "9.11.1", + "resolved": "https://registry.npmjs.org/simple-peer/-/simple-peer-9.11.1.tgz", + "integrity": "sha512-D1SaWpOW8afq1CZGWB8xTfrT3FekjQmPValrqncJMX7QFl8YwhrPTZvMCANLtgBwwdS+7zURyqxDDEmY558tTw==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "dependencies": { + "buffer": "^6.0.3", + "debug": "^4.3.2", + "err-code": "^3.0.1", + "get-browser-rtc": "^1.1.0", + "queue-microtask": "^1.2.3", + "randombytes": "^2.1.0", + "readable-stream": "^3.6.0" + } + }, + "node_modules/simple-peer/node_modules/debug": { + "version": "4.3.7", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.7.tgz", + "integrity": "sha512-Er2nc/H7RrMXZBFCEim6TCmMk02Z8vLC2Rbi1KEBggpo0fS6l0S1nnapwmIi3yW/+GOJap1Krg4w0Hg80oCqgQ==", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/slice-ansi": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/slice-ansi/-/slice-ansi-2.1.0.tgz", + "integrity": "sha512-Qu+VC3EwYLldKa1fCxuuvULvSJOKEgk9pi8dZeCVK7TqBfUNTH4sFkk4joj8afVSfAYgJoSOetjx9QWOJ5mYoQ==", + "dev": true, + "dependencies": { + "ansi-styles": "^3.2.0", + "astral-regex": "^1.0.0", + "is-fullwidth-code-point": "^2.0.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/slice-ansi/node_modules/is-fullwidth-code-point": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-2.0.0.tgz", + "integrity": "sha512-VHskAKYM8RfSFXwee5t5cbN5PZeq1Wrh6qd5bkyiXIf6UQcN6w/A0eXM9r6t8d+GYOh+o6ZhiEnb88LN/Y8m2w==", + "dev": true, + "engines": { + "node": ">=4" + } + }, + "node_modules/source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/source-map-support": { + "version": "0.5.21", + "resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.21.tgz", + "integrity": "sha512-uBHU3L3czsIyYXKX88fdrGovxdSCoTGDRZ6SYXtSRxLZUzHg5P/66Ht6uoUlHu9EZod+inXhKo3qQgwXUT/y1w==", + "dev": true, + "dependencies": { + "buffer-from": "^1.0.0", + "source-map": "^0.6.0" + } + }, + "node_modules/sourcemap-codec": { + "version": "1.4.8", + "resolved": "https://registry.npmjs.org/sourcemap-codec/-/sourcemap-codec-1.4.8.tgz", + "integrity": "sha512-9NykojV5Uih4lgo5So5dtw+f0JgJX30KCNI8gwhz2J9A15wD0Ml6tjHKwf6fTSa6fAdVBdZeNOs9eJ71qCk8vA==", + "deprecated": "Please use @jridgewell/sourcemap-codec instead", + "dev": true + }, + "node_modules/spawn-command": { + "version": "0.0.2", + "resolved": "https://registry.npmjs.org/spawn-command/-/spawn-command-0.0.2.tgz", + "integrity": "sha512-zC8zGoGkmc8J9ndvml8Xksr1Amk9qBujgbF0JAIWO7kXr43w0h/0GJNM/Vustixu+YE8N/MTrQ7N31FvHUACxQ==", + "dev": true + }, + "node_modules/spdx-correct": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/spdx-correct/-/spdx-correct-3.2.0.tgz", + "integrity": "sha512-kN9dJbvnySHULIluDHy32WHRUu3Og7B9sbY7tsFLctQkIqnMh3hErYgdMjTYuqmcXX+lK5T1lnUt3G7zNswmZA==", + "dev": true, + "dependencies": { + "spdx-expression-parse": "^3.0.0", + "spdx-license-ids": "^3.0.0" + } + }, + "node_modules/spdx-exceptions": { + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/spdx-exceptions/-/spdx-exceptions-2.5.0.tgz", + "integrity": "sha512-PiU42r+xO4UbUS1buo3LPJkjlO7430Xn5SVAhdpzzsPHsjbYVflnnFdATgabnLude+Cqu25p6N+g2lw/PFsa4w==", + "dev": true + }, + "node_modules/spdx-expression-parse": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/spdx-expression-parse/-/spdx-expression-parse-3.0.1.tgz", + "integrity": "sha512-cbqHunsQWnJNE6KhVSMsMeH5H/L9EpymbzqTQ3uLwNCLZ1Q481oWaofqH7nO6V07xlXwY6PhQdQ2IedWx/ZK4Q==", + "dev": true, + "dependencies": { + "spdx-exceptions": "^2.1.0", + "spdx-license-ids": "^3.0.0" + } + }, + "node_modules/spdx-license-ids": { + "version": "3.0.20", + "resolved": "https://registry.npmjs.org/spdx-license-ids/-/spdx-license-ids-3.0.20.tgz", + "integrity": "sha512-jg25NiDV/1fLtSgEgyvVyDunvaNHbuwF9lfNV17gSmPFAlYzdfNBlLtLzXTevwkPj7DhGbmN9VnmJIgLnhvaBw==", + "dev": true + }, + "node_modules/sprintf-js": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz", + "integrity": "sha512-D9cPgkvLlV3t3IzL0D0YLvGA9Ahk4PcvVwUbN0dSGr1aP0Nrt4AEnTUbuGvquEC0mA64Gqt1fzirlRs5ibXx8g==", + "dev": true + }, + "node_modules/standard": { + "version": "14.3.4", + "resolved": "https://registry.npmjs.org/standard/-/standard-14.3.4.tgz", + "integrity": "sha512-+lpOkFssMkljJ6eaILmqxHQ2n4csuEABmcubLTb9almFi1ElDzXb1819fjf/5ygSyePCq4kU2wMdb2fBfb9P9Q==", + "dev": true, + "dependencies": { + "eslint": "~6.8.0", + "eslint-config-standard": "14.1.1", + "eslint-config-standard-jsx": "8.1.0", + "eslint-plugin-import": "~2.18.0", + "eslint-plugin-node": "~10.0.0", + "eslint-plugin-promise": "~4.2.1", + "eslint-plugin-react": "~7.14.2", + "eslint-plugin-standard": "~4.0.0", + "standard-engine": "^12.0.0" + }, + "bin": { + "standard": "bin/cmd.js" + }, + "engines": { + "node": ">=8.10.0" + } + }, + "node_modules/standard-engine": { + "version": "12.1.0", + "resolved": "https://registry.npmjs.org/standard-engine/-/standard-engine-12.1.0.tgz", + "integrity": "sha512-DVJnWM1CGkag4ucFLGdiYWa5/kJURPONmMmk17p8FT5NE4UnPZB1vxWnXnRo2sPSL78pWJG8xEM+1Tu19z0deg==", + "dev": true, + "dependencies": { + "deglob": "^4.0.1", + "get-stdin": "^7.0.0", + "minimist": "^1.2.5", + "pkg-conf": "^3.1.0" + }, + "engines": { + "node": ">=8.10" + } + }, + "node_modules/string_decoder": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", + "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==", + "dependencies": { + "safe-buffer": "~5.2.0" + } + }, + "node_modules/string-width": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "dev": true, + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/string-width/node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/string-width/node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "dev": true, + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/string.prototype.trim": { + "version": "1.2.9", + "resolved": "https://registry.npmjs.org/string.prototype.trim/-/string.prototype.trim-1.2.9.tgz", + "integrity": "sha512-klHuCNxiMZ8MlsOihJhJEBJAiMVqU3Z2nEXWfWnIqjN0gEFS9J9+IxKozWWtQGcgoa1WUZzLjKPTr4ZHNFTFxw==", + "dev": true, + "dependencies": { + "call-bind": "^1.0.7", + "define-properties": "^1.2.1", + "es-abstract": "^1.23.0", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/string.prototype.trimend": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/string.prototype.trimend/-/string.prototype.trimend-1.0.8.tgz", + "integrity": "sha512-p73uL5VCHCO2BZZ6krwwQE3kCzM7NKmis8S//xEC6fQonchbum4eP6kR4DLEjQFO3Wnj3Fuo8NM0kOSjVdHjZQ==", + "dev": true, + "dependencies": { + "call-bind": "^1.0.7", + "define-properties": "^1.2.1", + "es-object-atoms": "^1.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/string.prototype.trimstart": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/string.prototype.trimstart/-/string.prototype.trimstart-1.0.8.tgz", + "integrity": "sha512-UXSH262CSZY1tfu3G3Secr6uGLCFVPMhIqHjlgCUtCCcgihYc/xKs9djMTMUOb2j1mVSeU8EU6NWc/iQKU6Gfg==", + "dev": true, + "dependencies": { + "call-bind": "^1.0.7", + "define-properties": "^1.2.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/strip-ansi": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-5.2.0.tgz", + "integrity": "sha512-DuRs1gKbBqsMKIZlrffwlug8MHkcnpjs5VPmL1PAh+mA30U0DTotfDZ0d2UUsXpPmPmMMJ6W773MaA3J+lbiWA==", + "dev": true, + "dependencies": { + "ansi-regex": "^4.1.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/strip-bom": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-3.0.0.tgz", + "integrity": "sha512-vavAMRXOgBVNF6nyEEmL3DBK19iRpDcoIwW+swQ+CbGiu7lju6t+JklA1MHweoWtadgt4ISVUsXLyDq34ddcwA==", + "dev": true, + "engines": { + "node": ">=4" + } + }, + "node_modules/strip-json-comments": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.1.1.tgz", + "integrity": "sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==", + "dev": true, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/supports-color": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-6.1.0.tgz", + "integrity": "sha512-qe1jfm1Mg7Nq/NSh6XE24gPXROEVsWHxC1LIx//XNlD9iw7YZQGjZNjYN7xGaEG6iKdA8EtNFW6R0gjnVXp+wQ==", + "dev": true, + "dependencies": { + "has-flag": "^3.0.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/supports-preserve-symlinks-flag": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz", + "integrity": "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==", + "dev": true, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/table": { + "version": "5.4.6", + "resolved": "https://registry.npmjs.org/table/-/table-5.4.6.tgz", + "integrity": "sha512-wmEc8m4fjnob4gt5riFRtTu/6+4rSe12TpAELNSqHMfF3IqnA+CH37USM6/YR3qRZv7e56kAEAtd6nKZaxe0Ug==", + "dev": true, + "dependencies": { + "ajv": "^6.10.2", + "lodash": "^4.17.14", + "slice-ansi": "^2.1.0", + "string-width": "^3.0.0" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/table/node_modules/emoji-regex": { + "version": "7.0.3", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-7.0.3.tgz", + "integrity": "sha512-CwBLREIQ7LvYFB0WyRvwhq5N5qPhc6PMjD6bYggFlI5YyDgl+0vxq5VHbMOFqLg7hfWzmu8T5Z1QofhmTIhItA==", + "dev": true + }, + "node_modules/table/node_modules/is-fullwidth-code-point": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-2.0.0.tgz", + "integrity": "sha512-VHskAKYM8RfSFXwee5t5cbN5PZeq1Wrh6qd5bkyiXIf6UQcN6w/A0eXM9r6t8d+GYOh+o6ZhiEnb88LN/Y8m2w==", + "dev": true, + "engines": { + "node": ">=4" + } + }, + "node_modules/table/node_modules/string-width": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-3.1.0.tgz", + "integrity": "sha512-vafcv6KjVZKSgz06oM/H6GDBrAtz8vdhQakGjFIvNrHA6y3HCF1CInLy+QLq8dTJPQ1b+KDUqDFctkdRW44e1w==", + "dev": true, + "dependencies": { + "emoji-regex": "^7.0.1", + "is-fullwidth-code-point": "^2.0.0", + "strip-ansi": "^5.1.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/terser": { + "version": "4.8.1", + "resolved": "https://registry.npmjs.org/terser/-/terser-4.8.1.tgz", + "integrity": "sha512-4GnLC0x667eJG0ewJTa6z/yXrbLGv80D9Ru6HIpCQmO+Q4PfEtBFi0ObSckqwL6VyQv/7ENJieXHo2ANmdQwgw==", + "dev": true, + "dependencies": { + "commander": "^2.20.0", + "source-map": "~0.6.1", + "source-map-support": "~0.5.12" + }, + "bin": { + "terser": "bin/terser" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/text-table": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/text-table/-/text-table-0.2.0.tgz", + "integrity": "sha512-N+8UisAXDGk8PFXP4HAzVR9nbfmVJ3zYLAWiTIoqC5v5isinhr+r5uaO8+7r3BMfuNIufIsA7RdpVgacC2cSpw==", + "dev": true + }, + "node_modules/through": { + "version": "2.3.8", + "resolved": "https://registry.npmjs.org/through/-/through-2.3.8.tgz", + "integrity": "sha512-w89qg7PI8wAdvX60bMDP+bFoD5Dvhm9oLheFp5O4a2QF0cSBGsBX4qZmadPMvVqlLJBBci+WqGGOAPvcDeNSVg==", + "dev": true + }, + "node_modules/tmp": { + "version": "0.0.33", + "resolved": "https://registry.npmjs.org/tmp/-/tmp-0.0.33.tgz", + "integrity": "sha512-jRCJlojKnZ3addtTOjdIqoRuPEKBvNXcGYqzO6zWZX8KfKEpnGY5jfggJQ3EjKuu8D4bJRr0y+cYJFmYbImXGw==", + "dev": true, + "dependencies": { + "os-tmpdir": "~1.0.2" + }, + "engines": { + "node": ">=0.6.0" + } + }, + "node_modules/tree-kill": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/tree-kill/-/tree-kill-1.2.2.tgz", + "integrity": "sha512-L0Orpi8qGpRG//Nd+H90vFB+3iHnue1zSSGmNOOCh1GLJ7rUKVwV2HvijphGQS2UmhUZewS9VgvxYIdgr+fG1A==", + "dev": true, + "bin": { + "tree-kill": "cli.js" + } + }, + "node_modules/tslib": { + "version": "1.14.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-1.14.1.tgz", + "integrity": "sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg==", + "dev": true + }, + "node_modules/type-check": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.3.2.tgz", + "integrity": "sha512-ZCmOJdvOWDBYJlzAoFkC+Q0+bUyEOS1ltgp1MGU03fqHG+dbi9tBFU2Rd9QKiDZFAYrhPh2JUf7rZRIuHRKtOg==", + "dev": true, + "dependencies": { + "prelude-ls": "~1.1.2" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/type-fest": { + "version": "0.8.1", + "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.8.1.tgz", + "integrity": "sha512-4dbzIzqvjtgiM5rw1k5rEHtBANKmdudhGyBEajN01fEyhaAIhsoKNy6y7+IN93IfpFtwY9iqi7kD+xwKhQsNJA==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/typed-array-buffer": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/typed-array-buffer/-/typed-array-buffer-1.0.2.tgz", + "integrity": "sha512-gEymJYKZtKXzzBzM4jqa9w6Q1Jjm7x2d+sh19AdsD4wqnMPDYyvwpsIc2Q/835kHuo3BEQ7CjelGhfTsoBb2MQ==", + "dev": true, + "dependencies": { + "call-bind": "^1.0.7", + "es-errors": "^1.3.0", + "is-typed-array": "^1.1.13" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/typed-array-byte-length": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/typed-array-byte-length/-/typed-array-byte-length-1.0.1.tgz", + "integrity": "sha512-3iMJ9q0ao7WE9tWcaYKIptkNBuOIcZCCT0d4MRvuuH88fEoEH62IuQe0OtraD3ebQEoTRk8XCBoknUNc1Y67pw==", + "dev": true, + "dependencies": { + "call-bind": "^1.0.7", + "for-each": "^0.3.3", + "gopd": "^1.0.1", + "has-proto": "^1.0.3", + "is-typed-array": "^1.1.13" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/typed-array-byte-offset": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/typed-array-byte-offset/-/typed-array-byte-offset-1.0.2.tgz", + "integrity": "sha512-Ous0vodHa56FviZucS2E63zkgtgrACj7omjwd/8lTEMEPFFyjfixMZ1ZXenpgCFBBt4EC1J2XsyVS2gkG0eTFA==", + "dev": true, + "dependencies": { + "available-typed-arrays": "^1.0.7", + "call-bind": "^1.0.7", + "for-each": "^0.3.3", + "gopd": "^1.0.1", + "has-proto": "^1.0.3", + "is-typed-array": "^1.1.13" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/typed-array-length": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/typed-array-length/-/typed-array-length-1.0.6.tgz", + "integrity": "sha512-/OxDN6OtAk5KBpGb28T+HZc2M+ADtvRxXrKKbUwtsLgdoxgX13hyy7ek6bFRl5+aBs2yZzB0c4CnQfAtVypW/g==", + "dev": true, + "dependencies": { + "call-bind": "^1.0.7", + "for-each": "^0.3.3", + "gopd": "^1.0.1", + "has-proto": "^1.0.3", + "is-typed-array": "^1.1.13", + "possible-typed-array-names": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/typescript": { + "version": "4.9.5", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-4.9.5.tgz", + "integrity": "sha512-1FXk9E2Hm+QzZQ7z+McJiHL4NW1F2EzMu9Nq9i3zAaGqibafqYwCVU6WyWAuyQRRzOlxou8xZSyXLEN8oKj24g==", + "dev": true, + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=4.2.0" + } + }, + "node_modules/unbox-primitive": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/unbox-primitive/-/unbox-primitive-1.0.2.tgz", + "integrity": "sha512-61pPlCD9h51VoreyJ0BReideM3MDKMKnh6+V9L08331ipq6Q8OFXZYiqP6n/tbHx4s5I9uRhcye6BrbkizkBDw==", + "dev": true, + "dependencies": { + "call-bind": "^1.0.2", + "has-bigints": "^1.0.2", + "has-symbols": "^1.0.3", + "which-boxed-primitive": "^1.0.2" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/undici-types": { + "version": "6.19.8", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.19.8.tgz", + "integrity": "sha512-ve2KP6f/JnbPBFyobGHuerC9g1FYGn/F8n1LWTwNxCEzd6IfqTwUQcNXgEtmmQ6DlRrC1hrSrBnCZPokRrDHjw==", + "dev": true + }, + "node_modules/union": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/union/-/union-0.5.0.tgz", + "integrity": "sha512-N6uOhuW6zO95P3Mel2I2zMsbsanvvtgn6jVqJv4vbVcz/JN0OkL9suomjQGmWtxJQXOCqUJvquc1sMeNz/IwlA==", + "dev": true, + "dependencies": { + "qs": "^6.4.0" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/uniq": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/uniq/-/uniq-1.0.1.tgz", + "integrity": "sha512-Gw+zz50YNKPDKXs+9d+aKAjVwpjNwqzvNpLigIruT4HA9lMZNdMqs9x07kKHB/L9WRzqp4+DlTU5s4wG2esdoA==", + "dev": true + }, + "node_modules/uri-js": { + "version": "4.4.1", + "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz", + "integrity": "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==", + "dev": true, + "dependencies": { + "punycode": "^2.1.0" + } + }, + "node_modules/url-join": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/url-join/-/url-join-2.0.5.tgz", + "integrity": "sha512-c2H1fIgpUdwFRIru9HFno5DT73Ok8hg5oOb5AT3ayIgvCRfxgs2jyt5Slw8kEB7j3QUr6yJmMPDT/odjk7jXow==", + "dev": true + }, + "node_modules/util-deprecate": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", + "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==" + }, + "node_modules/v8-compile-cache": { + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/v8-compile-cache/-/v8-compile-cache-2.4.0.tgz", + "integrity": "sha512-ocyWc3bAHBB/guyqJQVI5o4BZkPhznPYUG2ea80Gond/BgNWpap8TOmLSeeQG7bnh2KMISxskdADG59j7zruhw==", + "dev": true + }, + "node_modules/validate-npm-package-license": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/validate-npm-package-license/-/validate-npm-package-license-3.0.4.tgz", + "integrity": "sha512-DpKm2Ui/xN7/HQKCtpZxoRWBhZ9Z0kqtygG8XCgNQ8ZlDnxuQmWhj566j8fN4Cu3/JmbhsDo7fcAJq4s9h27Ew==", + "dev": true, + "dependencies": { + "spdx-correct": "^3.0.0", + "spdx-expression-parse": "^3.0.0" + } + }, + "node_modules/which": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/which/-/which-1.3.1.tgz", + "integrity": "sha512-HxJdYWq1MTIQbJ3nw0cqssHoTNU267KlrDuGZ1WYlxDStUtKUhOaJmh112/TZmHxxUfuJqPXSOm7tDyas0OSIQ==", + "dev": true, + "dependencies": { + "isexe": "^2.0.0" + }, + "bin": { + "which": "bin/which" + } + }, + "node_modules/which-boxed-primitive": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/which-boxed-primitive/-/which-boxed-primitive-1.0.2.tgz", + "integrity": "sha512-bwZdv0AKLpplFY2KZRX6TvyuN7ojjr7lwkg6ml0roIy9YeuSr7JS372qlNW18UQYzgYK9ziGcerWqZOmEn9VNg==", + "dev": true, + "dependencies": { + "is-bigint": "^1.0.1", + "is-boolean-object": "^1.1.0", + "is-number-object": "^1.0.4", + "is-string": "^1.0.5", + "is-symbol": "^1.0.3" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/which-module": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/which-module/-/which-module-2.0.1.tgz", + "integrity": "sha512-iBdZ57RDvnOR9AGBhML2vFZf7h8vmBjhoaZqODJBFWHVtKkDmKuHai3cx5PgVMrX5YDNp27AofYbAwctSS+vhQ==", + "dev": true + }, + "node_modules/which-typed-array": { + "version": "1.1.15", + "resolved": "https://registry.npmjs.org/which-typed-array/-/which-typed-array-1.1.15.tgz", + "integrity": "sha512-oV0jmFtUky6CXfkqehVvBP/LSWJ2sy4vWMioiENyJLePrBO/yKyV9OyJySfAKosh+RYkIl5zJCNZ8/4JncrpdA==", + "dev": true, + "dependencies": { + "available-typed-arrays": "^1.0.7", + "call-bind": "^1.0.7", + "for-each": "^0.3.3", + "gopd": "^1.0.1", + "has-tostringtag": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/word-wrap": { + "version": "1.2.5", + "resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.5.tgz", + "integrity": "sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/wrap-ansi": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-5.1.0.tgz", + "integrity": "sha512-QC1/iN/2/RPVJ5jYK8BGttj5z83LmSKmvbvrXPNCLZSEb32KKVDJDl/MOt2N01qU2H/FkzEa9PKto1BqDjtd7Q==", + "dev": true, + "dependencies": { + "ansi-styles": "^3.2.0", + "string-width": "^3.0.0", + "strip-ansi": "^5.0.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/wrap-ansi/node_modules/emoji-regex": { + "version": "7.0.3", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-7.0.3.tgz", + "integrity": "sha512-CwBLREIQ7LvYFB0WyRvwhq5N5qPhc6PMjD6bYggFlI5YyDgl+0vxq5VHbMOFqLg7hfWzmu8T5Z1QofhmTIhItA==", + "dev": true + }, + "node_modules/wrap-ansi/node_modules/is-fullwidth-code-point": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-2.0.0.tgz", + "integrity": "sha512-VHskAKYM8RfSFXwee5t5cbN5PZeq1Wrh6qd5bkyiXIf6UQcN6w/A0eXM9r6t8d+GYOh+o6ZhiEnb88LN/Y8m2w==", + "dev": true, + "engines": { + "node": ">=4" + } + }, + "node_modules/wrap-ansi/node_modules/string-width": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-3.1.0.tgz", + "integrity": "sha512-vafcv6KjVZKSgz06oM/H6GDBrAtz8vdhQakGjFIvNrHA6y3HCF1CInLy+QLq8dTJPQ1b+KDUqDFctkdRW44e1w==", + "dev": true, + "dependencies": { + "emoji-regex": "^7.0.1", + "is-fullwidth-code-point": "^2.0.0", + "strip-ansi": "^5.1.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", + "dev": true + }, + "node_modules/write": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/write/-/write-1.0.3.tgz", + "integrity": "sha512-/lg70HAjtkUgWPVZhZcm+T4hkL8Zbtp1nFNOn3lRrxnlv50SRBv7cR7RqR+GMsd3hUXy9hWBo4CHTbFTcOYwig==", + "dev": true, + "dependencies": { + "mkdirp": "^0.5.1" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/ws": { + "version": "8.18.0", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.18.0.tgz", + "integrity": "sha512-8VbfWfHLbbwu3+N6OKsOMpBdT4kXPDDB9cJk2bJ6mh9ucxdlnNvH1e+roYkKmN9Nxw2yjz7VzeO9oOz2zJ04Pw==", + "optional": true, + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, + "node_modules/xtend": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz", + "integrity": "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==", + "dev": true, + "engines": { + "node": ">=0.4" + } + }, + "node_modules/y-protocols": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/y-protocols/-/y-protocols-1.0.6.tgz", + "integrity": "sha512-vHRF2L6iT3rwj1jub/K5tYcTT/mEYDUppgNPXwp8fmLpui9f7Yeq3OEtTLVF012j39QnV+KEQpNqoN7CWU7Y9Q==", + "dependencies": { + "lib0": "^0.2.85" + }, + "engines": { + "node": ">=16.0.0", + "npm": ">=8.0.0" + }, + "funding": { + "type": "GitHub Sponsors ❤", + "url": "https://github.com/sponsors/dmonad" + }, + "peerDependencies": { + "yjs": "^13.0.0" + } + }, + "node_modules/y-webrtc": { + "version": "10.3.0", + "resolved": "https://registry.npmjs.org/y-webrtc/-/y-webrtc-10.3.0.tgz", + "integrity": "sha512-KalJr7dCgUgyVFxoG3CQYbpS0O2qybegD0vI4bYnYHI0MOwoVbucED3RZ5f2o1a5HZb1qEssUKS0H/Upc6p1lA==", + "dependencies": { + "lib0": "^0.2.42", + "simple-peer": "^9.11.0", + "y-protocols": "^1.0.6" + }, + "bin": { + "y-webrtc-signaling": "bin/server.js" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "type": "GitHub Sponsors ❤", + "url": "https://github.com/sponsors/dmonad" + }, + "optionalDependencies": { + "ws": "^8.14.2" + }, + "peerDependencies": { + "yjs": "^13.6.8" + } + }, + "node_modules/y18n": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/y18n/-/y18n-4.0.3.tgz", + "integrity": "sha512-JKhqTOwSrqNA1NY5lSztJ1GrBiUodLMmIZuLiDaMRJ+itFd+ABVE8XBjOvIWL+rSqNDC74LCSFmlb/U4UZ4hJQ==", + "dev": true + }, + "node_modules/yargs": { + "version": "13.3.2", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-13.3.2.tgz", + "integrity": "sha512-AX3Zw5iPruN5ie6xGRIDgqkT+ZhnRlZMLMHAs8tg7nRruy2Nb+i5o9bwghAogtM08q1dpr2LVoS8KSTMYpWXUw==", + "dev": true, + "dependencies": { + "cliui": "^5.0.0", + "find-up": "^3.0.0", + "get-caller-file": "^2.0.1", + "require-directory": "^2.1.1", + "require-main-filename": "^2.0.0", + "set-blocking": "^2.0.0", + "string-width": "^3.0.0", + "which-module": "^2.0.0", + "y18n": "^4.0.0", + "yargs-parser": "^13.1.2" + } + }, + "node_modules/yargs-parser": { + "version": "13.1.2", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-13.1.2.tgz", + "integrity": "sha512-3lbsNRf/j+A4QuSZfDRA7HRSfWrzO0YjqTJd5kjAq37Zep1CEgaYmrH9Q3GwPiB9cHyd1Y1UwggGhJGoxipbzg==", + "dev": true, + "dependencies": { + "camelcase": "^5.0.0", + "decamelize": "^1.2.0" + } + }, + "node_modules/yargs/node_modules/emoji-regex": { + "version": "7.0.3", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-7.0.3.tgz", + "integrity": "sha512-CwBLREIQ7LvYFB0WyRvwhq5N5qPhc6PMjD6bYggFlI5YyDgl+0vxq5VHbMOFqLg7hfWzmu8T5Z1QofhmTIhItA==", + "dev": true + }, + "node_modules/yargs/node_modules/find-up": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-3.0.0.tgz", + "integrity": "sha512-1yD6RmLI1XBfxugvORwlck6f75tYL+iR0jqwsOrOxMZyGYqUuDhJ0l4AXdO1iX/FTs9cBAMEk1gWSEx1kSbylg==", + "dev": true, + "dependencies": { + "locate-path": "^3.0.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/yargs/node_modules/is-fullwidth-code-point": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-2.0.0.tgz", + "integrity": "sha512-VHskAKYM8RfSFXwee5t5cbN5PZeq1Wrh6qd5bkyiXIf6UQcN6w/A0eXM9r6t8d+GYOh+o6ZhiEnb88LN/Y8m2w==", + "dev": true, + "engines": { + "node": ">=4" + } + }, + "node_modules/yargs/node_modules/locate-path": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-3.0.0.tgz", + "integrity": "sha512-7AO748wWnIhNqAuaty2ZWHkQHRSNfPVIsPIfwEOWO22AmaoVrWavlOcMR5nzTLNYvp36X220/maaRsrec1G65A==", + "dev": true, + "dependencies": { + "p-locate": "^3.0.0", + "path-exists": "^3.0.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/yargs/node_modules/p-limit": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz", + "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==", + "dev": true, + "dependencies": { + "p-try": "^2.0.0" + }, + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/yargs/node_modules/p-locate": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-3.0.0.tgz", + "integrity": "sha512-x+12w/To+4GFfgJhBEpiDcLozRJGegY+Ei7/z0tSLkMmxGZNybVMSfWj9aJn8Z5Fc7dBUNJOOVgPv2H7IwulSQ==", + "dev": true, + "dependencies": { + "p-limit": "^2.0.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/yargs/node_modules/p-try": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/p-try/-/p-try-2.2.0.tgz", + "integrity": "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==", + "dev": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/yargs/node_modules/string-width": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-3.1.0.tgz", + "integrity": "sha512-vafcv6KjVZKSgz06oM/H6GDBrAtz8vdhQakGjFIvNrHA6y3HCF1CInLy+QLq8dTJPQ1b+KDUqDFctkdRW44e1w==", + "dev": true, + "dependencies": { + "emoji-regex": "^7.0.1", + "is-fullwidth-code-point": "^2.0.0", + "strip-ansi": "^5.1.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/yjs": { + "version": "13.6.20", + "resolved": "https://registry.npmjs.org/yjs/-/yjs-13.6.20.tgz", + "integrity": "sha512-Z2YZI+SYqK7XdWlloI3lhMiKnCdFCVC4PchpdO+mCYwtiTwncjUbnRK9R1JmkNfdmHyDXuWN3ibJAt0wsqTbLQ==", + "dependencies": { + "lib0": "^0.2.98" + }, + "engines": { + "node": ">=16.0.0", + "npm": ">=8.0.0" + }, + "funding": { + "type": "GitHub Sponsors ❤", + "url": "https://github.com/sponsors/dmonad" + } + } + } +} diff --git a/backend/signaling/package.json b/backend/signaling/package.json new file mode 100644 index 0000000000..19737488a8 --- /dev/null +++ b/backend/signaling/package.json @@ -0,0 +1,88 @@ +{ + "name": "y-webrtc", + "version": "10.3.0", + "description": "WebRTC provider for Yjs", + "type": "module", + "main": "./dist/y-webrtc.cjs", + "types": "./dist/src/y-webrtc.d.ts", + "module": "./src/y-webrtc.js", + "unpkg": "./src/y-webrtc.mjs", + "sideEffects": false, + "funding": { + "type": "GitHub Sponsors ❤", + "url": "https://github.com/sponsors/dmonad" + }, + "exports": { + "module": "./src/y-webrtc.js", + "import": "./src/y-webrtc.js", + "require": "./dist/y-webrtc.cjs", + "types": "./dist/src/y-webrtc.d.ts" + }, + "scripts": { + "clean": "rm -rf dist", + "start": "node ./bin/server.js", + "debug": "concurrently 'http-server -o index.html' 'npm run watch'", + "demo": "concurrently 'http-server -o demo/index.html' 'npm run watch'", + "dist": "rollup -c", + "types": "tsc", + "watch": "rollup -wc", + "test": "npm run lint", + "lint": "standard && tsc", + "preversion": "npm run clean && npm run lint && npm run dist && npm run types" + }, + "bin": { + "y-webrtc-signaling": "./bin/server.js" + }, + "files": [ + "dist/*", + "bin/*", + "src/*" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/yjs/y-webrtc.git" + }, + "keywords": [ + "Yjs" + ], + "author": "Kevin Jahns ", + "license": "MIT", + "bugs": { + "url": "https://github.com/yjs/y-webrtc/issues" + }, + "homepage": "https://github.com/yjs/y-webrtc#readme", + "standard": { + "ignore": [ + "/dist", + "/node_modules" + ] + }, + "dependencies": { + "lib0": "^0.2.42", + "simple-peer": "^9.11.0", + "y-protocols": "^1.0.6", + "y-webrtc": "^10.3.0" + }, + "devDependencies": { + "@rollup/plugin-commonjs": "^11.1.0", + "@rollup/plugin-node-resolve": "^7.1.3", + "@types/simple-peer": "^9.11.3", + "concurrently": "^5.3.0", + "http-server": "^0.12.3", + "rollup": "^1.32.1", + "rollup-cli": "^1.0.9", + "rollup-plugin-terser": "^5.3.1", + "standard": "^14.3.4", + "typescript": "^4.4.4", + "yjs": "^13.6.8" + }, + "peerDependencies": { + "yjs": "^13.6.8" + }, + "optionalDependencies": { + "ws": "^8.14.2" + }, + "engines": { + "node": ">=12" + } + } \ No newline at end of file diff --git a/backend/user/.env.sample b/backend/user/.env.sample new file mode 100644 index 0000000000..625ef2022d --- /dev/null +++ b/backend/user/.env.sample @@ -0,0 +1,9 @@ +DB_CLOUD_URI= +DB_LOCAL_URI= +PORT= + +# Will use cloud MongoDB Atlas database +ENV= + +# Secret for creating JWT signature +JWT_SECRET= diff --git a/backend/user/Dockerfile b/backend/user/Dockerfile new file mode 100644 index 0000000000..4e936beec1 --- /dev/null +++ b/backend/user/Dockerfile @@ -0,0 +1,13 @@ +FROM node + +WORKDIR /app + +COPY package*.json ./ + +RUN npm install + +COPY . . + +EXPOSE 3004 + +CMD ["npm", "start"] \ No newline at end of file diff --git a/backend/user/GuideAssets/AddIPAddress.png b/backend/user/GuideAssets/AddIPAddress.png new file mode 100644 index 0000000000..9d79550ca4 Binary files /dev/null and b/backend/user/GuideAssets/AddIPAddress.png differ diff --git a/backend/user/GuideAssets/ConnectCluster.png b/backend/user/GuideAssets/ConnectCluster.png new file mode 100644 index 0000000000..1f045f0e04 Binary files /dev/null and b/backend/user/GuideAssets/ConnectCluster.png differ diff --git a/backend/user/GuideAssets/ConnectionString.png b/backend/user/GuideAssets/ConnectionString.png new file mode 100644 index 0000000000..073d3ed6a9 Binary files /dev/null and b/backend/user/GuideAssets/ConnectionString.png differ diff --git a/backend/user/GuideAssets/Creation.png b/backend/user/GuideAssets/Creation.png new file mode 100644 index 0000000000..055ed783af Binary files /dev/null and b/backend/user/GuideAssets/Creation.png differ diff --git a/backend/user/GuideAssets/DriverSelection.png b/backend/user/GuideAssets/DriverSelection.png new file mode 100644 index 0000000000..585087811c Binary files /dev/null and b/backend/user/GuideAssets/DriverSelection.png differ diff --git a/backend/user/GuideAssets/IPWhitelisting.png b/backend/user/GuideAssets/IPWhitelisting.png new file mode 100644 index 0000000000..5718234553 Binary files /dev/null and b/backend/user/GuideAssets/IPWhitelisting.png differ diff --git a/backend/user/GuideAssets/Network.png b/backend/user/GuideAssets/Network.png new file mode 100644 index 0000000000..57bad4e677 Binary files /dev/null and b/backend/user/GuideAssets/Network.png differ diff --git a/backend/user/GuideAssets/Security.png b/backend/user/GuideAssets/Security.png new file mode 100644 index 0000000000..f328764083 Binary files /dev/null and b/backend/user/GuideAssets/Security.png differ diff --git a/backend/user/GuideAssets/Selection.png b/backend/user/GuideAssets/Selection.png new file mode 100644 index 0000000000..5029373ea1 Binary files /dev/null and b/backend/user/GuideAssets/Selection.png differ diff --git a/backend/user/GuideAssets/Selection1.png b/backend/user/GuideAssets/Selection1.png new file mode 100644 index 0000000000..211c69a156 Binary files /dev/null and b/backend/user/GuideAssets/Selection1.png differ diff --git a/backend/user/GuideAssets/Selection2.png b/backend/user/GuideAssets/Selection2.png new file mode 100644 index 0000000000..17ff928855 Binary files /dev/null and b/backend/user/GuideAssets/Selection2.png differ diff --git a/backend/user/GuideAssets/Selection3.png b/backend/user/GuideAssets/Selection3.png new file mode 100644 index 0000000000..948ed1026d Binary files /dev/null and b/backend/user/GuideAssets/Selection3.png differ diff --git a/backend/user/GuideAssets/Selection4.png b/backend/user/GuideAssets/Selection4.png new file mode 100644 index 0000000000..abf60bbe21 Binary files /dev/null and b/backend/user/GuideAssets/Selection4.png differ diff --git a/backend/user/GuideAssets/SidePane.png b/backend/user/GuideAssets/SidePane.png new file mode 100644 index 0000000000..95f7e2866f Binary files /dev/null and b/backend/user/GuideAssets/SidePane.png differ diff --git a/backend/user/MongoDBSetup.md b/backend/user/MongoDBSetup.md new file mode 100644 index 0000000000..276161ee4e --- /dev/null +++ b/backend/user/MongoDBSetup.md @@ -0,0 +1,60 @@ +# Setting up MongoDB Instance for User Service + +1. Visit the MongoDB Atlas Site [https://www.mongodb.com/atlas](https://www.mongodb.com/atlas) and click on "Try Free" + +2. Sign Up/Sign In with your preferred method. + +3. You will be greeted with welcome screens. Feel free to skip them till you reach the Dashboard page. + +4. Create a Database Deployment by clicking on the green `+ Create` Button: + +![alt text](./GuideAssets/Creation.png) + +5. Make selections as followings: + +- Select Shared Cluster +- Select `aws` as Provider + +![alt text](./GuideAssets/Selection1.png) + +- Select `Singapore` for Region + +![alt text](./GuideAssets/Selection2.png) + +- Select `M0 Sandbox` Cluster (Free Forever - No Card Required) + +> Ensure to select M0 Sandbox, else you may be prompted to enter card details and may be charged! + +![alt text](./GuideAssets/Selection3.png) + +- Leave `Additional Settings` as it is + +- Provide a suitable name to the Cluster + +![alt text](./GuideAssets/Selection4.png) + +6. You will be prompted to set up Security for the database by providing `Username and Password`. Select that option and enter `Username` and `Password`. Please keep this safe as it will be used in User Service later on. + +![alt text](./GuideAssets/Security.png) + +7. Next, click on `Add my Current IP Address`. This will whiteliste your IP address and allow you to connect to the MongoDB Database. + +![alt text](./GuideAssets/Network.png) + +8. Click `Finish and Close` and the MongoDB Instance should be up and running. + +## Whitelisting All IP's + +1. Select `Network Access` from the left side pane on Dashboard. + +![alt text](./GuideAssets/SidePane.png) + +2. Click on the `Add IP Address` Button + +![alt text](./GuideAssets/AddIPAddress.png) + +3. Select the `ALLOW ACCESS FROM ANYWHERE` Button and Click `Confirm` + +![alt text](./GuideAssets/IPWhitelisting.png) + +Now, any IP Address can access this Database. diff --git a/backend/user/README.md b/backend/user/README.md new file mode 100644 index 0000000000..be27594dbc --- /dev/null +++ b/backend/user/README.md @@ -0,0 +1,272 @@ +# User Service Guide + +## Setting-up + +> :notebook: If you are familiar to MongoDB and wish to use a local instance, please feel free to do so. This guide utilizes MongoDB Cloud Services. + +1. Set up a MongoDB Shared Cluster by following the steps in this [Guide](./MongoDBSetup.md). + +2. After setting up, go to the Database Deployment Page. You would see a list of the Databases you have set up. Select `Connect` on the cluster you just created earlier on for User Service. + + ![alt text](./GuideAssets/ConnectCluster.png) + +3. Select the `Drivers` option, as we have to link to a Node.js App (User Service). + + ![alt text](./GuideAssets/DriverSelection.png) + +4. Select `Node.js` in the `Driver` pull-down menu, and copy the connection string. + + Notice, you may see `` in this connection string. We will be replacing this with the admin account password that we created earlier on when setting up the Shared Cluster. + + ![alt text](./GuideAssets/ConnectionString.png) + +5. In the `user-service` directory, create a copy of the `.env.sample` file and name it `.env`. + +6. Update the `DB_CLOUD_URI` of the `.env` file, and paste the string we copied earlier in step 4. Also remember to replace the `` placeholder with the actual password. + +## Running User Service + +1. Open Command Line/Terminal and navigate into the `user-service` directory. + +2. Run the command: `npm install`. This will install all the necessary dependencies. + +3. Run the command `npm start` to start the User Service in production mode, or use `npm run dev` for development mode, which includes features like automatic server restart when you make code changes. + +4. Using applications like Postman, you can interact with the User Service on port 3001. If you wish to change this, please update the `.env` file. + +## User Service API Guide + +### Create User + +- This endpoint allows adding a new user to the database (i.e., user registration). + +- HTTP Method: `POST` + +- Endpoint: http://localhost:3001/users + +- Body + - Required: `username` (string), `email` (string), `password` (string) + + ```json + { + "username": "SampleUserName", + "email": "sample@gmail.com", + "password": "SecurePassword" + } + ``` + +- Responses: + + | Response Code | Explanation | + |-----------------------------|-------------------------------------------------------| + | 201 (Created) | User created successfully, created user data returned | + | 400 (Bad Request) | Missing fields | + | 409 (Conflict) | Duplicate username or email encountered | + | 500 (Internal Server Error) | Database or server error | + +### Get User + +- This endpoint allows retrieval of a single user's data from the database using the user's ID. + + > :bulb: The user ID refers to the MongoDB Object ID, a unique identifier automatically generated by MongoDB for each document in a collection. + +- HTTP Method: `GET` + +- Endpoint: http://localhost:3001/users/{userId} + +- Parameters + - Required: `userId` path parameter + - Example: `http://localhost:3001/users/60c72b2f9b1d4c3a2e5f8b4c` + +- Headers + + - Required: `Authorization: Bearer ` + + - Explanation: This endpoint requires the client to include a JWT (JSON Web Token) in the HTTP request header for authentication and authorization. This token is generated during the authentication process (i.e., login) and contains information about the user's identity. The server verifies this token to ensure that the client is authorized to access the data. + + - Auth Rules: + + - Admin users: Can retrieve any user's data. The server verifies the user associated with the JWT token is an admin user and allows access to the requested user's data. + + - Non-admin users: Can only retrieve their own data. The server checks if the user ID in the request URL matches the ID of the user associated with the JWT token. If it matches, the server returns the user's own data. + +- Responses: + + | Response Code | Explanation | + |-----------------------------|----------------------------------------------------------| + | 200 (OK) | Success, user data returned | + | 401 (Unauthorized) | Access denied due to missing/invalid/expired JWT | + | 403 (Forbidden) | Access denied for non-admin users accessing others' data | + | 404 (Not Found) | User with the specified ID not found | + | 500 (Internal Server Error) | Database or server error | + +### Get All Users + +- This endpoint allows retrieval of all users' data from the database. +- HTTP Method: `GET` +- Endpoint: http://localhost:3001/users +- Headers + - Required: `Authorization: Bearer ` + - Auth Rules: + + - Admin users: Can retrieve all users' data. The server verifies the user associated with the JWT token is an admin user and allows access to all users' data. + + - Non-admin users: Not allowed access. + +- Responses: + + | Response Code | Explanation | + |-----------------------------|--------------------------------------------------| + | 200 (OK) | Success, all user data returned | + | 401 (Unauthorized) | Access denied due to missing/invalid/expired JWT | + | 403 (Forbidden) | Access denied for non-admin users | + | 500 (Internal Server Error) | Database or server error | + +### Update User + +- This endpoint allows updating a user and their related data in the database using the user's ID. + +- HTTP Method: `PATCH` + +- Endpoint: http://localhost:3001/users/{userId} + +- Parameters + - Required: `userId` path parameter + +- Body + - At least one of the following fields is required: `username` (string), `email` (string), `password` (string) + + ```json + { + "username": "SampleUserName", + "email": "sample@gmail.com", + "password": "SecurePassword" + } + ``` + +- Headers + - Required: `Authorization: Bearer ` + - Auth Rules: + + - Admin users: Can update any user's data. The server verifies the user associated with the JWT token is an admin user and allows the update of requested user's data. + + - Non-admin users: Can only update their own data. The server checks if the user ID in the request URL matches the ID of the user associated with the JWT token. If it matches, the server updates the user's own data. + +- Responses: + + | Response Code | Explanation | + |-----------------------------|---------------------------------------------------------| + | 200 (OK) | User updated successfully, updated user data returned | + | 400 (Bad Request) | Missing fields | + | 401 (Unauthorized) | Access denied due to missing/invalid/expired JWT | + | 403 (Forbidden) | Access denied for non-admin users updating others' data | + | 404 (Not Found) | User with the specified ID not found | + | 409 (Conflict) | Duplicate username or email encountered | + | 500 (Internal Server Error) | Database or server error | + +### Update User Privilege + +- This endpoint allows updating a user’s privilege, i.e., promoting or demoting them from admin status. + +- HTTP Method: `PATCH` + +- Endpoint: http://localhost:3001/users/{userId} + +- Parameters + - Required: `userId` path parameter + +- Body + - Required: `isAdmin` (boolean) + + ```json + { + "isAdmin": true + } + ``` + +- Headers + - Required: `Authorization: Bearer ` + - Auth Rules: + + - Admin users: Can update any user's privilege. The server verifies the user associated with the JWT token is an admin user and allows the privilege update. + - Non-admin users: Not allowed access. + +> :bulb: You may need to manually assign admin status to the first user by directly editing the database document before using this endpoint. + +- Responses: + + | Response Code | Explanation | + |-----------------------------|-----------------------------------------------------------------| + | 200 (OK) | User privilege updated successfully, updated user data returned | + | 400 (Bad Request) | Missing fields | + | 401 (Unauthorized) | Access denied due to missing/invalid/expired JWT | + | 403 (Forbidden) | Access denied for non-admin users | + | 404 (Not Found) | User with the specified ID not found | + | 500 (Internal Server Error) | Database or server error | + +### Delete User + +- This endpoint allows deletion of a user and their related data from the database using the user's ID. +- HTTP Method: `DELETE` +- Endpoint: http://localhost:3001/users/{userId} +- Parameters + + - Required: `userId` path parameter +- Headers + + - Required: `Authorization: Bearer ` + + - Auth Rules: + + - Admin users: Can delete any user's data. The server verifies the user associated with the JWT token is an admin user and allows the deletion of requested user's data. + + - Non-admin users: Can only delete their own data. The server checks if the user ID in the request URL matches the ID of the user associated with the JWT token. If it matches, the server deletes the user's own data. +- Responses: + + | Response Code | Explanation | + |-----------------------------|---------------------------------------------------------| + | 200 (OK) | User deleted successfully | + | 401 (Unauthorized) | Access denied due to missing/invalid/expired JWT | + | 403 (Forbidden) | Access denied for non-admin users deleting others' data | + | 404 (Not Found) | User with the specified ID not found | + | 500 (Internal Server Error) | Database or server error | + +### Login + +- This endpoint allows a user to authenticate with an email and password and returns a JWT access token. The token is valid for 1 day and can be used subsequently to access protected resources. For example usage, refer to the [Authorization header section in the Get User endpoint](#auth-header). +- HTTP Method: `POST` +- Endpoint: http://localhost:3001/auth/login +- Body + - Required: `email` (string), `password` (string) + + ```json + { + "email": "sample@gmail.com", + "password": "SecurePassword" + } + ``` + +- Responses: + + | Response Code | Explanation | + |-----------------------------|----------------------------------------------------| + | 200 (OK) | Login successful, JWT token and user data returned | + | 400 (Bad Request) | Missing fields | + | 401 (Unauthorized) | Incorrect email or password | + | 500 (Internal Server Error) | Database or server error | + +### Verify Token + +- This endpoint allows one to verify a JWT access token to authenticate and retrieve the user's data associated with the token. +- HTTP Method: `GET` +- Endpoint: http://localhost:3001/auth/verify-token +- Headers + - Required: `Authorization: Bearer ` + +- Responses: + + | Response Code | Explanation | + |-----------------------------|----------------------------------------------------| + | 200 (OK) | Token verified, authenticated user's data returned | + | 401 (Unauthorized) | Missing/invalid/expired JWT | + | 500 (Internal Server Error) | Database or server error | \ No newline at end of file diff --git a/backend/user/controller/auth-controller.js b/backend/user/controller/auth-controller.js new file mode 100644 index 0000000000..f7a7a04827 --- /dev/null +++ b/backend/user/controller/auth-controller.js @@ -0,0 +1,41 @@ +import bcrypt from 'bcryptjs'; +import jwt from "jsonwebtoken"; +import { findUserByEmail as _findUserByEmail } from "../model/repository.js"; +import { formatUserResponse } from "./user-controller.js"; + +export async function handleLogin(req, res) { + const { email, password } = req.body; + if (email && password) { + try { + const user = await _findUserByEmail(email); + if (!user) { + return res.status(401).json({ message: "Wrong email and/or password" }); + } + + const match = await bcrypt.compare(password, user.password); + if (!match) { + return res.status(401).json({ message: "Wrong email and/or password" }); + } + + const accessToken = jwt.sign({ + id: user.id, + }, process.env.JWT_SECRET, { + expiresIn: "1d", + }); + return res.status(200).json({ message: "User logged in", data: { accessToken, ...formatUserResponse(user) } }); + } catch (err) { + return res.status(500).json({ message: err.message }); + } + } else { + return res.status(400).json({ message: "Missing email and/or password" }); + } +} + +export async function handleVerifyToken(req, res) { + try { + const verifiedUser = req.user; + return res.status(200).json({ message: "Token verified", data: verifiedUser }); + } catch (err) { + return res.status(500).json({ message: err.message }); + } +} diff --git a/backend/user/controller/user-controller.js b/backend/user/controller/user-controller.js new file mode 100644 index 0000000000..93a982e733 --- /dev/null +++ b/backend/user/controller/user-controller.js @@ -0,0 +1,492 @@ +import bcrypt from "bcryptjs"; +import { isValidObjectId } from "mongoose"; +import { + createUser as _createUser, + deleteUserById as _deleteUserById, + findAllUsers as _findAllUsers, + findUserByEmail as _findUserByEmail, + findUserById as _findUserById, + findUserByUsername as _findUserByUsername, + findUserByUsernameOrEmail as _findUserByUsernameOrEmail, + findUserByUsernameOrId as _findUserByUsernameOrId, + updateUserById as _updateUserById, + updateUserPrivilegeById as _updateUserPrivilegeById, + findUserByVerificationCode as _findUserByVerificationCode, + verifyUserByVerificationCode as _verifyUserByVerificationCode, + findUserByPasswordResetCode as _findUserByPasswordResetCode, + addPasswordResetCodeToUser as _addPasswordResetCodeToUser, +} from "../model/repository.js"; +import multer from "multer"; +import { Storage } from "@google-cloud/storage"; +import { + sendVerificationEmail, + sendPasswordResetEmail, +} from "../third-party/email.js"; + +const privateKey = process.env.credentials_private_key.replace(/\\n/g, "\n"); + +const storage = new Storage({ + projectId: process.env["credentials_project_id"], + credentials: { + type: process.env["credentials_type"], + project_id: process.env["credentials_project_id"], + private_key_id: process.env["credentials_private_key_id"], + private_key: privateKey, + client_email: process.env["credentials_client_email"], + client_id: process.env["credentials_client_id"], + auth_uri: process.env["credentials_auth_uri"], + token_uri: process.env["credentials_token_uri"], + auth_provider_x509_cert_url: process.env["credentials_auth_provider"], + client_x509_cert_url: process.env["credentials_cert_url"], + }, +}); + +const profileBucketName = "peerprep-g15-profile-pictures"; +const profileBucket = storage.bucket(profileBucketName); +const upload = multer({ + storage: multer.memoryStorage(), + limits: { fileSize: 5 * 1024 * 1024 }, // 5MB +}).single("profilePicture"); + +export async function createUser(req, res) { + try { + const { username, email, password } = req.body; + if (username && email && password) { + const existingUser = await _findUserByUsernameOrEmail(username, email); + if (existingUser) { + return res + .status(409) + .json({ message: "username or email already exists" }); + } + + const salt = bcrypt.genSaltSync(10); + const hashedPassword = bcrypt.hashSync(password, salt); + + // For email verification, you can generate a random verification code and save it in the database + const verificationCode = + Math.random().toString(36).substring(2, 15) + + Math.random().toString(36).substring(2, 15); + + const createdUser = await _createUser( + username, + email, + hashedPassword, + verificationCode + ); + + // Send email to user + await sendVerificationEmail(email, username, verificationCode); + + return res.status(201).json({ + message: `Created new user ${username} successfully`, + data: formatUserResponse(createdUser), + }); + } else { + return res + .status(400) + .json({ message: "username and/or email and/or password are missing" }); + } + } catch (err) { + console.error(err); + return res + .status(500) + .json({ message: "Unknown error when creating new user!" }); + } +} + +export async function getUser(req, res) { + try { + const userId = req.params.id; + + const user = await _findUserByUsernameOrId(userId); + if (!user) { + return res.status(404).json({ message: `User ${userId} not found` }); + } else { + return res + .status(200) + .json({ message: `Found user`, data: formatUserResponse(user) }); + } + } catch (err) { + console.error(err); + return res + .status(500) + .json({ message: "Unknown error when getting user!" }); + } +} + +export async function getAllUsers(req, res) { + try { + const users = await _findAllUsers(); + + return res + .status(200) + .json({ message: `Found users`, data: users.map(formatUserResponse) }); + } catch (err) { + console.error(err); + return res + .status(500) + .json({ message: "Unknown error when getting all users!" }); + } +} + +export async function updateUser(req, res) { + try { + const { + username, + email, + password, + bio, + linkedin, + github, + profilePictureUrl, + } = req.body; + if (username || email || password || bio || linkedin || github) { + const userId = req.params.id; + if (!isValidObjectId(userId)) { + return res.status(404).json({ message: `User ${userId} not found` }); + } + const user = await _findUserById(userId); + if (!user) { + return res.status(404).json({ message: `User ${userId} not found` }); + } + if (username || email) { + let existingUser = await _findUserByUsername(username); + if (existingUser && existingUser.id !== userId) { + return res.status(409).json({ message: "username already exists" }); + } + existingUser = await _findUserByEmail(email); + if (existingUser && existingUser.id !== userId) { + return res.status(409).json({ message: "email already exists" }); + } + } + + let hashedPassword; + if (password) { + const salt = bcrypt.genSaltSync(10); + hashedPassword = bcrypt.hashSync(password, salt); + } + + const updatedUser = await _updateUserById( + userId, + username, + email, + hashedPassword, + bio, + linkedin, + github, + profilePictureUrl + ); + return res.status(200).json({ + message: `Updated data for user ${userId}`, + data: formatUserResponse(updatedUser), + }); + } else { + return res.status(400).json({ + message: + "No field to update: username and email and password are all missing!", + }); + } + } catch (err) { + console.error(err); + return res + .status(500) + .json({ message: "Unknown error when updating user!" }); + } +} + +export async function updateUserPrivilege(req, res) { + try { + const { isAdmin } = req.body; + + if (isAdmin !== undefined) { + // isAdmin can have boolean value true or false + const userId = req.params.id; + if (!isValidObjectId(userId)) { + return res.status(404).json({ message: `User ${userId} not found` }); + } + const user = await _findUserById(userId); + if (!user) { + return res.status(404).json({ message: `User ${userId} not found` }); + } + + const updatedUser = await _updateUserPrivilegeById( + userId, + isAdmin === true + ); + return res.status(200).json({ + message: `Updated privilege for user ${userId}`, + data: formatUserResponse(updatedUser), + }); + } else { + return res.status(400).json({ message: "isAdmin is missing!" }); + } + } catch (err) { + console.error(err); + return res + .status(500) + .json({ message: "Unknown error when updating user privilege!" }); + } +} + +export async function deleteUser(req, res) { + try { + const userId = req.params.id; + if (!isValidObjectId(userId)) { + return res.status(404).json({ message: `User ${userId} not found` }); + } + const user = await _findUserById(userId); + if (!user) { + return res.status(404).json({ message: `User ${userId} not found` }); + } + + await _deleteUserById(userId); + return res + .status(200) + .json({ message: `Deleted user ${userId} successfully` }); + } catch (err) { + console.error(err); + return res + .status(500) + .json({ message: "Unknown error when deleting user!" }); + } +} + +// send email to user +export async function verifyUser(req, res) { + try { + const { code } = req.query; + const user = await _findUserByVerificationCode(code); + if (!user) { + return res + .status(404) + .json({ message: `User not found with verification code ${code}` }); + } + + if (user.isVerified) { + return res + .status(400) + .json({ message: `User ${user.username} is already verified` }); + } + + const updatedUser = await _verifyUserByVerificationCode(code); + return res.status(200).json({ + message: `Verified user ${user.username}`, + data: formatUserResponse(updatedUser), + }); + } catch (err) { + console.error(err); + return res + .status(500) + .json({ message: "Unknown error when verifying user!" }); + } +} + +export async function requestPasswordReset(req, res) { + try { + const { email } = req.body; + if (email) { + const user = await _findUserByEmail(email); + if (!user) { + return res + .status(404) + .json({ message: `User not found with email ${email}` }); + } + + // For password reset, you can generate a random password reset code and save it in the database + const passwordResetCode = + Math.random().toString(36).substring(2, 15) + + Math.random().toString(36).substring(2, 15); + + const updatedUser = await _addPasswordResetCodeToUser( + user.id, + passwordResetCode + ); + console.log(updatedUser); + + // Send email to user + await sendPasswordResetEmail(email, user.username, passwordResetCode); + + return res.status(200).json({ + message: `Sent password reset email to user ${user.username}`, + }); + } else { + return res.status(400).json({ message: "email is missing!" }); + } + } catch (err) { + console.error(err); + return res + .status(500) + .json({ message: "Unknown error when requesting password reset!" }); + } +} + +export async function checkPasswordResetCode(req, res) { + try { + const { code } = req.body; + const user = await _findUserByPasswordResetCode(code); + if (!user) { + return res + .status(404) + .json({ message: `User not found with verification code ${code}` }); + } + + return res.status(200).json({ + message: `Found user with verification code ${code}`, + username: user.username, + }); + } catch (err) { + console.error(err); + return res + .status(500) + .json({ message: "Unknown error when checking verification code!" }); + } +} + +export async function resetPasswordUsingCode(req, res) { + try { + const { code, password } = req.body; + if (password) { + const user = await _findUserByPasswordResetCode(code); + if (!user) { + return res + .status(404) + .json({ message: `User not found with verification code ${code}` }); + } + + const salt = bcrypt.genSaltSync(10); + const hashedPassword = bcrypt.hashSync(password, salt); + + const updatedUser = await _updateUserById( + user.id, + user.username, + user.email, + hashedPassword, + user.bio, + user.linkedin, + user.github + ); + return res.status(200).json({ + message: `Reset password for user ${user.username}`, + data: formatUserResponse(updatedUser), + }); + } else { + return res.status(400).json({ message: "password is missing!" }); + } + } catch (err) { + console.error(err); + return res + .status(500) + .json({ message: "Unknown error when resetting password!" }); + } +} + +export async function resetPasswordFromProfile(req, res) { + try { + const { password } = req.body; + const userId = req.params.id; + console.log(req.body); + if (password) { + const user = await _findUserById(userId); + if (!user) { + console.log("ERROR"); + return res + .status(404) + .json({ message: `User not found with user ID ${code}` }); + } + + const salt = bcrypt.genSaltSync(10); + const hashedPassword = bcrypt.hashSync(password, salt); + + const updatedUser = await _updateUserById( + user.id, + user.username, + user.email, + hashedPassword, + user.bio, + user.linkedin, + user.github + ); + return res.status(200).json({ + message: `Reset password for user ${user.username}`, + data: formatUserResponse(updatedUser), + }); + } else { + return res.status(400).json({ message: "password is missing!" }); + } + } catch (err) { + console.error(err); + return res + .status(500) + .json({ message: "Unknown error when resetting password!" }); + } +} + +export function formatUserResponse(user) { + return { + id: user.id, + username: user.username, + email: user.email, + bio: user.bio, + linkedin: user.linkedin, + github: user.github, + isVerified: user.isVerified, + isAdmin: user.isAdmin, + createdAt: user.createdAt, + profilePictureUrl: user.profilePictureUrl, + }; +} + +export function getFileUrl(req, res) { + upload(req, res, async (err) => { + if (err) { + console.error("File upload error:", err); + return res.status(400).json({ message: "Error uploading file" }); + } + + const userId = req.params.id; + + // Validate user ID + if (!isValidObjectId(userId)) { + return res.status(404).json({ message: `User ${userId} not found` }); + } + + const user = await _findUserById(userId); + if (!user) { + return res.status(404).json({ message: `User ${userId} not found` }); + } + + const file = req.file; + if (!file) { + return res.status(400).json({ message: "No file provided" }); + } + + // Define a unique file name + const blob = profileBucket.file( + `profile-pictures/${userId}-${Date.now()}-${file.originalname}` + ); + const blobStream = blob.createWriteStream({ + metadata: { + contentType: file.mimetype, + }, + }); + + blobStream.on("error", (error) => { + console.error("GCS upload error:", error); + return res + .status(500) + .json({ message: "Error uploading profile picture" }); + }); + + blobStream.on("finish", async () => { + const publicUrl = `https://storage.googleapis.com/${profileBucketName}/${blob.name}`; + + return res.status(200).json({ + message: "Picture uploaded successfully", + fileUrl: publicUrl, + }); + }); + + // Pipe the file buffer to the blob stream + blobStream.end(file.buffer); + }); +} diff --git a/backend/user/index.js b/backend/user/index.js new file mode 100644 index 0000000000..0e7936917c --- /dev/null +++ b/backend/user/index.js @@ -0,0 +1,64 @@ +import express from "express"; +import cors from "cors"; + +import userRoutes from "./routes/user-routes.js"; +import authRoutes from "./routes/auth-routes.js"; + +const app = express(); + +app.use(express.urlencoded({ extended: true })); +app.use(express.json()); +app.use(cors()); // config cors so that front-end can use +app.options("*", cors()); + +// To handle CORS Errors +app.use((req, res, next) => { + res.header("Access-Control-Allow-Origin", "*"); // "*" -> Allow all links to access + + res.header( + "Access-Control-Allow-Headers", + "Origin, X-Requested-With, Content-Type, Accept, Authorization" + ); + + // Browsers usually send this before PUT or POST Requests + if (req.method === "OPTIONS") { + res.header("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT, PATCH"); + return res.status(200).json({}); + } + + // Continue Route Processing + next(); +}); + +const apiRouter = express.Router(); + +apiRouter.use("/user", userRoutes); +apiRouter.use("/auth", authRoutes); + +apiRouter.get("/", (req, res, next) => { + console.log("Sending Greetings!"); + res.json({ + message: "Hello World from iam-service", + }); +}); + +app.use("/api/iam", apiRouter); + +// Handle When No Route Match Is Found +app.use((req, res, next) => { + console.log(req.url); + const error = new Error("Route Not Found"); + error.status = 404; + next(error); +}); + +app.use((error, req, res, next) => { + res.status(error.status || 500); + res.json({ + error: { + message: error.message, + }, + }); +}); + +export default app; diff --git a/backend/user/middleware/basic-access-control.js b/backend/user/middleware/basic-access-control.js new file mode 100644 index 0000000000..bb92665710 --- /dev/null +++ b/backend/user/middleware/basic-access-control.js @@ -0,0 +1,48 @@ +import jwt from "jsonwebtoken"; +import { findUserById as _findUserById } from "../model/repository.js"; + +export function verifyAccessToken(req, res, next) { + const authHeader = req.headers["authorization"]; + if (!authHeader) { + return res.status(401).json({ message: "Authentication failed" }); + } + + // request auth header: `Authorization: Bearer + ` + const token = authHeader.split(" ")[1]; + jwt.verify(token, process.env.JWT_SECRET, async (err, user) => { + if (err) { + return res.status(401).json({ message: "Authentication failed" }); + } + + // load latest user info from DB + const dbUser = await _findUserById(user.id); + if (!dbUser) { + return res.status(401).json({ message: "Authentication failed" }); + } + + req.user = { id: dbUser.id, username: dbUser.username, email: dbUser.email, isAdmin: dbUser.isAdmin }; + next(); + }); +} + +export function verifyIsAdmin(req, res, next) { + if (req.user.isAdmin) { + next(); + } else { + return res.status(403).json({ message: "Not authorized to access this resource" }); + } +} + +export function verifyIsOwnerOrAdmin(req, res, next) { + if (req.user.isAdmin) { + return next(); + } + + const userIdFromReqParams = req.params.id; + const userIdFromToken = req.user.id; + if (userIdFromReqParams === userIdFromToken) { + return next(); + } + + return res.status(403).json({ message: "Not authorized to access this resource" }); +} diff --git a/backend/user/model/repository.js b/backend/user/model/repository.js new file mode 100644 index 0000000000..0d1b69caf3 --- /dev/null +++ b/backend/user/model/repository.js @@ -0,0 +1,113 @@ +import UserModel from "./user-model.js"; +import "dotenv/config"; +import { connect } from "mongoose"; + +export async function connectToDB() { + let mongoDBUri = + process.env.ENV === "PROD" + ? process.env.DB_CLOUD_URI + : process.env.DB_LOCAL_URI; + + await connect(mongoDBUri); +} + +export async function createUser(username, email, password, verificationCode) { + return new UserModel({ username, email, password, verificationCode }).save(); +} + +export async function findUserByEmail(email) { + return UserModel.findOne({ email }); +} + +export async function findUserById(userId) { + return UserModel.findById(userId); +} + +export async function findUserByUsername(username) { + return UserModel.findOne({ username }); +} + +export async function findUserByUsernameOrId(userId) { + const length = userId.length; + if (length === 24) { + return await findUserById(userId); + } + return await findUserByUsername(userId); +} + +export async function findUserByUsernameOrEmail(username, email) { + return UserModel.findOne({ + $or: [{ username }, { email }], + }); +} + +export async function findAllUsers() { + return UserModel.find(); +} + +export async function updateUserById( + userId, + username, + email, + password, + bio, + linkedin, + github, + profilePictureUrl +) { + return UserModel.findByIdAndUpdate( + userId, + { + $set: { + username, + email, + password, + bio, + linkedin, + github, + profilePictureUrl, + }, + }, + { new: true } // return the updated user + ); +} + +export async function updateUserPrivilegeById(userId, isAdmin) { + return UserModel.findByIdAndUpdate( + userId, + { + $set: { + isAdmin, + }, + }, + { new: true } // return the updated user + ); +} + +export async function deleteUserById(userId) { + return UserModel.findByIdAndDelete(userId); +} + +export async function findUserByVerificationCode(verificationCode) { + return UserModel.findOne({ verificationCode }); +} + +export async function verifyUserByVerificationCode(verificationCode) { + return UserModel.findOneAndUpdate( + { verificationCode }, + { $set: { isVerified: true } }, // we keep verification code because we want to say "already verified" if the user decides to go again + { new: true }, // return the updated user + ); +} + +export async function addPasswordResetCodeToUser(userId, passwordResetCode) { + return UserModel.findByIdAndUpdate( + userId, + { $set: { passwordResetCode } }, + { new: true }, // return the updated user + ); +} + +export async function findUserByPasswordResetCode(passwordResetCode) { + return UserModel.findOne({ passwordResetCode }); +} \ No newline at end of file diff --git a/backend/user/model/user-model.js b/backend/user/model/user-model.js new file mode 100644 index 0000000000..5594e0b667 --- /dev/null +++ b/backend/user/model/user-model.js @@ -0,0 +1,60 @@ +import mongoose from "mongoose"; + +const Schema = mongoose.Schema; + +const UserModelSchema = new Schema({ + username: { + type: String, + required: true, + unique: true, + }, + email: { + type: String, + required: true, + unique: true, + }, + password: { + type: String, + required: true, + }, + bio: { + type: String, + default: "", + }, + linkedin: { + type: String, + default: "", + }, + github: { + type: String, + default: "", + }, + createdAt: { + type: Date, + default: Date.now, // Setting default to the current date/time + }, + profilePictureUrl: { + type: String, + default: "", + }, + verificationCode: { + type: String, + default: "", + }, + passwordResetCode: { + type: String, + default: "", + }, + isVerified: { + type: Boolean, + required: true, + default: false, + }, + isAdmin: { + type: Boolean, + required: true, + default: false, + }, +}); + +export default mongoose.model("UserModel", UserModelSchema); diff --git a/backend/user/package-lock.json b/backend/user/package-lock.json new file mode 100644 index 0000000000..4bfc565040 --- /dev/null +++ b/backend/user/package-lock.json @@ -0,0 +1,2728 @@ +{ + "name": "user-service", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "user-service", + "version": "1.0.0", + "license": "ISC", + "dependencies": { + "@google-cloud/storage": "^7.14.0", + "bcrypt": "^5.1.1", + "bcryptjs": "^2.4.3", + "cors": "^2.8.5", + "dotenv": "^16.4.5", + "express": "^4.19.2", + "jsonwebtoken": "^9.0.2", + "mongoose": "^8.5.4", + "multer": "^1.4.5-lts.1", + "nodemailer": "^6.9.16" + }, + "devDependencies": { + "@types/bcryptjs": "^2.4.6", + "nodemon": "^3.1.4" + } + }, + "node_modules/@google-cloud/paginator": { + "version": "5.0.2", + "resolved": "https://registry.npmjs.org/@google-cloud/paginator/-/paginator-5.0.2.tgz", + "integrity": "sha512-DJS3s0OVH4zFDB1PzjxAsHqJT6sKVbRwwML0ZBP9PbU7Yebtu/7SWMRzvO2J3nUi9pRNITCfu4LJeooM2w4pjg==", + "license": "Apache-2.0", + "dependencies": { + "arrify": "^2.0.0", + "extend": "^3.0.2" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@google-cloud/projectify": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/@google-cloud/projectify/-/projectify-4.0.0.tgz", + "integrity": "sha512-MmaX6HeSvyPbWGwFq7mXdo0uQZLGBYCwziiLIGq5JVX+/bdI3SAq6bP98trV5eTWfLuvsMcIC1YJOF2vfteLFA==", + "license": "Apache-2.0", + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@google-cloud/promisify": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/@google-cloud/promisify/-/promisify-4.0.0.tgz", + "integrity": "sha512-Orxzlfb9c67A15cq2JQEyVc7wEsmFBmHjZWZYQMUyJ1qivXyMwdyNOs9odi79hze+2zqdTtu1E19IM/FtqZ10g==", + "license": "Apache-2.0", + "engines": { + "node": ">=14" + } + }, + "node_modules/@google-cloud/storage": { + "version": "7.14.0", + "resolved": "https://registry.npmjs.org/@google-cloud/storage/-/storage-7.14.0.tgz", + "integrity": "sha512-H41bPL2cMfSi4EEnFzKvg7XSb7T67ocSXrmF7MPjfgFB0L6CKGzfIYJheAZi1iqXjz6XaCT1OBf6HCG5vDBTOQ==", + "license": "Apache-2.0", + "dependencies": { + "@google-cloud/paginator": "^5.0.0", + "@google-cloud/projectify": "^4.0.0", + "@google-cloud/promisify": "^4.0.0", + "abort-controller": "^3.0.0", + "async-retry": "^1.3.3", + "duplexify": "^4.1.3", + "fast-xml-parser": "^4.4.1", + "gaxios": "^6.0.2", + "google-auth-library": "^9.6.3", + "html-entities": "^2.5.2", + "mime": "^3.0.0", + "p-limit": "^3.0.1", + "retry-request": "^7.0.0", + "teeny-request": "^9.0.0", + "uuid": "^8.0.0" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/@google-cloud/storage/node_modules/mime": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/mime/-/mime-3.0.0.tgz", + "integrity": "sha512-jSCU7/VB1loIWBZe14aEYHU/+1UMEHoaO7qxCOVJOw9GgH72VAWppxNcjU+x9a2k3GSIBXNKxXQFqRvvZ7vr3A==", + "license": "MIT", + "bin": { + "mime": "cli.js" + }, + "engines": { + "node": ">=10.0.0" + } + }, + "node_modules/@mapbox/node-pre-gyp": { + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/@mapbox/node-pre-gyp/-/node-pre-gyp-1.0.11.tgz", + "integrity": "sha512-Yhlar6v9WQgUp/He7BdgzOz8lqMQ8sU+jkCq7Wx8Myc5YFJLbEe7lgui/V7G1qB1DJykHSGwreceSaD60Y0PUQ==", + "dependencies": { + "detect-libc": "^2.0.0", + "https-proxy-agent": "^5.0.0", + "make-dir": "^3.1.0", + "node-fetch": "^2.6.7", + "nopt": "^5.0.0", + "npmlog": "^5.0.1", + "rimraf": "^3.0.2", + "semver": "^7.3.5", + "tar": "^6.1.11" + }, + "bin": { + "node-pre-gyp": "bin/node-pre-gyp" + } + }, + "node_modules/@mongodb-js/saslprep": { + "version": "1.1.8", + "resolved": "https://registry.npmjs.org/@mongodb-js/saslprep/-/saslprep-1.1.8.tgz", + "integrity": "sha512-qKwC/M/nNNaKUBMQ0nuzm47b7ZYWQHN3pcXq4IIcoSBc2hOIrflAxJduIvvqmhoz3gR2TacTAs8vlsCVPkiEdQ==", + "dependencies": { + "sparse-bitfield": "^3.0.3" + } + }, + "node_modules/@tootallnate/once": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/@tootallnate/once/-/once-2.0.0.tgz", + "integrity": "sha512-XCuKFP5PS55gnMVu3dty8KPatLqUoy/ZYzDzAGCQ8JNFCkLXzmI7vNHCR+XpbZaMWQK/vQubr7PkYq8g470J/A==", + "license": "MIT", + "engines": { + "node": ">= 10" + } + }, + "node_modules/@types/bcryptjs": { + "version": "2.4.6", + "resolved": "https://registry.npmjs.org/@types/bcryptjs/-/bcryptjs-2.4.6.tgz", + "integrity": "sha512-9xlo6R2qDs5uixm0bcIqCeMCE6HiQsIyel9KQySStiyqNl2tnj2mP3DX1Nf56MD6KMenNNlBBsy3LJ7gUEQPXQ==", + "dev": true + }, + "node_modules/@types/caseless": { + "version": "0.12.5", + "resolved": "https://registry.npmjs.org/@types/caseless/-/caseless-0.12.5.tgz", + "integrity": "sha512-hWtVTC2q7hc7xZ/RLbxapMvDMgUnDvKvMOpKal4DrMyfGBUfB1oKaZlIRr6mJL+If3bAP6sV/QneGzF6tJjZDg==", + "license": "MIT" + }, + "node_modules/@types/node": { + "version": "22.9.0", + "resolved": "https://registry.npmjs.org/@types/node/-/node-22.9.0.tgz", + "integrity": "sha512-vuyHg81vvWA1Z1ELfvLko2c8f34gyA0zaic0+Rllc5lbCnbSyuvb2Oxpm6TAUAC/2xZN3QGqxBNggD1nNR2AfQ==", + "license": "MIT", + "dependencies": { + "undici-types": "~6.19.8" + } + }, + "node_modules/@types/request": { + "version": "2.48.12", + "resolved": "https://registry.npmjs.org/@types/request/-/request-2.48.12.tgz", + "integrity": "sha512-G3sY+NpsA9jnwm0ixhAFQSJ3Q9JkpLZpJbI3GMv0mIAT0y3mRabYeINzal5WOChIiaTEGQYlHOKgkaM9EisWHw==", + "license": "MIT", + "dependencies": { + "@types/caseless": "*", + "@types/node": "*", + "@types/tough-cookie": "*", + "form-data": "^2.5.0" + } + }, + "node_modules/@types/tough-cookie": { + "version": "4.0.5", + "resolved": "https://registry.npmjs.org/@types/tough-cookie/-/tough-cookie-4.0.5.tgz", + "integrity": "sha512-/Ad8+nIOV7Rl++6f1BdKxFSMgmoqEoYbHRpPcx3JEfv8VRsQe9Z4mCXeJBzxs7mbHY/XOZZuXlRNfhpVPbs6ZA==", + "license": "MIT" + }, + "node_modules/@types/webidl-conversions": { + "version": "7.0.3", + "resolved": "https://registry.npmjs.org/@types/webidl-conversions/-/webidl-conversions-7.0.3.tgz", + "integrity": "sha512-CiJJvcRtIgzadHCYXw7dqEnMNRjhGZlYK05Mj9OyktqV8uVT8fD2BFOB7S1uwBE3Kj2Z+4UyPmFw/Ixgw/LAlA==" + }, + "node_modules/@types/whatwg-url": { + "version": "11.0.5", + "resolved": "https://registry.npmjs.org/@types/whatwg-url/-/whatwg-url-11.0.5.tgz", + "integrity": "sha512-coYR071JRaHa+xoEvvYqvnIHaVqaYrLPbsufM9BF63HkwI5Lgmy2QR8Q5K/lYDYo5AK82wOvSOS0UsLTpTG7uQ==", + "dependencies": { + "@types/webidl-conversions": "*" + } + }, + "node_modules/abbrev": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-1.1.1.tgz", + "integrity": "sha512-nne9/IiQ/hzIhY6pdDnbBtz7DjPTKrY00P/zvPSm5pOFkl6xuGrGnXn/VtTNNfNtAfZ9/1RtehkszU9qcTii0Q==" + }, + "node_modules/abort-controller": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/abort-controller/-/abort-controller-3.0.0.tgz", + "integrity": "sha512-h8lQ8tacZYnR3vNQTgibj+tODHI5/+l06Au2Pcriv/Gmet0eaj4TwWH41sO9wnHDiQsEj19q0drzdWdeAHtweg==", + "license": "MIT", + "dependencies": { + "event-target-shim": "^5.0.0" + }, + "engines": { + "node": ">=6.5" + } + }, + "node_modules/accepts": { + "version": "1.3.8", + "resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.8.tgz", + "integrity": "sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw==", + "dependencies": { + "mime-types": "~2.1.34", + "negotiator": "0.6.3" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/agent-base": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz", + "integrity": "sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==", + "dependencies": { + "debug": "4" + }, + "engines": { + "node": ">= 6.0.0" + } + }, + "node_modules/agent-base/node_modules/debug": { + "version": "4.3.6", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.6.tgz", + "integrity": "sha512-O/09Bd4Z1fBrU4VzkhFqVgpPzaGbw6Sm9FEkBT1A/YBXQFGuuSxa1dN2nxgxS34JmKXqYx8CZAwEVoJFImUXIg==", + "dependencies": { + "ms": "2.1.2" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/agent-base/node_modules/ms": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==" + }, + "node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "engines": { + "node": ">=8" + } + }, + "node_modules/anymatch": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.3.tgz", + "integrity": "sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw==", + "dev": true, + "dependencies": { + "normalize-path": "^3.0.0", + "picomatch": "^2.0.4" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/append-field": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/append-field/-/append-field-1.0.0.tgz", + "integrity": "sha512-klpgFSWLW1ZEs8svjfb7g4qWY0YS5imI82dTg+QahUvJ8YqAY0P10Uk8tTyh9ZGuYEZEMaeJYCF5BFuX552hsw==", + "license": "MIT" + }, + "node_modules/aproba": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/aproba/-/aproba-2.0.0.tgz", + "integrity": "sha512-lYe4Gx7QT+MKGbDsA+Z+he/Wtef0BiwDOlK/XkBrdfsh9J/jPPXbX0tE9x9cl27Tmu5gg3QUbUrQYa/y+KOHPQ==" + }, + "node_modules/are-we-there-yet": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/are-we-there-yet/-/are-we-there-yet-2.0.0.tgz", + "integrity": "sha512-Ci/qENmwHnsYo9xKIcUJN5LeDKdJ6R1Z1j9V/J5wyq8nh/mYPEpIKJbBZXtZjG04HiK7zV/p6Vs9952MrMeUIw==", + "deprecated": "This package is no longer supported.", + "dependencies": { + "delegates": "^1.0.0", + "readable-stream": "^3.6.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/array-flatten": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz", + "integrity": "sha512-PCVAQswWemu6UdxsDFFX/+gVeYqKAod3D3UVm91jHwynguOwAvYPhx8nNlM++NqRcK6CxxpUafjmhIdKiHibqg==" + }, + "node_modules/arrify": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/arrify/-/arrify-2.0.1.tgz", + "integrity": "sha512-3duEwti880xqi4eAMN8AyR4a0ByT90zoYdLlevfrvU43vb0YZwZVfxOgxWrLXXXpyugL0hNZc9G6BiB5B3nUug==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/async-retry": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/async-retry/-/async-retry-1.3.3.tgz", + "integrity": "sha512-wfr/jstw9xNi/0teMHrRW7dsz3Lt5ARhYNZ2ewpadnhaIp5mbALhOAP+EAdsC7t4Z6wqsDVv9+W6gm1Dk9mEyw==", + "license": "MIT", + "dependencies": { + "retry": "0.13.1" + } + }, + "node_modules/asynckit": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", + "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==", + "license": "MIT" + }, + "node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==" + }, + "node_modules/base64-js": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", + "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/bcrypt": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/bcrypt/-/bcrypt-5.1.1.tgz", + "integrity": "sha512-AGBHOG5hPYZ5Xl9KXzU5iKq9516yEmvCKDg3ecP5kX2aB6UqTeXZxk2ELnDgDm6BQSMlLt9rDB4LoSMx0rYwww==", + "hasInstallScript": true, + "dependencies": { + "@mapbox/node-pre-gyp": "^1.0.11", + "node-addon-api": "^5.0.0" + }, + "engines": { + "node": ">= 10.0.0" + } + }, + "node_modules/bcryptjs": { + "version": "2.4.3", + "resolved": "https://registry.npmjs.org/bcryptjs/-/bcryptjs-2.4.3.tgz", + "integrity": "sha512-V/Hy/X9Vt7f3BbPJEi8BdVFMByHi+jNXrYkW3huaybV/kQ0KJg0Y6PkEMbn+zeT+i+SiKZ/HMqJGIIt4LZDqNQ==" + }, + "node_modules/bignumber.js": { + "version": "9.1.2", + "resolved": "https://registry.npmjs.org/bignumber.js/-/bignumber.js-9.1.2.tgz", + "integrity": "sha512-2/mKyZH9K85bzOEfhXDBFZTGd1CTs+5IHpeFQo9luiBG7hghdC851Pj2WAhb6E3R6b9tZj/XKhbg4fum+Kepug==", + "license": "MIT", + "engines": { + "node": "*" + } + }, + "node_modules/binary-extensions": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.3.0.tgz", + "integrity": "sha512-Ceh+7ox5qe7LJuLHoY0feh3pHuUDHAcRUeyL2VYghZwfpkNIy/+8Ocg0a3UuSoYzavmylwuLWQOf3hl0jjMMIw==", + "dev": true, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/body-parser": { + "version": "1.20.2", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.2.tgz", + "integrity": "sha512-ml9pReCu3M61kGlqoTm2umSXTlRTuGTx0bfYj+uIUKKYycG5NtSbeetV3faSU6R7ajOPw0g/J1PvK4qNy7s5bA==", + "dependencies": { + "bytes": "3.1.2", + "content-type": "~1.0.5", + "debug": "2.6.9", + "depd": "2.0.0", + "destroy": "1.2.0", + "http-errors": "2.0.0", + "iconv-lite": "0.4.24", + "on-finished": "2.4.1", + "qs": "6.11.0", + "raw-body": "2.5.2", + "type-is": "~1.6.18", + "unpipe": "1.0.0" + }, + "engines": { + "node": ">= 0.8", + "npm": "1.2.8000 || >= 1.4.16" + } + }, + "node_modules/brace-expansion": { + "version": "1.1.11", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", + "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "node_modules/braces": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.3.tgz", + "integrity": "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==", + "dev": true, + "dependencies": { + "fill-range": "^7.1.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/bson": { + "version": "6.8.0", + "resolved": "https://registry.npmjs.org/bson/-/bson-6.8.0.tgz", + "integrity": "sha512-iOJg8pr7wq2tg/zSlCCHMi3hMm5JTOxLTagf3zxhcenHsFp+c6uOs6K7W5UE7A4QIJGtqh/ZovFNMP4mOPJynQ==", + "engines": { + "node": ">=16.20.1" + } + }, + "node_modules/buffer-equal-constant-time": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz", + "integrity": "sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA==" + }, + "node_modules/buffer-from": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz", + "integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==", + "license": "MIT" + }, + "node_modules/busboy": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/busboy/-/busboy-1.6.0.tgz", + "integrity": "sha512-8SFQbg/0hQ9xy3UNTB0YEnsNBbWfhf7RtnzpL7TkBiTBRfrQ9Fxcnz7VJsleJpyp6rVLvXiuORqjlHi5q+PYuA==", + "dependencies": { + "streamsearch": "^1.1.0" + }, + "engines": { + "node": ">=10.16.0" + } + }, + "node_modules/bytes": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", + "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/call-bind": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.7.tgz", + "integrity": "sha512-GHTSNSYICQ7scH7sZ+M2rFopRoLh8t2bLSW6BbgrtLsahOIB5iyAVJf9GjWK3cYTDaMj4XdBpM1cA6pIS0Kv2w==", + "dependencies": { + "es-define-property": "^1.0.0", + "es-errors": "^1.3.0", + "function-bind": "^1.1.2", + "get-intrinsic": "^1.2.4", + "set-function-length": "^1.2.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/chokidar": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.6.0.tgz", + "integrity": "sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw==", + "dev": true, + "dependencies": { + "anymatch": "~3.1.2", + "braces": "~3.0.2", + "glob-parent": "~5.1.2", + "is-binary-path": "~2.1.0", + "is-glob": "~4.0.1", + "normalize-path": "~3.0.0", + "readdirp": "~3.6.0" + }, + "engines": { + "node": ">= 8.10.0" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + }, + "optionalDependencies": { + "fsevents": "~2.3.2" + } + }, + "node_modules/chownr": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/chownr/-/chownr-2.0.0.tgz", + "integrity": "sha512-bIomtDF5KGpdogkLd9VspvFzk9KfpyyGlS8YFVZl7TGPBHL5snIOnxeshwVgPteQ9b4Eydl+pVbIyE1DcvCWgQ==", + "engines": { + "node": ">=10" + } + }, + "node_modules/color-support": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/color-support/-/color-support-1.1.3.tgz", + "integrity": "sha512-qiBjkpbMLO/HL68y+lh4q0/O1MZFj2RX6X/KmMa3+gJD3z+WwI1ZzDHysvqHGS3mP6mznPckpXmw1nI9cJjyRg==", + "bin": { + "color-support": "bin.js" + } + }, + "node_modules/combined-stream": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", + "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==", + "license": "MIT", + "dependencies": { + "delayed-stream": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/concat-map": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", + "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==" + }, + "node_modules/concat-stream": { + "version": "1.6.2", + "resolved": "https://registry.npmjs.org/concat-stream/-/concat-stream-1.6.2.tgz", + "integrity": "sha512-27HBghJxjiZtIk3Ycvn/4kbJk/1uZuJFfuPEns6LaEvpvG1f0hTea8lilrouyo9mVc2GWdcEZ8OLoGmSADlrCw==", + "engines": [ + "node >= 0.8" + ], + "license": "MIT", + "dependencies": { + "buffer-from": "^1.0.0", + "inherits": "^2.0.3", + "readable-stream": "^2.2.2", + "typedarray": "^0.0.6" + } + }, + "node_modules/concat-stream/node_modules/readable-stream": { + "version": "2.3.8", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.8.tgz", + "integrity": "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==", + "license": "MIT", + "dependencies": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", + "util-deprecate": "~1.0.1" + } + }, + "node_modules/concat-stream/node_modules/safe-buffer": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", + "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==", + "license": "MIT" + }, + "node_modules/concat-stream/node_modules/string_decoder": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", + "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", + "license": "MIT", + "dependencies": { + "safe-buffer": "~5.1.0" + } + }, + "node_modules/console-control-strings": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/console-control-strings/-/console-control-strings-1.1.0.tgz", + "integrity": "sha512-ty/fTekppD2fIwRvnZAVdeOiGd1c7YXEixbgJTNzqcxJWKQnjJ/V1bNEEE6hygpM3WjwHFUVK6HTjWSzV4a8sQ==" + }, + "node_modules/content-disposition": { + "version": "0.5.4", + "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.4.tgz", + "integrity": "sha512-FveZTNuGw04cxlAiWbzi6zTAL/lhehaWbTtgluJh4/E95DqMwTmha3KZN1aAWA8cFIhHzMZUvLevkw5Rqk+tSQ==", + "dependencies": { + "safe-buffer": "5.2.1" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/content-type": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz", + "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.6.0.tgz", + "integrity": "sha512-U71cyTamuh1CRNCfpGY6to28lxvNwPG4Guz/EVjgf3Jmzv0vlDp1atT9eS5dDjMYHucpHbWns6Lwf3BKz6svdw==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie-signature": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.6.tgz", + "integrity": "sha512-QADzlaHc8icV8I7vbaJXJwod9HWYp8uCqf1xa4OfNu1T7JVxQIrUgOWtHdNDtPiywmFbiS12VjotIXLrKM3orQ==" + }, + "node_modules/core-util-is": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.3.tgz", + "integrity": "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==", + "license": "MIT" + }, + "node_modules/cors": { + "version": "2.8.5", + "resolved": "https://registry.npmjs.org/cors/-/cors-2.8.5.tgz", + "integrity": "sha512-KIHbLJqu73RGr/hnbrO9uBeixNGuvSQjul/jdFvS/KFSIH1hWVd1ng7zOHx+YrEfInLG7q4n6GHQ9cDtxv/P6g==", + "dependencies": { + "object-assign": "^4", + "vary": "^1" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "dependencies": { + "ms": "2.0.0" + } + }, + "node_modules/define-data-property": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/define-data-property/-/define-data-property-1.1.4.tgz", + "integrity": "sha512-rBMvIzlpA8v6E+SJZoo++HAYqsLrkg7MSfIinMPFhmkorw7X+dOXVJQs+QT69zGkzMyfDnIMN2Wid1+NbL3T+A==", + "dependencies": { + "es-define-property": "^1.0.0", + "es-errors": "^1.3.0", + "gopd": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/delayed-stream": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", + "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==", + "license": "MIT", + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/delegates": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/delegates/-/delegates-1.0.0.tgz", + "integrity": "sha512-bd2L678uiWATM6m5Z1VzNCErI3jiGzt6HGY8OVICs40JQq/HALfbyNJmp0UDakEY4pMMaN0Ly5om/B1VI/+xfQ==" + }, + "node_modules/depd": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", + "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/destroy": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/destroy/-/destroy-1.2.0.tgz", + "integrity": "sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg==", + "engines": { + "node": ">= 0.8", + "npm": "1.2.8000 || >= 1.4.16" + } + }, + "node_modules/detect-libc": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.0.3.tgz", + "integrity": "sha512-bwy0MGW55bG41VqxxypOsdSdGqLwXPI/focwgTYCFMbdUiBAxLg9CFzG08sz2aqzknwiX7Hkl0bQENjg8iLByw==", + "engines": { + "node": ">=8" + } + }, + "node_modules/dotenv": { + "version": "16.4.5", + "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.4.5.tgz", + "integrity": "sha512-ZmdL2rui+eB2YwhsWzjInR8LldtZHGDoQ1ugH85ppHKwpUHL7j7rN0Ti9NCnGiQbhaZ11FpR+7ao1dNsmduNUg==", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://dotenvx.com" + } + }, + "node_modules/duplexify": { + "version": "4.1.3", + "resolved": "https://registry.npmjs.org/duplexify/-/duplexify-4.1.3.tgz", + "integrity": "sha512-M3BmBhwJRZsSx38lZyhE53Csddgzl5R7xGJNk7CVddZD6CcmwMCH8J+7AprIrQKH7TonKxaCjcv27Qmf+sQ+oA==", + "license": "MIT", + "dependencies": { + "end-of-stream": "^1.4.1", + "inherits": "^2.0.3", + "readable-stream": "^3.1.1", + "stream-shift": "^1.0.2" + } + }, + "node_modules/ecdsa-sig-formatter": { + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/ecdsa-sig-formatter/-/ecdsa-sig-formatter-1.0.11.tgz", + "integrity": "sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ==", + "dependencies": { + "safe-buffer": "^5.0.1" + } + }, + "node_modules/ee-first": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", + "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==" + }, + "node_modules/emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==" + }, + "node_modules/encodeurl": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-1.0.2.tgz", + "integrity": "sha512-TPJXq8JqFaVYm2CWmPvnP2Iyo4ZSM7/QKcSmuMLDObfpH5fi7RUGmd/rTDf+rut/saiDiQEeVTNgAmJEdAOx0w==", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/end-of-stream": { + "version": "1.4.4", + "resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.4.tgz", + "integrity": "sha512-+uw1inIHVPQoaVuHzRyXd21icM+cnt4CzD5rW+NC1wjOUSTOs+Te7FOv7AhN7vS9x/oIyhLP5PR1H+phQAHu5Q==", + "license": "MIT", + "dependencies": { + "once": "^1.4.0" + } + }, + "node_modules/es-define-property": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.0.tgz", + "integrity": "sha512-jxayLKShrEqqzJ0eumQbVhTYQM27CfT1T35+gCgDFoL82JLsXqTJ76zv6A0YLOgEnLUMvLzsDsGIrl8NFpT2gQ==", + "dependencies": { + "get-intrinsic": "^1.2.4" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/escape-html": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", + "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==" + }, + "node_modules/etag": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", + "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/event-target-shim": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/event-target-shim/-/event-target-shim-5.0.1.tgz", + "integrity": "sha512-i/2XbnSz/uxRCU6+NdVJgKWDTM427+MqYbkQzD321DuCQJUqOuJKIA0IM2+W2xtYHdKOmZ4dR6fExsd4SXL+WQ==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/express": { + "version": "4.19.2", + "resolved": "https://registry.npmjs.org/express/-/express-4.19.2.tgz", + "integrity": "sha512-5T6nhjsT+EOMzuck8JjBHARTHfMht0POzlA60WV2pMD3gyXw2LZnZ+ueGdNxG+0calOJcWKbpFcuzLZ91YWq9Q==", + "dependencies": { + "accepts": "~1.3.8", + "array-flatten": "1.1.1", + "body-parser": "1.20.2", + "content-disposition": "0.5.4", + "content-type": "~1.0.4", + "cookie": "0.6.0", + "cookie-signature": "1.0.6", + "debug": "2.6.9", + "depd": "2.0.0", + "encodeurl": "~1.0.2", + "escape-html": "~1.0.3", + "etag": "~1.8.1", + "finalhandler": "1.2.0", + "fresh": "0.5.2", + "http-errors": "2.0.0", + "merge-descriptors": "1.0.1", + "methods": "~1.1.2", + "on-finished": "2.4.1", + "parseurl": "~1.3.3", + "path-to-regexp": "0.1.7", + "proxy-addr": "~2.0.7", + "qs": "6.11.0", + "range-parser": "~1.2.1", + "safe-buffer": "5.2.1", + "send": "0.18.0", + "serve-static": "1.15.0", + "setprototypeof": "1.2.0", + "statuses": "2.0.1", + "type-is": "~1.6.18", + "utils-merge": "1.0.1", + "vary": "~1.1.2" + }, + "engines": { + "node": ">= 0.10.0" + } + }, + "node_modules/extend": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/extend/-/extend-3.0.2.tgz", + "integrity": "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==", + "license": "MIT" + }, + "node_modules/fast-xml-parser": { + "version": "4.5.0", + "resolved": "https://registry.npmjs.org/fast-xml-parser/-/fast-xml-parser-4.5.0.tgz", + "integrity": "sha512-/PlTQCI96+fZMAOLMZK4CWG1ItCbfZ/0jx7UIJFChPNrx7tcEgerUgWbeieCM9MfHInUDyK8DWYZ+YrywDJuTg==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/NaturalIntelligence" + }, + { + "type": "paypal", + "url": "https://paypal.me/naturalintelligence" + } + ], + "license": "MIT", + "dependencies": { + "strnum": "^1.0.5" + }, + "bin": { + "fxparser": "src/cli/cli.js" + } + }, + "node_modules/fill-range": { + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz", + "integrity": "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==", + "dev": true, + "dependencies": { + "to-regex-range": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/finalhandler": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.2.0.tgz", + "integrity": "sha512-5uXcUVftlQMFnWC9qu/svkWv3GTd2PfUhK/3PLkYNAe7FbqJMt3515HaxE6eRL74GdsriiwujiawdaB1BpEISg==", + "dependencies": { + "debug": "2.6.9", + "encodeurl": "~1.0.2", + "escape-html": "~1.0.3", + "on-finished": "2.4.1", + "parseurl": "~1.3.3", + "statuses": "2.0.1", + "unpipe": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/form-data": { + "version": "2.5.2", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-2.5.2.tgz", + "integrity": "sha512-GgwY0PS7DbXqajuGf4OYlsrIu3zgxD6Vvql43IBhm6MahqA5SK/7mwhtNj2AdH2z35YR34ujJ7BN+3fFC3jP5Q==", + "license": "MIT", + "dependencies": { + "asynckit": "^0.4.0", + "combined-stream": "^1.0.6", + "mime-types": "^2.1.12", + "safe-buffer": "^5.2.1" + }, + "engines": { + "node": ">= 0.12" + } + }, + "node_modules/forwarded": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz", + "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/fresh": { + "version": "0.5.2", + "resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz", + "integrity": "sha512-zJ2mQYM18rEFOudeV4GShTGIQ7RbzA7ozbU9I/XBpm7kqgMywgmylMwXHxZJmkVoYkna9d2pVXVXPdYTP9ej8Q==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/fs-minipass": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/fs-minipass/-/fs-minipass-2.1.0.tgz", + "integrity": "sha512-V/JgOLFCS+R6Vcq0slCuaeWEdNC3ouDlJMNIsacH2VtALiu9mV4LPrHc5cDl8k5aw6J8jwgWWpiTo5RYhmIzvg==", + "dependencies": { + "minipass": "^3.0.0" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/fs-minipass/node_modules/minipass": { + "version": "3.3.6", + "resolved": "https://registry.npmjs.org/minipass/-/minipass-3.3.6.tgz", + "integrity": "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw==", + "dependencies": { + "yallist": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/fs.realpath": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", + "integrity": "sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==" + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/gauge": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/gauge/-/gauge-3.0.2.tgz", + "integrity": "sha512-+5J6MS/5XksCuXq++uFRsnUd7Ovu1XenbeuIuNRJxYWjgQbPuFhT14lAvsWfqfAmnwluf1OwMjz39HjfLPci0Q==", + "deprecated": "This package is no longer supported.", + "dependencies": { + "aproba": "^1.0.3 || ^2.0.0", + "color-support": "^1.1.2", + "console-control-strings": "^1.0.0", + "has-unicode": "^2.0.1", + "object-assign": "^4.1.1", + "signal-exit": "^3.0.0", + "string-width": "^4.2.3", + "strip-ansi": "^6.0.1", + "wide-align": "^1.1.2" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/gaxios": { + "version": "6.7.1", + "resolved": "https://registry.npmjs.org/gaxios/-/gaxios-6.7.1.tgz", + "integrity": "sha512-LDODD4TMYx7XXdpwxAVRAIAuB0bzv0s+ywFonY46k126qzQHT9ygyoa9tncmOiQmmDrik65UYsEkv3lbfqQ3yQ==", + "license": "Apache-2.0", + "dependencies": { + "extend": "^3.0.2", + "https-proxy-agent": "^7.0.1", + "is-stream": "^2.0.0", + "node-fetch": "^2.6.9", + "uuid": "^9.0.1" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/gaxios/node_modules/agent-base": { + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.1.tgz", + "integrity": "sha512-H0TSyFNDMomMNJQBn8wFV5YC/2eJ+VXECwOadZJT554xP6cODZHPX3H9QMQECxvrgiSOP1pHjy1sMWQVYJOUOA==", + "license": "MIT", + "dependencies": { + "debug": "^4.3.4" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/gaxios/node_modules/debug": { + "version": "4.3.7", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.7.tgz", + "integrity": "sha512-Er2nc/H7RrMXZBFCEim6TCmMk02Z8vLC2Rbi1KEBggpo0fS6l0S1nnapwmIi3yW/+GOJap1Krg4w0Hg80oCqgQ==", + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/gaxios/node_modules/https-proxy-agent": { + "version": "7.0.5", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.5.tgz", + "integrity": "sha512-1e4Wqeblerz+tMKPIq2EMGiiWW1dIjZOksyHWSUm1rmuvw/how9hBHZ38lAGj5ID4Ik6EdkOw7NmWPy6LAwalw==", + "license": "MIT", + "dependencies": { + "agent-base": "^7.0.2", + "debug": "4" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/gaxios/node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "license": "MIT" + }, + "node_modules/gaxios/node_modules/uuid": { + "version": "9.0.1", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-9.0.1.tgz", + "integrity": "sha512-b+1eJOlsR9K8HJpow9Ok3fiWOWSIcIzXodvv0rQjVoOVNpWMpxf1wZNpt4y9h10odCNrqnYp1OBzRktckBe3sA==", + "funding": [ + "https://github.com/sponsors/broofa", + "https://github.com/sponsors/ctavan" + ], + "license": "MIT", + "bin": { + "uuid": "dist/bin/uuid" + } + }, + "node_modules/gcp-metadata": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/gcp-metadata/-/gcp-metadata-5.3.0.tgz", + "integrity": "sha512-FNTkdNEnBdlqF2oatizolQqNANMrcqJt6AAYt99B3y1aLLC8Hc5IOBb+ZnnzllodEEf6xMBp6wRcBbc16fa65w==", + "license": "Apache-2.0", + "optional": true, + "peer": true, + "dependencies": { + "gaxios": "^5.0.0", + "json-bigint": "^1.0.0" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/gcp-metadata/node_modules/gaxios": { + "version": "5.1.3", + "resolved": "https://registry.npmjs.org/gaxios/-/gaxios-5.1.3.tgz", + "integrity": "sha512-95hVgBRgEIRQQQHIbnxBXeHbW4TqFk4ZDJW7wmVtvYar72FdhRIo1UGOLS2eRAKCPEdPBWu+M7+A33D9CdX9rA==", + "license": "Apache-2.0", + "optional": true, + "peer": true, + "dependencies": { + "extend": "^3.0.2", + "https-proxy-agent": "^5.0.0", + "is-stream": "^2.0.0", + "node-fetch": "^2.6.9" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/get-intrinsic": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.2.4.tgz", + "integrity": "sha512-5uYhsJH8VJBTv7oslg4BznJYhDoRI6waYCxMmCdnTrcCrHA/fCFKoTFz2JKKE0HdDFUF7/oQuhzumXJK7paBRQ==", + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2", + "has-proto": "^1.0.1", + "has-symbols": "^1.0.3", + "hasown": "^2.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/glob": { + "version": "7.2.3", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz", + "integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==", + "deprecated": "Glob versions prior to v9 are no longer supported", + "dependencies": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.1.1", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + }, + "engines": { + "node": "*" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/glob-parent": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz", + "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==", + "dev": true, + "dependencies": { + "is-glob": "^4.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/google-auth-library": { + "version": "9.14.2", + "resolved": "https://registry.npmjs.org/google-auth-library/-/google-auth-library-9.14.2.tgz", + "integrity": "sha512-R+FRIfk1GBo3RdlRYWPdwk8nmtVUOn6+BkDomAC46KoU8kzXzE1HLmOasSCbWUByMMAGkknVF0G5kQ69Vj7dlA==", + "license": "Apache-2.0", + "dependencies": { + "base64-js": "^1.3.0", + "ecdsa-sig-formatter": "^1.0.11", + "gaxios": "^6.1.1", + "gcp-metadata": "^6.1.0", + "gtoken": "^7.0.0", + "jws": "^4.0.0" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/google-auth-library/node_modules/gcp-metadata": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/gcp-metadata/-/gcp-metadata-6.1.0.tgz", + "integrity": "sha512-Jh/AIwwgaxan+7ZUUmRLCjtchyDiqh4KjBJ5tW3plBZb5iL/BPcso8A5DlzeD9qlw0duCamnNdpFjxwaT0KyKg==", + "license": "Apache-2.0", + "dependencies": { + "gaxios": "^6.0.0", + "json-bigint": "^1.0.0" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/google-auth-library/node_modules/jwa": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/jwa/-/jwa-2.0.0.tgz", + "integrity": "sha512-jrZ2Qx916EA+fq9cEAeCROWPTfCwi1IVHqT2tapuqLEVVDKFDENFw1oL+MwrTvH6msKxsd1YTDVw6uKEcsrLEA==", + "license": "MIT", + "dependencies": { + "buffer-equal-constant-time": "1.0.1", + "ecdsa-sig-formatter": "1.0.11", + "safe-buffer": "^5.0.1" + } + }, + "node_modules/google-auth-library/node_modules/jws": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/jws/-/jws-4.0.0.tgz", + "integrity": "sha512-KDncfTmOZoOMTFG4mBlG0qUIOlc03fmzH+ru6RgYVZhPkyiy/92Owlt/8UEN+a4TXR1FQetfIpJE8ApdvdVxTg==", + "license": "MIT", + "dependencies": { + "jwa": "^2.0.0", + "safe-buffer": "^5.0.1" + } + }, + "node_modules/gopd": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.0.1.tgz", + "integrity": "sha512-d65bNlIadxvpb/A2abVdlqKqV563juRnZ1Wtk6s1sIR8uNsXR70xqIzVqxVf1eTqDunwT2MkczEeaezCKTZhwA==", + "dependencies": { + "get-intrinsic": "^1.1.3" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/gtoken": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/gtoken/-/gtoken-7.1.0.tgz", + "integrity": "sha512-pCcEwRi+TKpMlxAQObHDQ56KawURgyAf6jtIY046fJ5tIv3zDe/LEIubckAO8fj6JnAxLdmWkUfNyulQ2iKdEw==", + "license": "MIT", + "dependencies": { + "gaxios": "^6.0.0", + "jws": "^4.0.0" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/gtoken/node_modules/jwa": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/jwa/-/jwa-2.0.0.tgz", + "integrity": "sha512-jrZ2Qx916EA+fq9cEAeCROWPTfCwi1IVHqT2tapuqLEVVDKFDENFw1oL+MwrTvH6msKxsd1YTDVw6uKEcsrLEA==", + "license": "MIT", + "dependencies": { + "buffer-equal-constant-time": "1.0.1", + "ecdsa-sig-formatter": "1.0.11", + "safe-buffer": "^5.0.1" + } + }, + "node_modules/gtoken/node_modules/jws": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/jws/-/jws-4.0.0.tgz", + "integrity": "sha512-KDncfTmOZoOMTFG4mBlG0qUIOlc03fmzH+ru6RgYVZhPkyiy/92Owlt/8UEN+a4TXR1FQetfIpJE8ApdvdVxTg==", + "license": "MIT", + "dependencies": { + "jwa": "^2.0.0", + "safe-buffer": "^5.0.1" + } + }, + "node_modules/has-flag": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", + "integrity": "sha512-sKJf1+ceQBr4SMkvQnBDNDtf4TXpVhVGateu0t918bl30FnbE2m4vNLX+VWe/dpjlb+HugGYzW7uQXH98HPEYw==", + "dev": true, + "engines": { + "node": ">=4" + } + }, + "node_modules/has-property-descriptors": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-property-descriptors/-/has-property-descriptors-1.0.2.tgz", + "integrity": "sha512-55JNKuIW+vq4Ke1BjOTjM2YctQIvCT7GFzHwmfZPGo5wnrgkid0YQtnAleFSqumZm4az3n2BS+erby5ipJdgrg==", + "dependencies": { + "es-define-property": "^1.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-proto": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/has-proto/-/has-proto-1.0.3.tgz", + "integrity": "sha512-SJ1amZAJUiZS+PhsVLf5tGydlaVB8EdFpaSO4gmiUKUOxk8qzn5AIy4ZeJUmh22znIdk/uMAUT2pl3FxzVUH+Q==", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-symbols": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.3.tgz", + "integrity": "sha512-l3LCuF6MgDNwTDKkdYGEihYjt5pRPbEg46rtlmnSPlUbgmB8LOIrKJbYYFBSbnPaJexMKtiPO8hmeRjRz2Td+A==", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-unicode": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/has-unicode/-/has-unicode-2.0.1.tgz", + "integrity": "sha512-8Rf9Y83NBReMnx0gFzA8JImQACstCYWUplepDa9xprwwtmgEZUF0h/i5xSA625zB/I37EtrswSST6OXxwaaIJQ==" + }, + "node_modules/hasown": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz", + "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/html-entities": { + "version": "2.5.2", + "resolved": "https://registry.npmjs.org/html-entities/-/html-entities-2.5.2.tgz", + "integrity": "sha512-K//PSRMQk4FZ78Kyau+mZurHn3FH0Vwr+H36eE0rPbeYkRRi9YxceYPhuN60UwWorxyKHhqoAJl2OFKa4BVtaA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/mdevils" + }, + { + "type": "patreon", + "url": "https://patreon.com/mdevils" + } + ], + "license": "MIT" + }, + "node_modules/http-errors": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.0.tgz", + "integrity": "sha512-FtwrG/euBzaEjYeRqOgly7G0qviiXoJWnvEH2Z1plBdXgbyjv34pHTSb9zoeHMyDy33+DWy5Wt9Wo+TURtOYSQ==", + "dependencies": { + "depd": "2.0.0", + "inherits": "2.0.4", + "setprototypeof": "1.2.0", + "statuses": "2.0.1", + "toidentifier": "1.0.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/http-proxy-agent": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-5.0.0.tgz", + "integrity": "sha512-n2hY8YdoRE1i7r6M0w9DIw5GgZN0G25P8zLCRQ8rjXtTU3vsNFBI/vWK/UIeE6g5MUUz6avwAPXmL6Fy9D/90w==", + "license": "MIT", + "dependencies": { + "@tootallnate/once": "2", + "agent-base": "6", + "debug": "4" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/http-proxy-agent/node_modules/debug": { + "version": "4.3.7", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.7.tgz", + "integrity": "sha512-Er2nc/H7RrMXZBFCEim6TCmMk02Z8vLC2Rbi1KEBggpo0fS6l0S1nnapwmIi3yW/+GOJap1Krg4w0Hg80oCqgQ==", + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/http-proxy-agent/node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "license": "MIT" + }, + "node_modules/https-proxy-agent": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-5.0.1.tgz", + "integrity": "sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA==", + "dependencies": { + "agent-base": "6", + "debug": "4" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/https-proxy-agent/node_modules/debug": { + "version": "4.3.6", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.6.tgz", + "integrity": "sha512-O/09Bd4Z1fBrU4VzkhFqVgpPzaGbw6Sm9FEkBT1A/YBXQFGuuSxa1dN2nxgxS34JmKXqYx8CZAwEVoJFImUXIg==", + "dependencies": { + "ms": "2.1.2" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/https-proxy-agent/node_modules/ms": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==" + }, + "node_modules/iconv-lite": { + "version": "0.4.24", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz", + "integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/ignore-by-default": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/ignore-by-default/-/ignore-by-default-1.0.1.tgz", + "integrity": "sha512-Ius2VYcGNk7T90CppJqcIkS5ooHUZyIQK+ClZfMfMNFEF9VSE73Fq+906u/CWu92x4gzZMWOwfFYckPObzdEbA==", + "dev": true + }, + "node_modules/inflight": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", + "integrity": "sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA==", + "deprecated": "This module is not supported, and leaks memory. Do not use it. Check out lru-cache if you want a good and tested way to coalesce async requests by a key value, which is much more comprehensive and powerful.", + "dependencies": { + "once": "^1.3.0", + "wrappy": "1" + } + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==" + }, + "node_modules/ipaddr.js": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz", + "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==", + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/is-binary-path": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/is-binary-path/-/is-binary-path-2.1.0.tgz", + "integrity": "sha512-ZMERYes6pDydyuGidse7OsHxtbI7WVeUEozgR/g7rd0xUimYNlvZRE/K2MgZTjWy725IfelLeVcEM97mmtRGXw==", + "dev": true, + "dependencies": { + "binary-extensions": "^2.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/is-extglob": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", + "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-fullwidth-code-point": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", + "engines": { + "node": ">=8" + } + }, + "node_modules/is-glob": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", + "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", + "dev": true, + "dependencies": { + "is-extglob": "^2.1.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-number": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", + "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", + "dev": true, + "engines": { + "node": ">=0.12.0" + } + }, + "node_modules/is-stream": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-2.0.1.tgz", + "integrity": "sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg==", + "license": "MIT", + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/isarray": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", + "integrity": "sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ==", + "license": "MIT" + }, + "node_modules/json-bigint": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/json-bigint/-/json-bigint-1.0.0.tgz", + "integrity": "sha512-SiPv/8VpZuWbvLSMtTDU8hEfrZWg/mH/nV/b4o0CYbSxu1UIQPLdwKOCIyLQX+VIPO5vrLX3i8qtqFyhdPSUSQ==", + "license": "MIT", + "dependencies": { + "bignumber.js": "^9.0.0" + } + }, + "node_modules/jsonwebtoken": { + "version": "9.0.2", + "resolved": "https://registry.npmjs.org/jsonwebtoken/-/jsonwebtoken-9.0.2.tgz", + "integrity": "sha512-PRp66vJ865SSqOlgqS8hujT5U4AOgMfhrwYIuIhfKaoSCZcirrmASQr8CX7cUg+RMih+hgznrjp99o+W4pJLHQ==", + "dependencies": { + "jws": "^3.2.2", + "lodash.includes": "^4.3.0", + "lodash.isboolean": "^3.0.3", + "lodash.isinteger": "^4.0.4", + "lodash.isnumber": "^3.0.3", + "lodash.isplainobject": "^4.0.6", + "lodash.isstring": "^4.0.1", + "lodash.once": "^4.0.0", + "ms": "^2.1.1", + "semver": "^7.5.4" + }, + "engines": { + "node": ">=12", + "npm": ">=6" + } + }, + "node_modules/jsonwebtoken/node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==" + }, + "node_modules/jwa": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/jwa/-/jwa-1.4.1.tgz", + "integrity": "sha512-qiLX/xhEEFKUAJ6FiBMbes3w9ATzyk5W7Hvzpa/SLYdxNtng+gcurvrI7TbACjIXlsJyr05/S1oUhZrc63evQA==", + "dependencies": { + "buffer-equal-constant-time": "1.0.1", + "ecdsa-sig-formatter": "1.0.11", + "safe-buffer": "^5.0.1" + } + }, + "node_modules/jws": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/jws/-/jws-3.2.2.tgz", + "integrity": "sha512-YHlZCB6lMTllWDtSPHz/ZXTsi8S00usEV6v1tjq8tOUZzw7DpSDWVXjXDre6ed1w/pd495ODpHZYSdkRTsa0HA==", + "dependencies": { + "jwa": "^1.4.1", + "safe-buffer": "^5.0.1" + } + }, + "node_modules/kareem": { + "version": "2.6.3", + "resolved": "https://registry.npmjs.org/kareem/-/kareem-2.6.3.tgz", + "integrity": "sha512-C3iHfuGUXK2u8/ipq9LfjFfXFxAZMQJJq7vLS45r3D9Y2xQ/m4S8zaR4zMLFWh9AsNPXmcFfUDhTEO8UIC/V6Q==", + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/lodash.includes": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/lodash.includes/-/lodash.includes-4.3.0.tgz", + "integrity": "sha512-W3Bx6mdkRTGtlJISOvVD/lbqjTlPPUDTMnlXZFnVwi9NKJ6tiAk6LVdlhZMm17VZisqhKcgzpO5Wz91PCt5b0w==" + }, + "node_modules/lodash.isboolean": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/lodash.isboolean/-/lodash.isboolean-3.0.3.tgz", + "integrity": "sha512-Bz5mupy2SVbPHURB98VAcw+aHh4vRV5IPNhILUCsOzRmsTmSQ17jIuqopAentWoehktxGd9e/hbIXq980/1QJg==" + }, + "node_modules/lodash.isinteger": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/lodash.isinteger/-/lodash.isinteger-4.0.4.tgz", + "integrity": "sha512-DBwtEWN2caHQ9/imiNeEA5ys1JoRtRfY3d7V9wkqtbycnAmTvRRmbHKDV4a0EYc678/dia0jrte4tjYwVBaZUA==" + }, + "node_modules/lodash.isnumber": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/lodash.isnumber/-/lodash.isnumber-3.0.3.tgz", + "integrity": "sha512-QYqzpfwO3/CWf3XP+Z+tkQsfaLL/EnUlXWVkIk5FUPc4sBdTehEqZONuyRt2P67PXAk+NXmTBcc97zw9t1FQrw==" + }, + "node_modules/lodash.isplainobject": { + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/lodash.isplainobject/-/lodash.isplainobject-4.0.6.tgz", + "integrity": "sha512-oSXzaWypCMHkPC3NvBEaPHf0KsA5mvPrOPgQWDsbg8n7orZ290M0BmC/jgRZ4vcJ6DTAhjrsSYgdsW/F+MFOBA==" + }, + "node_modules/lodash.isstring": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/lodash.isstring/-/lodash.isstring-4.0.1.tgz", + "integrity": "sha512-0wJxfxH1wgO3GrbuP+dTTk7op+6L41QCXbGINEmD+ny/G/eCqGzxyCsh7159S+mgDDcoarnBw6PC1PS5+wUGgw==" + }, + "node_modules/lodash.once": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/lodash.once/-/lodash.once-4.1.1.tgz", + "integrity": "sha512-Sb487aTOCr9drQVL8pIxOzVhafOjZN9UU54hiN8PU3uAiSV7lx1yYNpbNmex2PK6dSJoNTSJUUswT651yww3Mg==" + }, + "node_modules/make-dir": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-3.1.0.tgz", + "integrity": "sha512-g3FeP20LNwhALb/6Cz6Dd4F2ngze0jz7tbzrD2wAV+o9FeNHe4rL+yK2md0J/fiSf1sa1ADhXqi5+oVwOM/eGw==", + "dependencies": { + "semver": "^6.0.0" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/make-dir/node_modules/semver": { + "version": "6.3.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", + "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", + "bin": { + "semver": "bin/semver.js" + } + }, + "node_modules/media-typer": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz", + "integrity": "sha512-dq+qelQ9akHpcOl/gUVRTxVIOkAJ1wR3QAvb4RsVjS8oVoFjDGTc679wJYmUmknUF5HwMLOgb5O+a3KxfWapPQ==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/memory-pager": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/memory-pager/-/memory-pager-1.5.0.tgz", + "integrity": "sha512-ZS4Bp4r/Zoeq6+NLJpP+0Zzm0pR8whtGPf1XExKLJBAczGMnSi3It14OiNCStjQjM6NU1okjQGSxgEZN8eBYKg==" + }, + "node_modules/merge-descriptors": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.1.tgz", + "integrity": "sha512-cCi6g3/Zr1iqQi6ySbseM1Xvooa98N0w31jzUYrXPX2xqObmFGHJ0tQ5u74H3mVh7wLouTseZyYIq39g8cNp1w==" + }, + "node_modules/methods": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/methods/-/methods-1.1.2.tgz", + "integrity": "sha512-iclAHeNqNm68zFtnZ0e+1L2yUIdvzNoauKU4WBA3VvH/vPFieF7qfRlwUZU+DA9P9bPXIS90ulxoUoCH23sV2w==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/mime/-/mime-1.6.0.tgz", + "integrity": "sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg==", + "bin": { + "mime": "cli.js" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/mime-db": { + "version": "1.52.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", + "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "2.1.35", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", + "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", + "dependencies": { + "mime-db": "1.52.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/minimatch": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", + "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, + "node_modules/minimist": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz", + "integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/minipass": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/minipass/-/minipass-5.0.0.tgz", + "integrity": "sha512-3FnjYuehv9k6ovOEbyOswadCDPX1piCfhV8ncmYtHOjuPwylVWsghTLo7rabjC3Rx5xD4HDx8Wm1xnMF7S5qFQ==", + "engines": { + "node": ">=8" + } + }, + "node_modules/minizlib": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/minizlib/-/minizlib-2.1.2.tgz", + "integrity": "sha512-bAxsR8BVfj60DWXHE3u30oHzfl4G7khkSuPW+qvpd7jFRHm7dLxOjUk1EHACJ/hxLY8phGJ0YhYHZo7jil7Qdg==", + "dependencies": { + "minipass": "^3.0.0", + "yallist": "^4.0.0" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/minizlib/node_modules/minipass": { + "version": "3.3.6", + "resolved": "https://registry.npmjs.org/minipass/-/minipass-3.3.6.tgz", + "integrity": "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw==", + "dependencies": { + "yallist": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/mkdirp": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-1.0.4.tgz", + "integrity": "sha512-vVqVZQyf3WLx2Shd0qJ9xuvqgAyKPLAiqITEtqW0oIUjzo3PePDd6fW9iFz30ef7Ysp/oiWqbhszeGWW2T6Gzw==", + "bin": { + "mkdirp": "bin/cmd.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/mongodb": { + "version": "6.7.0", + "resolved": "https://registry.npmjs.org/mongodb/-/mongodb-6.7.0.tgz", + "integrity": "sha512-TMKyHdtMcO0fYBNORiYdmM25ijsHs+Njs963r4Tro4OQZzqYigAzYQouwWRg4OIaiLRUEGUh/1UAcH5lxdSLIA==", + "dependencies": { + "@mongodb-js/saslprep": "^1.1.5", + "bson": "^6.7.0", + "mongodb-connection-string-url": "^3.0.0" + }, + "engines": { + "node": ">=16.20.1" + }, + "peerDependencies": { + "@aws-sdk/credential-providers": "^3.188.0", + "@mongodb-js/zstd": "^1.1.0", + "gcp-metadata": "^5.2.0", + "kerberos": "^2.0.1", + "mongodb-client-encryption": ">=6.0.0 <7", + "snappy": "^7.2.2", + "socks": "^2.7.1" + }, + "peerDependenciesMeta": { + "@aws-sdk/credential-providers": { + "optional": true + }, + "@mongodb-js/zstd": { + "optional": true + }, + "gcp-metadata": { + "optional": true + }, + "kerberos": { + "optional": true + }, + "mongodb-client-encryption": { + "optional": true + }, + "snappy": { + "optional": true + }, + "socks": { + "optional": true + } + } + }, + "node_modules/mongodb-connection-string-url": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/mongodb-connection-string-url/-/mongodb-connection-string-url-3.0.1.tgz", + "integrity": "sha512-XqMGwRX0Lgn05TDB4PyG2h2kKO/FfWJyCzYQbIhXUxz7ETt0I/FqHjUeqj37irJ+Dl1ZtU82uYyj14u2XsZKfg==", + "dependencies": { + "@types/whatwg-url": "^11.0.2", + "whatwg-url": "^13.0.0" + } + }, + "node_modules/mongoose": { + "version": "8.5.4", + "resolved": "https://registry.npmjs.org/mongoose/-/mongoose-8.5.4.tgz", + "integrity": "sha512-nG3eehhWf9l1q80WuHvp5DV+4xDNFpDWLE5ZgcFD5tslUV2USJ56ogun8gaZ62MKAocJnoStjAdno08b8U57hg==", + "dependencies": { + "bson": "^6.7.0", + "kareem": "2.6.3", + "mongodb": "6.7.0", + "mpath": "0.9.0", + "mquery": "5.0.0", + "ms": "2.1.3", + "sift": "17.1.3" + }, + "engines": { + "node": ">=16.20.1" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/mongoose" + } + }, + "node_modules/mongoose/node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==" + }, + "node_modules/mpath": { + "version": "0.9.0", + "resolved": "https://registry.npmjs.org/mpath/-/mpath-0.9.0.tgz", + "integrity": "sha512-ikJRQTk8hw5DEoFVxHG1Gn9T/xcjtdnOKIU1JTmGjZZlg9LST2mBLmcX3/ICIbgJydT2GOc15RnNy5mHmzfSew==", + "engines": { + "node": ">=4.0.0" + } + }, + "node_modules/mquery": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/mquery/-/mquery-5.0.0.tgz", + "integrity": "sha512-iQMncpmEK8R8ncT8HJGsGc9Dsp8xcgYMVSbs5jgnm1lFHTZqMJTUWTDx1LBO8+mK3tPNZWFLBghQEIOULSTHZg==", + "dependencies": { + "debug": "4.x" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/mquery/node_modules/debug": { + "version": "4.3.6", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.6.tgz", + "integrity": "sha512-O/09Bd4Z1fBrU4VzkhFqVgpPzaGbw6Sm9FEkBT1A/YBXQFGuuSxa1dN2nxgxS34JmKXqYx8CZAwEVoJFImUXIg==", + "dependencies": { + "ms": "2.1.2" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/mquery/node_modules/ms": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==" + }, + "node_modules/ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==" + }, + "node_modules/multer": { + "version": "1.4.5-lts.1", + "resolved": "https://registry.npmjs.org/multer/-/multer-1.4.5-lts.1.tgz", + "integrity": "sha512-ywPWvcDMeH+z9gQq5qYHCCy+ethsk4goepZ45GLD63fOu0YcNecQxi64nDs3qluZB+murG3/D4dJ7+dGctcCQQ==", + "license": "MIT", + "dependencies": { + "append-field": "^1.0.0", + "busboy": "^1.0.0", + "concat-stream": "^1.5.2", + "mkdirp": "^0.5.4", + "object-assign": "^4.1.1", + "type-is": "^1.6.4", + "xtend": "^4.0.0" + }, + "engines": { + "node": ">= 6.0.0" + } + }, + "node_modules/multer/node_modules/mkdirp": { + "version": "0.5.6", + "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.6.tgz", + "integrity": "sha512-FP+p8RB8OWpF3YZBCrP5gtADmtXApB5AMLn+vdyA+PyxCjrCs00mjyUozssO33cwDeT3wNGdLxJ5M//YqtHAJw==", + "license": "MIT", + "dependencies": { + "minimist": "^1.2.6" + }, + "bin": { + "mkdirp": "bin/cmd.js" + } + }, + "node_modules/negotiator": { + "version": "0.6.3", + "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.3.tgz", + "integrity": "sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/node-addon-api": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-5.1.0.tgz", + "integrity": "sha512-eh0GgfEkpnoWDq+VY8OyvYhFEzBk6jIYbRKdIlyTiAXIVJ8PyBaKb0rp7oDtoddbdoHWhq8wwr+XZ81F1rpNdA==" + }, + "node_modules/node-fetch": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.7.0.tgz", + "integrity": "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==", + "dependencies": { + "whatwg-url": "^5.0.0" + }, + "engines": { + "node": "4.x || >=6.0.0" + }, + "peerDependencies": { + "encoding": "^0.1.0" + }, + "peerDependenciesMeta": { + "encoding": { + "optional": true + } + } + }, + "node_modules/node-fetch/node_modules/tr46": { + "version": "0.0.3", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz", + "integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==" + }, + "node_modules/node-fetch/node_modules/webidl-conversions": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz", + "integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==" + }, + "node_modules/node-fetch/node_modules/whatwg-url": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz", + "integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==", + "dependencies": { + "tr46": "~0.0.3", + "webidl-conversions": "^3.0.0" + } + }, + "node_modules/nodemailer": { + "version": "6.9.16", + "resolved": "https://registry.npmjs.org/nodemailer/-/nodemailer-6.9.16.tgz", + "integrity": "sha512-psAuZdTIRN08HKVd/E8ObdV6NO7NTBY3KsC30F7M4H1OnmLCUNaS56FpYxyb26zWLSyYF9Ozch9KYHhHegsiOQ==", + "license": "MIT-0", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/nodemon": { + "version": "3.1.4", + "resolved": "https://registry.npmjs.org/nodemon/-/nodemon-3.1.4.tgz", + "integrity": "sha512-wjPBbFhtpJwmIeY2yP7QF+UKzPfltVGtfce1g/bB15/8vCGZj8uxD62b/b9M9/WVgme0NZudpownKN+c0plXlQ==", + "dev": true, + "dependencies": { + "chokidar": "^3.5.2", + "debug": "^4", + "ignore-by-default": "^1.0.1", + "minimatch": "^3.1.2", + "pstree.remy": "^1.1.8", + "semver": "^7.5.3", + "simple-update-notifier": "^2.0.0", + "supports-color": "^5.5.0", + "touch": "^3.1.0", + "undefsafe": "^2.0.5" + }, + "bin": { + "nodemon": "bin/nodemon.js" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/nodemon" + } + }, + "node_modules/nodemon/node_modules/debug": { + "version": "4.3.6", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.6.tgz", + "integrity": "sha512-O/09Bd4Z1fBrU4VzkhFqVgpPzaGbw6Sm9FEkBT1A/YBXQFGuuSxa1dN2nxgxS34JmKXqYx8CZAwEVoJFImUXIg==", + "dev": true, + "dependencies": { + "ms": "2.1.2" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/nodemon/node_modules/ms": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==", + "dev": true + }, + "node_modules/nopt": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/nopt/-/nopt-5.0.0.tgz", + "integrity": "sha512-Tbj67rffqceeLpcRXrT7vKAN8CwfPeIBgM7E6iBkmKLV7bEMwpGgYLGv0jACUsECaa/vuxP0IjEont6umdMgtQ==", + "dependencies": { + "abbrev": "1" + }, + "bin": { + "nopt": "bin/nopt.js" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/normalize-path": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz", + "integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/npmlog": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/npmlog/-/npmlog-5.0.1.tgz", + "integrity": "sha512-AqZtDUWOMKs1G/8lwylVjrdYgqA4d9nu8hc+0gzRxlDb1I10+FHBGMXs6aiQHFdCUUlqH99MUMuLfzWDNDtfxw==", + "deprecated": "This package is no longer supported.", + "dependencies": { + "are-we-there-yet": "^2.0.0", + "console-control-strings": "^1.1.0", + "gauge": "^3.0.0", + "set-blocking": "^2.0.0" + } + }, + "node_modules/object-assign": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", + "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/object-inspect": { + "version": "1.13.2", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.2.tgz", + "integrity": "sha512-IRZSRuzJiynemAXPYtPe5BoI/RESNYR7TYm50MC5Mqbd3Jmw5y790sErYw3V6SryFJD64b74qQQs9wn5Bg/k3g==", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/on-finished": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz", + "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==", + "dependencies": { + "ee-first": "1.1.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", + "dependencies": { + "wrappy": "1" + } + }, + "node_modules/p-limit": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz", + "integrity": "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==", + "license": "MIT", + "dependencies": { + "yocto-queue": "^0.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/parseurl": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", + "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/path-is-absolute": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", + "integrity": "sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/path-to-regexp": { + "version": "0.1.7", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.7.tgz", + "integrity": "sha512-5DFkuoqlv1uYQKxy8omFBeJPQcdoE07Kv2sferDCrAq1ohOU+MSDswDIbnx3YAM60qIOnYa53wBhXW0EbMonrQ==" + }, + "node_modules/picomatch": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz", + "integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==", + "dev": true, + "engines": { + "node": ">=8.6" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/process-nextick-args": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.1.tgz", + "integrity": "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag==", + "license": "MIT" + }, + "node_modules/proxy-addr": { + "version": "2.0.7", + "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz", + "integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==", + "dependencies": { + "forwarded": "0.2.0", + "ipaddr.js": "1.9.1" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/pstree.remy": { + "version": "1.1.8", + "resolved": "https://registry.npmjs.org/pstree.remy/-/pstree.remy-1.1.8.tgz", + "integrity": "sha512-77DZwxQmxKnu3aR542U+X8FypNzbfJ+C5XQDk3uWjWxn6151aIMGthWYRXTqT1E5oJvg+ljaa2OJi+VfvCOQ8w==", + "dev": true + }, + "node_modules/punycode": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", + "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==", + "engines": { + "node": ">=6" + } + }, + "node_modules/qs": { + "version": "6.11.0", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.11.0.tgz", + "integrity": "sha512-MvjoMCJwEarSbUYk5O+nmoSzSutSsTwF85zcHPQ9OrlFoZOYIjaqBAJIqIXjptyD5vThxGq52Xu/MaJzRkIk4Q==", + "dependencies": { + "side-channel": "^1.0.4" + }, + "engines": { + "node": ">=0.6" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/range-parser": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz", + "integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/raw-body": { + "version": "2.5.2", + "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.5.2.tgz", + "integrity": "sha512-8zGqypfENjCIqGhgXToC8aB2r7YrBX+AQAfIPs/Mlk+BtPTztOvTS01NRW/3Eh60J+a48lt8qsCzirQ6loCVfA==", + "dependencies": { + "bytes": "3.1.2", + "http-errors": "2.0.0", + "iconv-lite": "0.4.24", + "unpipe": "1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/readable-stream": { + "version": "3.6.2", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", + "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", + "dependencies": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/readdirp": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.6.0.tgz", + "integrity": "sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==", + "dev": true, + "dependencies": { + "picomatch": "^2.2.1" + }, + "engines": { + "node": ">=8.10.0" + } + }, + "node_modules/retry": { + "version": "0.13.1", + "resolved": "https://registry.npmjs.org/retry/-/retry-0.13.1.tgz", + "integrity": "sha512-XQBQ3I8W1Cge0Seh+6gjj03LbmRFWuoszgK9ooCpwYIrhhoO80pfq4cUkU5DkknwfOfFteRwlZ56PYOGYyFWdg==", + "license": "MIT", + "engines": { + "node": ">= 4" + } + }, + "node_modules/retry-request": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/retry-request/-/retry-request-7.0.2.tgz", + "integrity": "sha512-dUOvLMJ0/JJYEn8NrpOaGNE7X3vpI5XlZS/u0ANjqtcZVKnIxP7IgCFwrKTxENw29emmwug53awKtaMm4i9g5w==", + "license": "MIT", + "dependencies": { + "@types/request": "^2.48.8", + "extend": "^3.0.2", + "teeny-request": "^9.0.0" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/rimraf": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-3.0.2.tgz", + "integrity": "sha512-JZkJMZkAGFFPP2YqXZXPbMlMBgsxzE8ILs4lMIX/2o0L9UBw9O/Y3o6wFw/i9YLapcUJWwqbi3kdxIPdC62TIA==", + "deprecated": "Rimraf versions prior to v4 are no longer supported", + "dependencies": { + "glob": "^7.1.3" + }, + "bin": { + "rimraf": "bin.js" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] + }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==" + }, + "node_modules/semver": { + "version": "7.6.3", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.6.3.tgz", + "integrity": "sha512-oVekP1cKtI+CTDvHWYFUcMtsK/00wmAEfyqKfNdARm8u1wNVhSgaX7A8d4UuIlUI5e84iEwOhs7ZPYRmzU9U6A==", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/send": { + "version": "0.18.0", + "resolved": "https://registry.npmjs.org/send/-/send-0.18.0.tgz", + "integrity": "sha512-qqWzuOjSFOuqPjFe4NOsMLafToQQwBSOEpS+FwEt3A2V3vKubTquT3vmLTQpFgMXp8AlFWFuP1qKaJZOtPpVXg==", + "dependencies": { + "debug": "2.6.9", + "depd": "2.0.0", + "destroy": "1.2.0", + "encodeurl": "~1.0.2", + "escape-html": "~1.0.3", + "etag": "~1.8.1", + "fresh": "0.5.2", + "http-errors": "2.0.0", + "mime": "1.6.0", + "ms": "2.1.3", + "on-finished": "2.4.1", + "range-parser": "~1.2.1", + "statuses": "2.0.1" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/send/node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==" + }, + "node_modules/serve-static": { + "version": "1.15.0", + "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.15.0.tgz", + "integrity": "sha512-XGuRDNjXUijsUL0vl6nSD7cwURuzEgglbOaFuZM9g3kwDXOWVTck0jLzjPzGD+TazWbboZYu52/9/XPdUgne9g==", + "dependencies": { + "encodeurl": "~1.0.2", + "escape-html": "~1.0.3", + "parseurl": "~1.3.3", + "send": "0.18.0" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/set-blocking": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/set-blocking/-/set-blocking-2.0.0.tgz", + "integrity": "sha512-KiKBS8AnWGEyLzofFfmvKwpdPzqiy16LvQfK3yv/fVH7Bj13/wl3JSR1J+rfgRE9q7xUJK4qvgS8raSOeLUehw==" + }, + "node_modules/set-function-length": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/set-function-length/-/set-function-length-1.2.2.tgz", + "integrity": "sha512-pgRc4hJ4/sNjWCSS9AmnS40x3bNMDTknHgL5UaMBTMyJnU90EgWh1Rz+MC9eFu4BuN/UwZjKQuY/1v3rM7HMfg==", + "dependencies": { + "define-data-property": "^1.1.4", + "es-errors": "^1.3.0", + "function-bind": "^1.1.2", + "get-intrinsic": "^1.2.4", + "gopd": "^1.0.1", + "has-property-descriptors": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/setprototypeof": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", + "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==" + }, + "node_modules/side-channel": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.0.6.tgz", + "integrity": "sha512-fDW/EZ6Q9RiO8eFG8Hj+7u/oW+XrPTIChwCOM2+th2A6OblDtYYIpve9m+KvI9Z4C9qSEXlaGR6bTEYHReuglA==", + "dependencies": { + "call-bind": "^1.0.7", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.4", + "object-inspect": "^1.13.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/sift": { + "version": "17.1.3", + "resolved": "https://registry.npmjs.org/sift/-/sift-17.1.3.tgz", + "integrity": "sha512-Rtlj66/b0ICeFzYTuNvX/EF1igRbbnGSvEyT79McoZa/DeGhMyC5pWKOEsZKnpkqtSeovd5FL/bjHWC3CIIvCQ==" + }, + "node_modules/signal-exit": { + "version": "3.0.7", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz", + "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==" + }, + "node_modules/simple-update-notifier": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/simple-update-notifier/-/simple-update-notifier-2.0.0.tgz", + "integrity": "sha512-a2B9Y0KlNXl9u/vsW6sTIu9vGEpfKu2wRV6l1H3XEas/0gUIzGzBoP/IouTcUQbm9JWZLH3COxyn03TYlFax6w==", + "dev": true, + "dependencies": { + "semver": "^7.5.3" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/sparse-bitfield": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/sparse-bitfield/-/sparse-bitfield-3.0.3.tgz", + "integrity": "sha512-kvzhi7vqKTfkh0PZU+2D2PIllw2ymqJKujUcyPMd9Y75Nv4nPbGJZXNhxsgdQab2BmlDct1YnfQCguEvHr7VsQ==", + "dependencies": { + "memory-pager": "^1.0.2" + } + }, + "node_modules/statuses": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.1.tgz", + "integrity": "sha512-RwNA9Z/7PrK06rYLIzFMlaF+l73iwpzsqRIFgbMLbTcLD6cOao82TaWefPXQvB2fOC4AjuYSEndS7N/mTCbkdQ==", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/stream-events": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/stream-events/-/stream-events-1.0.5.tgz", + "integrity": "sha512-E1GUzBSgvct8Jsb3v2X15pjzN1tYebtbLaMg+eBOUOAxgbLoSbT2NS91ckc5lJD1KfLjId+jXJRgo0qnV5Nerg==", + "license": "MIT", + "dependencies": { + "stubs": "^3.0.0" + } + }, + "node_modules/stream-shift": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/stream-shift/-/stream-shift-1.0.3.tgz", + "integrity": "sha512-76ORR0DO1o1hlKwTbi/DM3EXWGf3ZJYO8cXX5RJwnul2DEg2oyoZyjLNoQM8WsvZiFKCRfC1O0J7iCvie3RZmQ==", + "license": "MIT" + }, + "node_modules/streamsearch": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/streamsearch/-/streamsearch-1.1.0.tgz", + "integrity": "sha512-Mcc5wHehp9aXz1ax6bZUyY5afg9u2rv5cqQI3mRrYkGC8rW2hM02jWuwjtL++LS5qinSyhj2QfLyNsuc+VsExg==", + "engines": { + "node": ">=10.0.0" + } + }, + "node_modules/string_decoder": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", + "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==", + "dependencies": { + "safe-buffer": "~5.2.0" + } + }, + "node_modules/string-width": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/strnum": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/strnum/-/strnum-1.0.5.tgz", + "integrity": "sha512-J8bbNyKKXl5qYcR36TIO8W3mVGVHrmmxsd5PAItGkmyzwJvybiw2IVq5nqd0i4LSNSkB/sx9VHllbfFdr9k1JA==", + "license": "MIT" + }, + "node_modules/stubs": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/stubs/-/stubs-3.0.0.tgz", + "integrity": "sha512-PdHt7hHUJKxvTCgbKX9C1V/ftOcjJQgz8BZwNfV5c4B6dcGqlpelTbJ999jBGZ2jYiPAwcX5dP6oBwVlBlUbxw==", + "license": "MIT" + }, + "node_modules/supports-color": { + "version": "5.5.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", + "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", + "dev": true, + "dependencies": { + "has-flag": "^3.0.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/tar": { + "version": "6.2.1", + "resolved": "https://registry.npmjs.org/tar/-/tar-6.2.1.tgz", + "integrity": "sha512-DZ4yORTwrbTj/7MZYq2w+/ZFdI6OZ/f9SFHR+71gIVUZhOQPHzVCLpvRnPgyaMpfWxxk/4ONva3GQSyNIKRv6A==", + "dependencies": { + "chownr": "^2.0.0", + "fs-minipass": "^2.0.0", + "minipass": "^5.0.0", + "minizlib": "^2.1.1", + "mkdirp": "^1.0.3", + "yallist": "^4.0.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/teeny-request": { + "version": "9.0.0", + "resolved": "https://registry.npmjs.org/teeny-request/-/teeny-request-9.0.0.tgz", + "integrity": "sha512-resvxdc6Mgb7YEThw6G6bExlXKkv6+YbuzGg9xuXxSgxJF7Ozs+o8Y9+2R3sArdWdW8nOokoQb1yrpFB0pQK2g==", + "license": "Apache-2.0", + "dependencies": { + "http-proxy-agent": "^5.0.0", + "https-proxy-agent": "^5.0.0", + "node-fetch": "^2.6.9", + "stream-events": "^1.0.5", + "uuid": "^9.0.0" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/teeny-request/node_modules/uuid": { + "version": "9.0.1", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-9.0.1.tgz", + "integrity": "sha512-b+1eJOlsR9K8HJpow9Ok3fiWOWSIcIzXodvv0rQjVoOVNpWMpxf1wZNpt4y9h10odCNrqnYp1OBzRktckBe3sA==", + "funding": [ + "https://github.com/sponsors/broofa", + "https://github.com/sponsors/ctavan" + ], + "license": "MIT", + "bin": { + "uuid": "dist/bin/uuid" + } + }, + "node_modules/to-regex-range": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", + "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", + "dev": true, + "dependencies": { + "is-number": "^7.0.0" + }, + "engines": { + "node": ">=8.0" + } + }, + "node_modules/toidentifier": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz", + "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==", + "engines": { + "node": ">=0.6" + } + }, + "node_modules/touch": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/touch/-/touch-3.1.1.tgz", + "integrity": "sha512-r0eojU4bI8MnHr8c5bNo7lJDdI2qXlWWJk6a9EAFG7vbhTjElYhBVS3/miuE0uOuoLdb8Mc/rVfsmm6eo5o9GA==", + "dev": true, + "bin": { + "nodetouch": "bin/nodetouch.js" + } + }, + "node_modules/tr46": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-4.1.1.tgz", + "integrity": "sha512-2lv/66T7e5yNyhAAC4NaKe5nVavzuGJQVVtRYLyQ2OI8tsJ61PMLlelehb0wi2Hx6+hT/OJUWZcw8MjlSRnxvw==", + "dependencies": { + "punycode": "^2.3.0" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/type-is": { + "version": "1.6.18", + "resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz", + "integrity": "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==", + "dependencies": { + "media-typer": "0.3.0", + "mime-types": "~2.1.24" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/typedarray": { + "version": "0.0.6", + "resolved": "https://registry.npmjs.org/typedarray/-/typedarray-0.0.6.tgz", + "integrity": "sha512-/aCDEGatGvZ2BIk+HmLf4ifCJFwvKFNb9/JeZPMulfgFracn9QFcAf5GO8B/mweUjSoblS5In0cWhqpfs/5PQA==", + "license": "MIT" + }, + "node_modules/undefsafe": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/undefsafe/-/undefsafe-2.0.5.tgz", + "integrity": "sha512-WxONCrssBM8TSPRqN5EmsjVrsv4A8X12J4ArBiiayv3DyyG3ZlIg6yysuuSYdZsVz3TKcTg2fd//Ujd4CHV1iA==", + "dev": true + }, + "node_modules/undici-types": { + "version": "6.19.8", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.19.8.tgz", + "integrity": "sha512-ve2KP6f/JnbPBFyobGHuerC9g1FYGn/F8n1LWTwNxCEzd6IfqTwUQcNXgEtmmQ6DlRrC1hrSrBnCZPokRrDHjw==", + "license": "MIT" + }, + "node_modules/unpipe": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", + "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/util-deprecate": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", + "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==" + }, + "node_modules/utils-merge": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz", + "integrity": "sha512-pMZTvIkT1d+TFGvDOqodOclx0QWkkgi6Tdoa8gC8ffGAAqz9pzPTZWAybbsHHoED/ztMtkv/VoYTYyShUn81hA==", + "engines": { + "node": ">= 0.4.0" + } + }, + "node_modules/uuid": { + "version": "8.3.2", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-8.3.2.tgz", + "integrity": "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg==", + "license": "MIT", + "bin": { + "uuid": "dist/bin/uuid" + } + }, + "node_modules/vary": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", + "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/webidl-conversions": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-7.0.0.tgz", + "integrity": "sha512-VwddBukDzu71offAQR975unBIGqfKZpM+8ZX6ySk8nYhVoo5CYaZyzt3YBvYtRtO+aoGlqxPg/B87NGVZ/fu6g==", + "engines": { + "node": ">=12" + } + }, + "node_modules/whatwg-url": { + "version": "13.0.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-13.0.0.tgz", + "integrity": "sha512-9WWbymnqj57+XEuqADHrCJ2eSXzn8WXIW/YSGaZtb2WKAInQ6CHfaUUcTyyver0p8BDg5StLQq8h1vtZuwmOig==", + "dependencies": { + "tr46": "^4.1.1", + "webidl-conversions": "^7.0.0" + }, + "engines": { + "node": ">=16" + } + }, + "node_modules/wide-align": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/wide-align/-/wide-align-1.1.5.tgz", + "integrity": "sha512-eDMORYaPNZ4sQIuuYPDHdQvf4gyCF9rEEV/yPxGfwPkRodwEgiMUUXTx/dex+Me0wxx53S+NgUHaP7y3MGlDmg==", + "dependencies": { + "string-width": "^1.0.2 || 2 || 3 || 4" + } + }, + "node_modules/wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==" + }, + "node_modules/xtend": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz", + "integrity": "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==", + "license": "MIT", + "engines": { + "node": ">=0.4" + } + }, + "node_modules/yallist": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", + "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==" + }, + "node_modules/yocto-queue": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz", + "integrity": "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==", + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + } + } +} diff --git a/backend/user/package.json b/backend/user/package.json new file mode 100644 index 0000000000..52371f5071 --- /dev/null +++ b/backend/user/package.json @@ -0,0 +1,31 @@ +{ + "name": "user-service", + "version": "1.0.0", + "description": "", + "main": "index.js", + "type": "module", + "scripts": { + "dev": "nodemon server.js", + "start": "node server.js", + "test": "echo \"Error: no test specified\" && exit 1" + }, + "keywords": [], + "author": "", + "license": "ISC", + "devDependencies": { + "@types/bcryptjs": "^2.4.6", + "nodemon": "^3.1.4" + }, + "dependencies": { + "@google-cloud/storage": "^7.14.0", + "bcrypt": "^5.1.1", + "bcryptjs": "^2.4.3", + "cors": "^2.8.5", + "dotenv": "^16.4.5", + "express": "^4.19.2", + "jsonwebtoken": "^9.0.2", + "mongoose": "^8.5.4", + "multer": "^1.4.5-lts.1", + "nodemailer": "^6.9.16" + } +} \ No newline at end of file diff --git a/backend/user/routes/auth-routes.js b/backend/user/routes/auth-routes.js new file mode 100644 index 0000000000..8690cbe1f6 --- /dev/null +++ b/backend/user/routes/auth-routes.js @@ -0,0 +1,12 @@ +import express from "express"; + +import { handleLogin, handleVerifyToken } from "../controller/auth-controller.js"; +import { verifyAccessToken } from "../middleware/basic-access-control.js"; + +const router = express.Router(); + +router.post("/login", handleLogin); + +router.get("/verify-token", verifyAccessToken, handleVerifyToken); + +export default router; diff --git a/backend/user/routes/user-routes.js b/backend/user/routes/user-routes.js new file mode 100644 index 0000000000..00c4a42919 --- /dev/null +++ b/backend/user/routes/user-routes.js @@ -0,0 +1,54 @@ +import express from "express"; + +import { + checkPasswordResetCode, + createUser, + deleteUser, + getAllUsers, + getUser, + requestPasswordReset, + resetPasswordUsingCode, + updateUser, + updateUserPrivilege, + getFileUrl, + verifyUser, + resetPasswordFromProfile, +} from "../controller/user-controller.js"; +import { + verifyAccessToken, + verifyIsAdmin, + verifyIsOwnerOrAdmin, +} from "../middleware/basic-access-control.js"; + +const router = express.Router(); + +router.get("/", verifyAccessToken, verifyIsAdmin, getAllUsers); + +router.patch( + "/:id/privilege", + verifyAccessToken, + verifyIsAdmin, + updateUserPrivilege +); + +router.get("/verify", verifyUser); + +router.post("/:id/reset-password-from-profile", resetPasswordFromProfile); + +router.post("/request-password-reset", requestPasswordReset); + +router.post("/check-password-reset-code", checkPasswordResetCode); + +router.post("/password-reset", resetPasswordUsingCode); + +router.post("/", createUser); + +router.post("/:id/getFileUrl", getFileUrl); + +router.get("/:id", verifyAccessToken, getUser); + +router.patch("/:id", verifyAccessToken, verifyIsOwnerOrAdmin, updateUser); + +router.delete("/:id", verifyAccessToken, verifyIsOwnerOrAdmin, deleteUser); + +export default router; diff --git a/backend/user/server.js b/backend/user/server.js new file mode 100644 index 0000000000..910f1db7fd --- /dev/null +++ b/backend/user/server.js @@ -0,0 +1,20 @@ +import http from "http"; +import index from "./index.js"; +import "dotenv/config"; +import { connectToDB } from "./model/repository.js"; + +const port = process.env.PORT || 3001; + +const server = http.createServer(index); + +await connectToDB() + .then(() => { + console.log("MongoDB Connected!"); + + server.listen(port); + console.log("IAM service server listening on http://localhost:" + port); + }) + .catch((err) => { + console.error("Failed to connect to DB"); + console.error(err); + }); diff --git a/backend/user/third-party/email.js b/backend/user/third-party/email.js new file mode 100644 index 0000000000..1ac1b5e69d --- /dev/null +++ b/backend/user/third-party/email.js @@ -0,0 +1,61 @@ +import nodemailer from 'nodemailer'; + +// Create a transporter object using the SMTP transport +const transporter = nodemailer.createTransport({ + service: 'gmail', // e.g., 'gmail', 'yahoo', or use SMTP settings for a custom service + auth: { + user: 'peerprepg15@gmail.com', // replace with your email + pass: process.env.EMAIL_PASSWORD // replace with your email password or app-specific password + } +}); + +// Function to send an email +export const sendVerificationEmail = async (email, username, code) => { + try { + const link = `${process.env.FRONTEND_URL}/verify?code=${code}`; + const info = await transporter.sendMail({ + from: '"Mai from PeerPrep" ', // sender address + to: email, // recipient address(es) + subject: 'Verify Your Email for PeerPrep', // subject line + html: ` + Hi, ${username}!

+ Welcome to PeerPrep! We’re excited to have you on board.

+ To complete your registration, please confirm your email address by clicking the link below: + ${link}

+ If you did not create an account with PeerPrep, please disregard this email.

+ Thanks for joining our community! We’re here to help you every step of the way.

+ Best regards,
+ Mai from PeerPrep + ` // HTML body (optional) + }); + + console.log('Email sent:', info.messageId); + } catch (error) { + console.error('Error sending email:', error); + } +}; + +export const sendPasswordResetEmail = async (email, username, code) => { + try { + const link = `${process.env.FRONTEND_URL}/reset-password?code=${code}`; + const info = await transporter.sendMail({ + from: '"Mai from PeerPrep" ', // sender address + to: email, // recipient address(es) + subject: 'Reset Your Password for PeerPrep', // subject line + html: ` + Hi, ${username}!

+ We received a request to reset your password for your PeerPrep account.

+ To reset your password, please click the link below: + ${link}

+ If you did not request a password reset, please disregard this email.

+ Thanks for using PeerPrep! We’re here to help you every step of the way.

+ Best regards,
+ Mai from PeerPrep + ` // HTML body (optional) + }); + + console.log('Email sent:', info.messageId); + } catch (error) { + console.error('Error sending email:', error); + } +} diff --git a/backend/websocket/.gitattributes b/backend/websocket/.gitattributes new file mode 100644 index 0000000000..3b41682ac5 --- /dev/null +++ b/backend/websocket/.gitattributes @@ -0,0 +1,2 @@ +/mvnw text eol=lf +*.cmd text eol=crlf diff --git a/backend/websocket/.gitignore b/backend/websocket/.gitignore new file mode 100644 index 0000000000..549e00a2a9 --- /dev/null +++ b/backend/websocket/.gitignore @@ -0,0 +1,33 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ diff --git a/backend/websocket/.mvn/wrapper/maven-wrapper.properties b/backend/websocket/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000000..d58dfb70ba --- /dev/null +++ b/backend/websocket/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,19 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +wrapperVersion=3.3.2 +distributionType=only-script +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.9/apache-maven-3.9.9-bin.zip diff --git a/backend/websocket/Dockerfile b/backend/websocket/Dockerfile new file mode 100644 index 0000000000..c2ef614d0d --- /dev/null +++ b/backend/websocket/Dockerfile @@ -0,0 +1,13 @@ +FROM eclipse-temurin:17-jdk-jammy + +WORKDIR /app + +COPY .mvn/ .mvn/ +COPY mvnw pom.xml ./ +RUN ./mvnw dependency:go-offline + +COPY src/ ./src/ + +EXPOSE 3005 + +CMD ["./mvnw", "spring-boot:run"] \ No newline at end of file diff --git a/backend/websocket/mvnw b/backend/websocket/mvnw new file mode 100755 index 0000000000..19529ddf8c --- /dev/null +++ b/backend/websocket/mvnw @@ -0,0 +1,259 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Apache Maven Wrapper startup batch script, version 3.3.2 +# +# Optional ENV vars +# ----------------- +# JAVA_HOME - location of a JDK home dir, required when download maven via java source +# MVNW_REPOURL - repo url base for downloading maven distribution +# MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +# MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output +# ---------------------------------------------------------------------------- + +set -euf +[ "${MVNW_VERBOSE-}" != debug ] || set -x + +# OS specific support. +native_path() { printf %s\\n "$1"; } +case "$(uname)" in +CYGWIN* | MINGW*) + [ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")" + native_path() { cygpath --path --windows "$1"; } + ;; +esac + +# set JAVACMD and JAVACCMD +set_java_home() { + # For Cygwin and MinGW, ensure paths are in Unix format before anything is touched + if [ -n "${JAVA_HOME-}" ]; then + if [ -x "$JAVA_HOME/jre/sh/java" ]; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + JAVACCMD="$JAVA_HOME/jre/sh/javac" + else + JAVACMD="$JAVA_HOME/bin/java" + JAVACCMD="$JAVA_HOME/bin/javac" + + if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then + echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2 + echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2 + return 1 + fi + fi + else + JAVACMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v java + )" || : + JAVACCMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v javac + )" || : + + if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then + echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2 + return 1 + fi + fi +} + +# hash string like Java String::hashCode +hash_string() { + str="${1:-}" h=0 + while [ -n "$str" ]; do + char="${str%"${str#?}"}" + h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296)) + str="${str#?}" + done + printf %x\\n $h +} + +verbose() { :; } +[ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; } + +die() { + printf %s\\n "$1" >&2 + exit 1 +} + +trim() { + # MWRAPPER-139: + # Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds. + # Needed for removing poorly interpreted newline sequences when running in more + # exotic environments such as mingw bash on Windows. + printf "%s" "${1}" | tr -d '[:space:]' +} + +# parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties +while IFS="=" read -r key value; do + case "${key-}" in + distributionUrl) distributionUrl=$(trim "${value-}") ;; + distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;; + esac +done <"${0%/*}/.mvn/wrapper/maven-wrapper.properties" +[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in ${0%/*}/.mvn/wrapper/maven-wrapper.properties" + +case "${distributionUrl##*/}" in +maven-mvnd-*bin.*) + MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ + case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in + *AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;; + :Darwin*x86_64) distributionPlatform=darwin-amd64 ;; + :Darwin*arm64) distributionPlatform=darwin-aarch64 ;; + :Linux*x86_64*) distributionPlatform=linux-amd64 ;; + *) + echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2 + distributionPlatform=linux-amd64 + ;; + esac + distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip" + ;; +maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;; +*) MVN_CMD="mvn${0##*/mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;; +esac + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +[ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}" +distributionUrlName="${distributionUrl##*/}" +distributionUrlNameMain="${distributionUrlName%.*}" +distributionUrlNameMain="${distributionUrlNameMain%-bin}" +MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}" +MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")" + +exec_maven() { + unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || : + exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD" +} + +if [ -d "$MAVEN_HOME" ]; then + verbose "found existing MAVEN_HOME at $MAVEN_HOME" + exec_maven "$@" +fi + +case "${distributionUrl-}" in +*?-bin.zip | *?maven-mvnd-?*-?*.zip) ;; +*) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;; +esac + +# prepare tmp dir +if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then + clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; } + trap clean HUP INT TERM EXIT +else + die "cannot create temp dir" +fi + +mkdir -p -- "${MAVEN_HOME%/*}" + +# Download and Install Apache Maven +verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +verbose "Downloading from: $distributionUrl" +verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +# select .zip or .tar.gz +if ! command -v unzip >/dev/null; then + distributionUrl="${distributionUrl%.zip}.tar.gz" + distributionUrlName="${distributionUrl##*/}" +fi + +# verbose opt +__MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR='' +[ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v + +# normalize http auth +case "${MVNW_PASSWORD:+has-password}" in +'') MVNW_USERNAME='' MVNW_PASSWORD='' ;; +has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;; +esac + +if [ -z "${MVNW_USERNAME-}" ] && command -v wget >/dev/null; then + verbose "Found wget ... using wget" + wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" || die "wget: Failed to fetch $distributionUrl" +elif [ -z "${MVNW_USERNAME-}" ] && command -v curl >/dev/null; then + verbose "Found curl ... using curl" + curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" || die "curl: Failed to fetch $distributionUrl" +elif set_java_home; then + verbose "Falling back to use Java to download" + javaSource="$TMP_DOWNLOAD_DIR/Downloader.java" + targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName" + cat >"$javaSource" <<-END + public class Downloader extends java.net.Authenticator + { + protected java.net.PasswordAuthentication getPasswordAuthentication() + { + return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() ); + } + public static void main( String[] args ) throws Exception + { + setDefault( new Downloader() ); + java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() ); + } + } + END + # For Cygwin/MinGW, switch paths to Windows format before running javac and java + verbose " - Compiling Downloader.java ..." + "$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile Downloader.java" + verbose " - Running Downloader.java ..." + "$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")" +fi + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +if [ -n "${distributionSha256Sum-}" ]; then + distributionSha256Result=false + if [ "$MVN_CMD" = mvnd.sh ]; then + echo "Checksum validation is not supported for maven-mvnd." >&2 + echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + elif command -v sha256sum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c >/dev/null 2>&1; then + distributionSha256Result=true + fi + elif command -v shasum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c >/dev/null 2>&1; then + distributionSha256Result=true + fi + else + echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2 + echo "Please install either command, or disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + fi + if [ $distributionSha256Result = false ]; then + echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2 + echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2 + exit 1 + fi +fi + +# unzip and move +if command -v unzip >/dev/null; then + unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" || die "failed to unzip" +else + tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar" +fi +printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/mvnw.url" +mv -- "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME" + +clean || : +exec_maven "$@" diff --git a/backend/websocket/mvnw.cmd b/backend/websocket/mvnw.cmd new file mode 100644 index 0000000000..249bdf3822 --- /dev/null +++ b/backend/websocket/mvnw.cmd @@ -0,0 +1,149 @@ +<# : batch portion +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM http://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Apache Maven Wrapper startup batch script, version 3.3.2 +@REM +@REM Optional ENV vars +@REM MVNW_REPOURL - repo url base for downloading maven distribution +@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output +@REM ---------------------------------------------------------------------------- + +@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0) +@SET __MVNW_CMD__= +@SET __MVNW_ERROR__= +@SET __MVNW_PSMODULEP_SAVE=%PSModulePath% +@SET PSModulePath= +@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @( + IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B) +) +@SET PSModulePath=%__MVNW_PSMODULEP_SAVE% +@SET __MVNW_PSMODULEP_SAVE= +@SET __MVNW_ARG0_NAME__= +@SET MVNW_USERNAME= +@SET MVNW_PASSWORD= +@IF NOT "%__MVNW_CMD__%"=="" (%__MVNW_CMD__% %*) +@echo Cannot start maven from wrapper >&2 && exit /b 1 +@GOTO :EOF +: end batch / begin powershell #> + +$ErrorActionPreference = "Stop" +if ($env:MVNW_VERBOSE -eq "true") { + $VerbosePreference = "Continue" +} + +# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties +$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl +if (!$distributionUrl) { + Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" +} + +switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) { + "maven-mvnd-*" { + $USE_MVND = $true + $distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip" + $MVN_CMD = "mvnd.cmd" + break + } + default { + $USE_MVND = $false + $MVN_CMD = $script -replace '^mvnw','mvn' + break + } +} + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +if ($env:MVNW_REPOURL) { + $MVNW_REPO_PATTERN = if ($USE_MVND) { "/org/apache/maven/" } else { "/maven/mvnd/" } + $distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace '^.*'+$MVNW_REPO_PATTERN,'')" +} +$distributionUrlName = $distributionUrl -replace '^.*/','' +$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$','' +$MAVEN_HOME_PARENT = "$HOME/.m2/wrapper/dists/$distributionUrlNameMain" +if ($env:MAVEN_USER_HOME) { + $MAVEN_HOME_PARENT = "$env:MAVEN_USER_HOME/wrapper/dists/$distributionUrlNameMain" +} +$MAVEN_HOME_NAME = ([System.Security.Cryptography.MD5]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join '' +$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME" + +if (Test-Path -Path "$MAVEN_HOME" -PathType Container) { + Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME" + Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" + exit $? +} + +if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) { + Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl" +} + +# prepare tmp dir +$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile +$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir" +$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null +trap { + if ($TMP_DOWNLOAD_DIR.Exists) { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } + } +} + +New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null + +# Download and Install Apache Maven +Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +Write-Verbose "Downloading from: $distributionUrl" +Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +$webclient = New-Object System.Net.WebClient +if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) { + $webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD) +} +[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 +$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum +if ($distributionSha256Sum) { + if ($USE_MVND) { + Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." + } + Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash + if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) { + Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property." + } +} + +# unzip and move +Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null +Rename-Item -Path "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" -NewName $MAVEN_HOME_NAME | Out-Null +try { + Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null +} catch { + if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) { + Write-Error "fail to move MAVEN_HOME" + } +} finally { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } +} + +Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" diff --git a/backend/websocket/pom.xml b/backend/websocket/pom.xml new file mode 100644 index 0000000000..7ebee9b332 --- /dev/null +++ b/backend/websocket/pom.xml @@ -0,0 +1,78 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 3.3.4 + + + com.example.backend + websocket + 0.0.1-SNAPSHOT + websocket + WebSocket Service + + + + + + + + + + + + + + + 17 + + + + org.springframework.boot + spring-boot-starter-websocket + + + + org.springframework.kafka + spring-kafka + + + + org.springframework.boot + spring-boot-starter-test + test + + + + org.springframework.kafka + spring-kafka-test + test + + + + org.projectlombok + lombok + 1.18.20 + provided + + + + redis.clients + jedis + 4.3.1 + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/backend/websocket/src/main/java/com/example/backend/websocket/WebSocketService.java b/backend/websocket/src/main/java/com/example/backend/websocket/WebSocketService.java new file mode 100644 index 0000000000..45e1dcaa1b --- /dev/null +++ b/backend/websocket/src/main/java/com/example/backend/websocket/WebSocketService.java @@ -0,0 +1,70 @@ +package com.example.backend.websocket; + +import org.springframework.messaging.simp.SimpMessagingTemplate; +import org.springframework.messaging.simp.user.SimpUserRegistry; +import org.springframework.stereotype.Service; + +import redis.clients.jedis.Jedis; +import redis.clients.jedis.JedisPool; + +@Service +public class WebSocketService { + + private final SimpMessagingTemplate messagingTemplate; + private final SimpUserRegistry userRegistry; + private final JedisPool jedisPool; + private final String ACTIVE_USERS = "ActiveUsers"; + + public WebSocketService(SimpMessagingTemplate messagingTemplate, SimpUserRegistry userRegistry, JedisPool jedisPool) { + this.messagingTemplate = messagingTemplate; + this.userRegistry = userRegistry; + this.jedisPool = jedisPool; + } + + // Notify user that a match has been found + public void notifyUser(String userId, String message) { + if (userRegistry.getUser(userId) != null) { + messagingTemplate.convertAndSendToUser(userId, "/queue/matches", message); + } else { + System.out.println("User " + userId + " is not connected."); + } + } + + public void notifyUserNoQuestionExists(String userId) { + if (userRegistry.getUser(userId) != null) { + messagingTemplate.convertAndSendToUser(userId, "/queue/noQuestionExists", "No question exists for the match criteria."); + System.out.println("Notifying user " + userId + " that no question exists for the match criteria."); + } else { + System.out.println("User " + userId + " is not connected."); + } + } + + // Reject user from making a match request + public void rejectUser(String userId, String message) { + if (userRegistry.getUser(userId) != null) { + messagingTemplate.convertAndSendToUser(userId, "/queue/requestRejection", message); + } else { + System.out.println("User " + userId + " is not connected."); + } + } + + public boolean isUserActive(String userEmail) { + try (Jedis jedis = jedisPool.getResource()) { + boolean isUserActive = jedis.sismember(ACTIVE_USERS, userEmail); + jedis.close(); + return isUserActive; + } catch (Exception e) { + System.out.println("Error checking if user is active: " + e.getMessage()); + return false; + } + } + + public void addToActiveUsers(String userEmail) { + try (Jedis jedis = jedisPool.getResource()) { + jedis.sadd(ACTIVE_USERS, userEmail); + jedis.close(); + } catch (Exception e) { + System.out.println("Error adding user to active users: " + e.getMessage()); + } + } +} diff --git a/backend/websocket/src/main/java/com/example/backend/websocket/WebsocketApplication.java b/backend/websocket/src/main/java/com/example/backend/websocket/WebsocketApplication.java new file mode 100644 index 0000000000..84529bd8c4 --- /dev/null +++ b/backend/websocket/src/main/java/com/example/backend/websocket/WebsocketApplication.java @@ -0,0 +1,13 @@ +package com.example.backend.websocket; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class WebsocketApplication { + + public static void main(String[] args) { + SpringApplication.run(WebsocketApplication.class, args); + } + +} diff --git a/backend/websocket/src/main/java/com/example/backend/websocket/config/CorsConfig.java b/backend/websocket/src/main/java/com/example/backend/websocket/config/CorsConfig.java new file mode 100644 index 0000000000..d36ab3615c --- /dev/null +++ b/backend/websocket/src/main/java/com/example/backend/websocket/config/CorsConfig.java @@ -0,0 +1,20 @@ +package com.example.backend.websocket.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.CorsRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +@Configuration +public class CorsConfig { + + @Bean + public WebMvcConfigurer corsConfigurer() { + return new WebMvcConfigurer() { + @Override + public void addCorsMappings(CorsRegistry registry) { + registry.addMapping("/*").allowedOrigins(""); + } + }; + } +} \ No newline at end of file diff --git a/backend/websocket/src/main/java/com/example/backend/websocket/config/MyUserPrincipal.java b/backend/websocket/src/main/java/com/example/backend/websocket/config/MyUserPrincipal.java new file mode 100644 index 0000000000..4ef080355e --- /dev/null +++ b/backend/websocket/src/main/java/com/example/backend/websocket/config/MyUserPrincipal.java @@ -0,0 +1,47 @@ +package com.example.backend.websocket.config; + +import java.io.Serializable; +import java.security.Principal; + +import lombok.Data; + +@Data +public class MyUserPrincipal implements Principal, Serializable { + private static final long serialVersionUID = 1L; + private final String name; // the userId / wsId + private String userEmail = ""; + + public MyUserPrincipal(String name) { + if (name == null) { + throw new NullPointerException("null name is illegal"); + } + this.name = name; + } + + @Override + public String getName() { + return this.name; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj instanceof MyUserPrincipal) { + MyUserPrincipal other = (MyUserPrincipal) obj; + return this.name.equals(other.getName()); + } + return false; + } + + @Override + public int hashCode() { + return this.name.hashCode(); + } + + @Override + public String toString() { + return "MyUserPrincipal{name='" + this.name + "'}"; + } +} diff --git a/backend/websocket/src/main/java/com/example/backend/websocket/config/UserHandshakeHandler.java b/backend/websocket/src/main/java/com/example/backend/websocket/config/UserHandshakeHandler.java new file mode 100644 index 0000000000..50da43cb34 --- /dev/null +++ b/backend/websocket/src/main/java/com/example/backend/websocket/config/UserHandshakeHandler.java @@ -0,0 +1,17 @@ +package com.example.backend.websocket.config; + +import java.security.Principal; +import java.util.Map; +import java.util.UUID; + +import org.springframework.http.server.ServerHttpRequest; +import org.springframework.web.socket.WebSocketHandler; +import org.springframework.web.socket.server.support.DefaultHandshakeHandler; + +public class UserHandshakeHandler extends DefaultHandshakeHandler{ + @Override + protected Principal determineUser(ServerHttpRequest request, WebSocketHandler wsHandler, + Map attributes) { + return new MyUserPrincipal(UUID.randomUUID().toString()); + } +} diff --git a/backend/websocket/src/main/java/com/example/backend/websocket/config/WebSocketConfig.java b/backend/websocket/src/main/java/com/example/backend/websocket/config/WebSocketConfig.java new file mode 100644 index 0000000000..8f2f413b5d --- /dev/null +++ b/backend/websocket/src/main/java/com/example/backend/websocket/config/WebSocketConfig.java @@ -0,0 +1,98 @@ +package com.example.backend.websocket.config; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Configuration; +import org.springframework.messaging.Message; +import org.springframework.messaging.MessageChannel; +import org.springframework.messaging.simp.config.ChannelRegistration; +import org.springframework.messaging.simp.config.MessageBrokerRegistry; +import org.springframework.messaging.simp.stomp.StompCommand; +import org.springframework.messaging.simp.stomp.StompHeaderAccessor; +import org.springframework.messaging.support.ChannelInterceptor; +import org.springframework.messaging.support.MessageHeaderAccessor; +import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker; +import org.springframework.web.socket.config.annotation.StompEndpointRegistry; +import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer; + +import com.example.backend.websocket.kafka.producers.DisconnectProducer; + +import redis.clients.jedis.Jedis; +import redis.clients.jedis.JedisPool; + +@Configuration +@EnableWebSocketMessageBroker +public class WebSocketConfig implements WebSocketMessageBrokerConfigurer { + @Autowired + private DisconnectProducer disconnectProducer; + + @Autowired + private JedisPool jedisPool; + + // private final String allowedOrigin = System.getenv("FRONTEND_CORS_ALLOWED_ORIGINS"); + private final String allowedOrigin = "http://localhost:3000"; + + private final String ACTIVE_USERS = "ActiveUsers"; + + @Override + public void registerStompEndpoints(StompEndpointRegistry registry) { + // HTTP URL for the WebSocket connection used by the client + registry.addEndpoint("/matching-websocket") + .setAllowedOriginPatterns(allowedOrigin) + .setHandshakeHandler(new UserHandshakeHandler()) + .withSockJS(); + } + + @Override + public void configureMessageBroker(MessageBrokerRegistry config) { + // routes to @MessageMapping methods in @Controller classes + config.setApplicationDestinationPrefixes("/app"); + // defines message broker destinations: /topic for broadcasting to all subscribers, /queue for point-to-point messaging + config.enableSimpleBroker("/topic", "/queue"); + // defines prefix for messages that are bound for a specific user + config.setUserDestinationPrefix("/user"); + } + + // Intercepts messages coming from the client and handles connection and disconnection events + @Override + public void configureClientInboundChannel(ChannelRegistration registration) { + registration.interceptors(new ChannelInterceptor() { + @Override + public Message preSend(Message message, MessageChannel channel) { + StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class); + + if (accessor != null) { + // Handle connection events + if (StompCommand.CONNECT.equals(accessor.getCommand())) { + String connectedUser = accessor.getUser().getName(); + System.out.println("User connected: " + connectedUser); + } + + // Handle disconnection events + if (StompCommand.DISCONNECT.equals(accessor.getCommand())) { + MyUserPrincipal principal = (MyUserPrincipal) accessor.getUser(); + String disconnectedUserEmail = principal.getUserEmail(); + if (disconnectedUserEmail.equals("")) { + // This is the disconnection event for the same user's second connection + System.out.println("Disconnection event for active user's subsequent connection"); + return message; + } + + try { + Jedis jedis = jedisPool.getResource(); + jedis.srem(ACTIVE_USERS, disconnectedUserEmail); + jedis.close(); + } catch (Exception e) { + System.out.println("Error removing user from ActiveUsers: " + e.getMessage()); + } + + String disconnectedUserWsid = principal.getName(); + System.out.println("User disconnected: " + disconnectedUserWsid); + disconnectProducer.sendMessage("DISCONNECTS", disconnectedUserWsid, disconnectedUserWsid); + } + } + + return message; + } + }); + } +} diff --git a/backend/websocket/src/main/java/com/example/backend/websocket/controller/MatchRequest.java b/backend/websocket/src/main/java/com/example/backend/websocket/controller/MatchRequest.java new file mode 100644 index 0000000000..5fa3b85525 --- /dev/null +++ b/backend/websocket/src/main/java/com/example/backend/websocket/controller/MatchRequest.java @@ -0,0 +1,93 @@ +package com.example.backend.websocket.controller; + +import java.util.ArrayList; +import java.util.List; + +import lombok.Data; + +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.client.RestClientException; +import org.springframework.web.client.RestTemplate; + +import com.example.backend.websocket.model.VerifyMatchCriteriaDTO; +import com.example.backend.websocket.model.VerificationResponse; + +@Data +public class MatchRequest { + private String userEmail; + private String userId; + private String[] topics; + private String[] programmingLanguages; + private String[] difficulties; + + private static final String QUESTION_API_URL = System.getenv("ENV").equals("DEV") ? System.getenv("DEV_QUESTION_API_URL") : System.getenv("PROD_QUESTION_API_URL"); + + private final RestTemplate restTemplate = new RestTemplate(); + + // Retrieves all match criteria combinations for which at least 1 question exists + public List getValidMatchCriteriaKey() { + List validMatchCriteriaKey = new ArrayList<>(); + + List allTopicsInCombinations = new ArrayList<>(); + List allDifficutiesInCombinations = new ArrayList<>(); + List allProgrammingLanguagesInCombinations = new ArrayList<>(); + for (String t : topics) { + for (String d : difficulties) { + for (String pl : programmingLanguages) { + allTopicsInCombinations.add(t); + allDifficutiesInCombinations.add(d); + allProgrammingLanguagesInCombinations.add(pl); + } + } + } + + try { + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_JSON); + + VerifyMatchCriteriaDTO verifyMatchCriteriaDTO = new VerifyMatchCriteriaDTO(allDifficutiesInCombinations, allTopicsInCombinations); + HttpEntity request = new HttpEntity<>(verifyMatchCriteriaDTO, headers); + + ResponseEntity response = restTemplate.exchange( + QUESTION_API_URL + "/count-question", + HttpMethod.POST, + request, + new ParameterizedTypeReference() {} + ); + + if (!response.getStatusCode().is2xxSuccessful()) { + throw new RestClientException("Failed to verify that a question exists for the match criteria. Status code: " + response.getStatusCode()); + } + + VerificationResponse verificationResponse = response.getBody(); + if (verificationResponse == null) { + System.err.println("Failed to verify that a question exists for the match criteria. Verification response is missing."); + } + + int[] questionCounts = verificationResponse.getCounts(); + for (int i = 0; i < questionCounts.length; i++) { + String matchCriteria = allTopicsInCombinations.get(i) + + "_" + + allProgrammingLanguagesInCombinations.get(i) + + "_" + + allDifficutiesInCombinations.get(i); + if (questionCounts[i] > 0) { + validMatchCriteriaKey.add(matchCriteria); + System.out.println("At least 1 question found for match criteria: " + matchCriteria); + } else { + System.out.println("No question found for match criteria: " + matchCriteria); + } + } + System.out.println("Valid match criteria (at least 1 question exists): " + validMatchCriteriaKey); + } catch (RestClientException e) { + System.err.println("Error calling question service: " + e.getMessage()); + } + + return validMatchCriteriaKey; + } +} diff --git a/backend/websocket/src/main/java/com/example/backend/websocket/controller/WebSocketController.java b/backend/websocket/src/main/java/com/example/backend/websocket/controller/WebSocketController.java new file mode 100644 index 0000000000..c15c12a535 --- /dev/null +++ b/backend/websocket/src/main/java/com/example/backend/websocket/controller/WebSocketController.java @@ -0,0 +1,47 @@ +package com.example.backend.websocket.controller; + +import java.security.Principal; +import java.util.List; + +import org.springframework.messaging.handler.annotation.MessageMapping; +import org.springframework.stereotype.Controller; + +import com.example.backend.websocket.WebSocketService; +import com.example.backend.websocket.config.MyUserPrincipal; +import com.example.backend.websocket.kafka.producers.MatchRequestProducer; + +@Controller +public class WebSocketController { + + private MatchRequestProducer matchRequestProducer; + private WebSocketService webSocketService; + + public WebSocketController(MatchRequestProducer matchRequestProducer, WebSocketService webSocketService) { + this.matchRequestProducer = matchRequestProducer; + this.webSocketService = webSocketService; + } + + @MessageMapping("/matchRequest") + public void processMatchRequest(MatchRequest matchRequest, Principal principal) { + MyUserPrincipal myUserPrincipal = (MyUserPrincipal) principal; + String userId = myUserPrincipal.getName(); // This should return the wsid + System.out.println("Received match request from user: " + matchRequest.getUserEmail()); + + if (webSocketService.isUserActive(matchRequest.getUserEmail())) { + System.out.println("User " + matchRequest.getUserEmail() + " is already active."); + webSocketService.rejectUser(userId, "You are already active on another device."); + return; + } + + myUserPrincipal.setUserEmail(matchRequest.getUserEmail()); + webSocketService.addToActiveUsers(matchRequest.getUserEmail()); + List validMatchCriteriaKeys = matchRequest.getValidMatchCriteriaKey(); + if (validMatchCriteriaKeys.isEmpty()) { + webSocketService.notifyUserNoQuestionExists(userId); + return; + } + validMatchCriteriaKeys.forEach(key -> { + matchRequestProducer.sendMessage("MATCH_REQUESTS", key, userId + "_" + matchRequest.getUserEmail() + "_" + matchRequest.getUserId()); + }); + } +} \ No newline at end of file diff --git a/backend/websocket/src/main/java/com/example/backend/websocket/kafka/consumers/KafkaConsumerConfig.java b/backend/websocket/src/main/java/com/example/backend/websocket/kafka/consumers/KafkaConsumerConfig.java new file mode 100644 index 0000000000..8284b3b3c2 --- /dev/null +++ b/backend/websocket/src/main/java/com/example/backend/websocket/kafka/consumers/KafkaConsumerConfig.java @@ -0,0 +1,37 @@ +package com.example.backend.websocket.kafka.consumers; + +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +import org.apache.kafka.clients.consumer.ConsumerConfig; +import org.apache.kafka.common.serialization.StringDeserializer; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.kafka.config.ConcurrentKafkaListenerContainerFactory; +import org.springframework.kafka.core.ConsumerFactory; +import org.springframework.kafka.core.DefaultKafkaConsumerFactory; + +@Configuration +public class KafkaConsumerConfig { + + private final String kafkaBrokerAddress = System.getenv("ENV").equals("DEV") ? System.getenv("DEV_KAFKA_URL") : System.getenv("PROD_KAFKA_URL"); + + @Bean + public ConsumerFactory consumerFactory() { + Map configProps = new HashMap<>(); + configProps.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, kafkaBrokerAddress); // Kafka broker address + String randomGroupId = "group-" + UUID.randomUUID().toString(); + configProps.put(ConsumerConfig.GROUP_ID_CONFIG, randomGroupId); // Random consumer group ID + configProps.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class); // Key deserializer + configProps.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class); // Value deserializer + return new DefaultKafkaConsumerFactory<>(configProps); + } + + @Bean + public ConcurrentKafkaListenerContainerFactory kafkaListenerContainerFactory() { + ConcurrentKafkaListenerContainerFactory factory = new ConcurrentKafkaListenerContainerFactory<>(); + factory.setConsumerFactory(consumerFactory()); + return factory; + } +} diff --git a/backend/websocket/src/main/java/com/example/backend/websocket/kafka/consumers/MatchRequestConsumer.java b/backend/websocket/src/main/java/com/example/backend/websocket/kafka/consumers/MatchRequestConsumer.java new file mode 100644 index 0000000000..8d1fd3925e --- /dev/null +++ b/backend/websocket/src/main/java/com/example/backend/websocket/kafka/consumers/MatchRequestConsumer.java @@ -0,0 +1,48 @@ +package com.example.backend.websocket.kafka.consumers; + +import org.springframework.kafka.annotation.KafkaListener; +import org.springframework.stereotype.Component; + +import com.example.backend.websocket.WebSocketService; +import com.example.backend.websocket.model.MatchNotification; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; + +@Component +public class MatchRequestConsumer { + private final WebSocketService webSocketService; + private final ObjectMapper objectMapper; + + public MatchRequestConsumer(WebSocketService webSocketService) { + this.webSocketService = webSocketService; + this.objectMapper = new ObjectMapper(); + } + + @KafkaListener(topics = "SUCCESSFUL_MATCHES") + public void listen(String value) { + System.out.println("Received successful match: " + value); + + String[] userInformation = value.split("_"); + String collaborationId = userInformation[0]; + String questionId = userInformation[1]; + String language = userInformation[2]; + String user1WsId = userInformation[3]; + String user1Id = userInformation[4]; + String user1Email = userInformation[5]; + String user2WsId = userInformation[6]; + String user2Id = userInformation[7]; + String user2Email = userInformation[8]; + + MatchNotification user1Notification = new MatchNotification(user2Email, user2Id, collaborationId, questionId, language); + MatchNotification user2Notification = new MatchNotification(user1Email, user1Id, collaborationId, questionId, language); + + try { + String jsonNotification1 = objectMapper.writeValueAsString(user1Notification); + String jsonNotification2 = objectMapper.writeValueAsString(user2Notification); + webSocketService.notifyUser(user1WsId, jsonNotification1); + webSocketService.notifyUser(user2WsId, jsonNotification2); + } catch (JsonProcessingException e) { + System.err.println("Error converting notification to JSON: " + e.getMessage()); + } + } +} diff --git a/backend/websocket/src/main/java/com/example/backend/websocket/kafka/producers/DisconnectProducer.java b/backend/websocket/src/main/java/com/example/backend/websocket/kafka/producers/DisconnectProducer.java new file mode 100644 index 0000000000..9e55d762c8 --- /dev/null +++ b/backend/websocket/src/main/java/com/example/backend/websocket/kafka/producers/DisconnectProducer.java @@ -0,0 +1,16 @@ +package com.example.backend.websocket.kafka.producers; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.kafka.core.KafkaTemplate; +import org.springframework.stereotype.Component; + +@Component +public class DisconnectProducer { + + @Autowired + private KafkaTemplate kafkaTemplate; + + public void sendMessage(String topic, String key, String value) { + kafkaTemplate.send(topic, key, value); + } +} diff --git a/backend/websocket/src/main/java/com/example/backend/websocket/kafka/producers/KafkaProducerConfig.java b/backend/websocket/src/main/java/com/example/backend/websocket/kafka/producers/KafkaProducerConfig.java new file mode 100644 index 0000000000..25a04e94b4 --- /dev/null +++ b/backend/websocket/src/main/java/com/example/backend/websocket/kafka/producers/KafkaProducerConfig.java @@ -0,0 +1,32 @@ +package com.example.backend.websocket.kafka.producers; + +import java.util.HashMap; +import java.util.Map; + +import org.apache.kafka.clients.producer.ProducerConfig; +import org.apache.kafka.common.serialization.StringSerializer; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.kafka.core.DefaultKafkaProducerFactory; +import org.springframework.kafka.core.KafkaTemplate; +import org.springframework.kafka.core.ProducerFactory; + +@Configuration +public class KafkaProducerConfig { + + private final String kafkaBrokerAddress = System.getenv("ENV").equals("DEV") ? System.getenv("DEV_KAFKA_URL") : System.getenv("PROD_KAFKA_URL"); + + @Bean + public ProducerFactory producerFactory() { + Map configProps = new HashMap<>(); + configProps.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, kafkaBrokerAddress); // Kafka broker address + configProps.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class); // Key serializer + configProps.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class); // Value serializer + return new DefaultKafkaProducerFactory<>(configProps); + } + + @Bean + public KafkaTemplate kafkaTemplate() { + return new KafkaTemplate<>(producerFactory()); + } +} \ No newline at end of file diff --git a/backend/websocket/src/main/java/com/example/backend/websocket/kafka/producers/MatchRequestProducer.java b/backend/websocket/src/main/java/com/example/backend/websocket/kafka/producers/MatchRequestProducer.java new file mode 100644 index 0000000000..264f947c15 --- /dev/null +++ b/backend/websocket/src/main/java/com/example/backend/websocket/kafka/producers/MatchRequestProducer.java @@ -0,0 +1,16 @@ +package com.example.backend.websocket.kafka.producers; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.kafka.core.KafkaTemplate; +import org.springframework.stereotype.Component; + +@Component +public class MatchRequestProducer { + + @Autowired + private KafkaTemplate kafkaTemplate; + + public void sendMessage(String topic, String key, String value) { + kafkaTemplate.send(topic, key, value); + } +} diff --git a/backend/websocket/src/main/java/com/example/backend/websocket/model/MatchNotification.java b/backend/websocket/src/main/java/com/example/backend/websocket/model/MatchNotification.java new file mode 100644 index 0000000000..b17d51fa33 --- /dev/null +++ b/backend/websocket/src/main/java/com/example/backend/websocket/model/MatchNotification.java @@ -0,0 +1,20 @@ +package com.example.backend.websocket.model; + +import lombok.Data; + +@Data +public class MatchNotification { + private String matchedUserEmail; + private String matchedUserId; + private String collaborationId; + private String questionId; + private String language; + + public MatchNotification(String matchedUserEmail, String matchedUserId, String collaborationId, String questionId, String language) { + this.matchedUserEmail = matchedUserEmail; + this.matchedUserId = matchedUserId; + this.collaborationId = collaborationId; + this.questionId = questionId; + this.language = language; + } +} diff --git a/backend/websocket/src/main/java/com/example/backend/websocket/model/VerificationResponse.java b/backend/websocket/src/main/java/com/example/backend/websocket/model/VerificationResponse.java new file mode 100644 index 0000000000..7b24b0f56f --- /dev/null +++ b/backend/websocket/src/main/java/com/example/backend/websocket/model/VerificationResponse.java @@ -0,0 +1,8 @@ +package com.example.backend.websocket.model; + +import lombok.Data; + +@Data +public class VerificationResponse { + private int[] counts; +} diff --git a/backend/websocket/src/main/java/com/example/backend/websocket/model/VerifyMatchCriteriaDTO.java b/backend/websocket/src/main/java/com/example/backend/websocket/model/VerifyMatchCriteriaDTO.java new file mode 100644 index 0000000000..d8269a8bfe --- /dev/null +++ b/backend/websocket/src/main/java/com/example/backend/websocket/model/VerifyMatchCriteriaDTO.java @@ -0,0 +1,16 @@ +package com.example.backend.websocket.model; + +import java.util.List; + +import lombok.Data; + +@Data +public class VerifyMatchCriteriaDTO { + List complexity; + List category; + + public VerifyMatchCriteriaDTO(List complexity, List category) { + this.complexity = complexity; + this.category = category; + } +} diff --git a/backend/websocket/src/main/java/com/example/backend/websocket/redis/JedisConfig.java b/backend/websocket/src/main/java/com/example/backend/websocket/redis/JedisConfig.java new file mode 100644 index 0000000000..07541c392e --- /dev/null +++ b/backend/websocket/src/main/java/com/example/backend/websocket/redis/JedisConfig.java @@ -0,0 +1,23 @@ +package com.example.backend.websocket.redis; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import redis.clients.jedis.JedisPool; +import redis.clients.jedis.JedisPoolConfig; + +@Configuration +public class JedisConfig { + private static final String REDIS_HOST = System.getenv("ENV").equals("DEV") ? System.getenv("DEV_REDIS_HOST") : System.getenv("PROD_REDIS_HOST"); + private static final int REDIS_PORT = System.getenv("ENV").equals("DEV") ? Integer.parseInt(System.getenv("DEV_REDIS_PORT")) : Integer.parseInt(System.getenv("PROD_REDIS_PORT")); + + @Bean + public JedisPool jedisPool() { + JedisPoolConfig poolConfig = new JedisPoolConfig(); + poolConfig.setMaxTotal(50); + poolConfig.setMaxIdle(10); + poolConfig.setMinIdle(5); + poolConfig.setTestOnBorrow(true); + poolConfig.setTestOnReturn(true); + return new JedisPool(poolConfig, REDIS_HOST, REDIS_PORT); + } +} \ No newline at end of file diff --git a/backend/websocket/src/main/resources/application-dev.properties b/backend/websocket/src/main/resources/application-dev.properties new file mode 100644 index 0000000000..40d841d20f --- /dev/null +++ b/backend/websocket/src/main/resources/application-dev.properties @@ -0,0 +1 @@ +spring.kafka.bootstrap-servers=${DEV_KAFKA_URL} diff --git a/backend/websocket/src/main/resources/application-prod.properties b/backend/websocket/src/main/resources/application-prod.properties new file mode 100644 index 0000000000..5c71ea6660 --- /dev/null +++ b/backend/websocket/src/main/resources/application-prod.properties @@ -0,0 +1 @@ +spring.kafka.bootstrap-servers=${PROD_KAFKA_URL} diff --git a/backend/websocket/src/main/resources/application.properties b/backend/websocket/src/main/resources/application.properties new file mode 100644 index 0000000000..e3f96d77bd --- /dev/null +++ b/backend/websocket/src/main/resources/application.properties @@ -0,0 +1,8 @@ +spring.application.name=websocket +server.port=3005 +spring.profiles.active=${ENV} + +# Kafka Configuration +spring.kafka.consumer.group-id=matching-service +spring.kafka.consumer.auto-offset-reset=earliest +spring.kafka.consumer.properties.spring.json.trusted.packages=* \ No newline at end of file diff --git a/backend/websocket/src/main/resources/static/app.js b/backend/websocket/src/main/resources/static/app.js new file mode 100644 index 0000000000..2eb52c0e42 --- /dev/null +++ b/backend/websocket/src/main/resources/static/app.js @@ -0,0 +1,57 @@ +let stompClient; + +// Add event listeners for buttons +document.getElementById("connectButton").addEventListener("click", connect); +document + .getElementById("sendMessageButton") + .addEventListener("click", sendMatchRequest); + +// Function to connect to the WebSocket server +function connect() { + const socket = new SockJS("/matching-websocket"); // Connect to the WebSocket endpoint + stompClient = Stomp.over(socket); + + stompClient.connect( + {}, + (frame) => { + // Connection successful + console.log("Connected: " + frame); // Add print statement for connection success + alert("WebSocket connection established"); // Optional alert to notify success in UI + + // Subscribe to the user-specific queue for receiving match notifications + stompClient.subscribe("/user/queue/matches", (message) => { + console.log("Received a message from the server: ", message.body); // Add print statement for received messages + document.getElementById( + "messages" + ).innerHTML += `

Received: ${message.body}

`; + }); + }, + (error) => { + // Connection error handling + console.error("WebSocket connection failed: " + error); // Print error if connection fails + alert("WebSocket connection failed. Check console for details."); // Notify user of connection failure + } + ); +} + +// Function to send a test match request through WebSocket +function sendMatchRequest() { + // Create a hardcoded test match request object + const matchRequest = JSON.stringify({ + userEmail: "testuser@example.com", + topics: ["test_topic_1"], + programmingLanguages: ["Java"], + difficulties: ["medium"], + }); + + // Check if stompClient is connected before sending + if (stompClient && stompClient.connected) { + // Send the test match request through the WebSocket + stompClient.send("/app/matchRequest", {}, matchRequest); + console.log("Test match request sent: ", matchRequest); // Add print statement for sent match request + alert("Match request sent successfully"); // Notify the user + } else { + console.error("Cannot send match request: WebSocket is not connected"); + alert("Cannot send match request: WebSocket is not connected"); // Notify user of connection issue + } +} diff --git a/backend/websocket/src/main/resources/static/index.html b/backend/websocket/src/main/resources/static/index.html new file mode 100644 index 0000000000..7396882662 --- /dev/null +++ b/backend/websocket/src/main/resources/static/index.html @@ -0,0 +1,19 @@ + + + + + + WebSocket Test + + + + + +

WebSocket Test

+ + + + +
+ + diff --git a/backend/websocket/src/test/java/com/example/backend/websocket/WebsocketApplicationTests.java b/backend/websocket/src/test/java/com/example/backend/websocket/WebsocketApplicationTests.java new file mode 100644 index 0000000000..8860edcb00 --- /dev/null +++ b/backend/websocket/src/test/java/com/example/backend/websocket/WebsocketApplicationTests.java @@ -0,0 +1,13 @@ +package com.example.backend.websocket; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class WebsocketApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/backend/websocketchat/.gitattributes b/backend/websocketchat/.gitattributes new file mode 100644 index 0000000000..3b41682ac5 --- /dev/null +++ b/backend/websocketchat/.gitattributes @@ -0,0 +1,2 @@ +/mvnw text eol=lf +*.cmd text eol=crlf diff --git a/backend/websocketchat/.gitignore b/backend/websocketchat/.gitignore new file mode 100644 index 0000000000..549e00a2a9 --- /dev/null +++ b/backend/websocketchat/.gitignore @@ -0,0 +1,33 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ diff --git a/backend/websocketchat/.mvn/wrapper/maven-wrapper.properties b/backend/websocketchat/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000000..d58dfb70ba --- /dev/null +++ b/backend/websocketchat/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,19 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +wrapperVersion=3.3.2 +distributionType=only-script +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.9/apache-maven-3.9.9-bin.zip diff --git a/backend/websocketchat/Dockerfile b/backend/websocketchat/Dockerfile new file mode 100644 index 0000000000..7f404a2ec5 --- /dev/null +++ b/backend/websocketchat/Dockerfile @@ -0,0 +1,13 @@ +FROM eclipse-temurin:17-jdk-jammy + +WORKDIR /app + +COPY .mvn/ .mvn/ +COPY mvnw pom.xml ./ +RUN ./mvnw dependency:go-offline + +COPY src/ ./src/ + +EXPOSE 3007 + +CMD ["./mvnw", "spring-boot:run"] \ No newline at end of file diff --git a/backend/websocketchat/mvnw b/backend/websocketchat/mvnw new file mode 100755 index 0000000000..19529ddf8c --- /dev/null +++ b/backend/websocketchat/mvnw @@ -0,0 +1,259 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Apache Maven Wrapper startup batch script, version 3.3.2 +# +# Optional ENV vars +# ----------------- +# JAVA_HOME - location of a JDK home dir, required when download maven via java source +# MVNW_REPOURL - repo url base for downloading maven distribution +# MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +# MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output +# ---------------------------------------------------------------------------- + +set -euf +[ "${MVNW_VERBOSE-}" != debug ] || set -x + +# OS specific support. +native_path() { printf %s\\n "$1"; } +case "$(uname)" in +CYGWIN* | MINGW*) + [ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")" + native_path() { cygpath --path --windows "$1"; } + ;; +esac + +# set JAVACMD and JAVACCMD +set_java_home() { + # For Cygwin and MinGW, ensure paths are in Unix format before anything is touched + if [ -n "${JAVA_HOME-}" ]; then + if [ -x "$JAVA_HOME/jre/sh/java" ]; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + JAVACCMD="$JAVA_HOME/jre/sh/javac" + else + JAVACMD="$JAVA_HOME/bin/java" + JAVACCMD="$JAVA_HOME/bin/javac" + + if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then + echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2 + echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2 + return 1 + fi + fi + else + JAVACMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v java + )" || : + JAVACCMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v javac + )" || : + + if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then + echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2 + return 1 + fi + fi +} + +# hash string like Java String::hashCode +hash_string() { + str="${1:-}" h=0 + while [ -n "$str" ]; do + char="${str%"${str#?}"}" + h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296)) + str="${str#?}" + done + printf %x\\n $h +} + +verbose() { :; } +[ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; } + +die() { + printf %s\\n "$1" >&2 + exit 1 +} + +trim() { + # MWRAPPER-139: + # Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds. + # Needed for removing poorly interpreted newline sequences when running in more + # exotic environments such as mingw bash on Windows. + printf "%s" "${1}" | tr -d '[:space:]' +} + +# parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties +while IFS="=" read -r key value; do + case "${key-}" in + distributionUrl) distributionUrl=$(trim "${value-}") ;; + distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;; + esac +done <"${0%/*}/.mvn/wrapper/maven-wrapper.properties" +[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in ${0%/*}/.mvn/wrapper/maven-wrapper.properties" + +case "${distributionUrl##*/}" in +maven-mvnd-*bin.*) + MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ + case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in + *AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;; + :Darwin*x86_64) distributionPlatform=darwin-amd64 ;; + :Darwin*arm64) distributionPlatform=darwin-aarch64 ;; + :Linux*x86_64*) distributionPlatform=linux-amd64 ;; + *) + echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2 + distributionPlatform=linux-amd64 + ;; + esac + distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip" + ;; +maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;; +*) MVN_CMD="mvn${0##*/mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;; +esac + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +[ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}" +distributionUrlName="${distributionUrl##*/}" +distributionUrlNameMain="${distributionUrlName%.*}" +distributionUrlNameMain="${distributionUrlNameMain%-bin}" +MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}" +MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")" + +exec_maven() { + unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || : + exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD" +} + +if [ -d "$MAVEN_HOME" ]; then + verbose "found existing MAVEN_HOME at $MAVEN_HOME" + exec_maven "$@" +fi + +case "${distributionUrl-}" in +*?-bin.zip | *?maven-mvnd-?*-?*.zip) ;; +*) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;; +esac + +# prepare tmp dir +if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then + clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; } + trap clean HUP INT TERM EXIT +else + die "cannot create temp dir" +fi + +mkdir -p -- "${MAVEN_HOME%/*}" + +# Download and Install Apache Maven +verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +verbose "Downloading from: $distributionUrl" +verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +# select .zip or .tar.gz +if ! command -v unzip >/dev/null; then + distributionUrl="${distributionUrl%.zip}.tar.gz" + distributionUrlName="${distributionUrl##*/}" +fi + +# verbose opt +__MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR='' +[ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v + +# normalize http auth +case "${MVNW_PASSWORD:+has-password}" in +'') MVNW_USERNAME='' MVNW_PASSWORD='' ;; +has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;; +esac + +if [ -z "${MVNW_USERNAME-}" ] && command -v wget >/dev/null; then + verbose "Found wget ... using wget" + wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" || die "wget: Failed to fetch $distributionUrl" +elif [ -z "${MVNW_USERNAME-}" ] && command -v curl >/dev/null; then + verbose "Found curl ... using curl" + curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" || die "curl: Failed to fetch $distributionUrl" +elif set_java_home; then + verbose "Falling back to use Java to download" + javaSource="$TMP_DOWNLOAD_DIR/Downloader.java" + targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName" + cat >"$javaSource" <<-END + public class Downloader extends java.net.Authenticator + { + protected java.net.PasswordAuthentication getPasswordAuthentication() + { + return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() ); + } + public static void main( String[] args ) throws Exception + { + setDefault( new Downloader() ); + java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() ); + } + } + END + # For Cygwin/MinGW, switch paths to Windows format before running javac and java + verbose " - Compiling Downloader.java ..." + "$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile Downloader.java" + verbose " - Running Downloader.java ..." + "$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")" +fi + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +if [ -n "${distributionSha256Sum-}" ]; then + distributionSha256Result=false + if [ "$MVN_CMD" = mvnd.sh ]; then + echo "Checksum validation is not supported for maven-mvnd." >&2 + echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + elif command -v sha256sum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c >/dev/null 2>&1; then + distributionSha256Result=true + fi + elif command -v shasum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c >/dev/null 2>&1; then + distributionSha256Result=true + fi + else + echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2 + echo "Please install either command, or disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + fi + if [ $distributionSha256Result = false ]; then + echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2 + echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2 + exit 1 + fi +fi + +# unzip and move +if command -v unzip >/dev/null; then + unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" || die "failed to unzip" +else + tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar" +fi +printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/mvnw.url" +mv -- "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME" + +clean || : +exec_maven "$@" diff --git a/backend/websocketchat/mvnw.cmd b/backend/websocketchat/mvnw.cmd new file mode 100644 index 0000000000..249bdf3822 --- /dev/null +++ b/backend/websocketchat/mvnw.cmd @@ -0,0 +1,149 @@ +<# : batch portion +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM http://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Apache Maven Wrapper startup batch script, version 3.3.2 +@REM +@REM Optional ENV vars +@REM MVNW_REPOURL - repo url base for downloading maven distribution +@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output +@REM ---------------------------------------------------------------------------- + +@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0) +@SET __MVNW_CMD__= +@SET __MVNW_ERROR__= +@SET __MVNW_PSMODULEP_SAVE=%PSModulePath% +@SET PSModulePath= +@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @( + IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B) +) +@SET PSModulePath=%__MVNW_PSMODULEP_SAVE% +@SET __MVNW_PSMODULEP_SAVE= +@SET __MVNW_ARG0_NAME__= +@SET MVNW_USERNAME= +@SET MVNW_PASSWORD= +@IF NOT "%__MVNW_CMD__%"=="" (%__MVNW_CMD__% %*) +@echo Cannot start maven from wrapper >&2 && exit /b 1 +@GOTO :EOF +: end batch / begin powershell #> + +$ErrorActionPreference = "Stop" +if ($env:MVNW_VERBOSE -eq "true") { + $VerbosePreference = "Continue" +} + +# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties +$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl +if (!$distributionUrl) { + Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" +} + +switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) { + "maven-mvnd-*" { + $USE_MVND = $true + $distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip" + $MVN_CMD = "mvnd.cmd" + break + } + default { + $USE_MVND = $false + $MVN_CMD = $script -replace '^mvnw','mvn' + break + } +} + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +if ($env:MVNW_REPOURL) { + $MVNW_REPO_PATTERN = if ($USE_MVND) { "/org/apache/maven/" } else { "/maven/mvnd/" } + $distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace '^.*'+$MVNW_REPO_PATTERN,'')" +} +$distributionUrlName = $distributionUrl -replace '^.*/','' +$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$','' +$MAVEN_HOME_PARENT = "$HOME/.m2/wrapper/dists/$distributionUrlNameMain" +if ($env:MAVEN_USER_HOME) { + $MAVEN_HOME_PARENT = "$env:MAVEN_USER_HOME/wrapper/dists/$distributionUrlNameMain" +} +$MAVEN_HOME_NAME = ([System.Security.Cryptography.MD5]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join '' +$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME" + +if (Test-Path -Path "$MAVEN_HOME" -PathType Container) { + Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME" + Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" + exit $? +} + +if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) { + Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl" +} + +# prepare tmp dir +$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile +$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir" +$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null +trap { + if ($TMP_DOWNLOAD_DIR.Exists) { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } + } +} + +New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null + +# Download and Install Apache Maven +Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +Write-Verbose "Downloading from: $distributionUrl" +Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +$webclient = New-Object System.Net.WebClient +if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) { + $webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD) +} +[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 +$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum +if ($distributionSha256Sum) { + if ($USE_MVND) { + Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." + } + Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash + if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) { + Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property." + } +} + +# unzip and move +Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null +Rename-Item -Path "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" -NewName $MAVEN_HOME_NAME | Out-Null +try { + Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null +} catch { + if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) { + Write-Error "fail to move MAVEN_HOME" + } +} finally { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } +} + +Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" diff --git a/backend/websocketchat/pom.xml b/backend/websocketchat/pom.xml new file mode 100644 index 0000000000..c30c125e0f --- /dev/null +++ b/backend/websocketchat/pom.xml @@ -0,0 +1,72 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 3.3.4 + + + com.example.backend + websocketchat + 0.0.1-SNAPSHOT + websocketchat + WebSocket Chat Service + + + + + + + + + + + + + + + 17 + + + + org.springframework.boot + spring-boot-starter-websocket + + + + org.springframework.kafka + spring-kafka + + + + org.springframework.boot + spring-boot-starter-test + test + + + + org.springframework.kafka + spring-kafka-test + test + + + + org.projectlombok + lombok + 1.18.20 + provided + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/backend/websocketchat/src/main/java/com/example/backend/websocket/.LCKWebSocketChatService.java~ b/backend/websocketchat/src/main/java/com/example/backend/websocket/.LCKWebSocketChatService.java~ new file mode 100644 index 0000000000..e6e1a83612 --- /dev/null +++ b/backend/websocketchat/src/main/java/com/example/backend/websocket/.LCKWebSocketChatService.java~ @@ -0,0 +1 @@ +/Users/mai/Projects/CS3219/cs3219-ay2425s1-project-g15/backend/websocketChat/src/main/java/com/example/backend/websocket/WebSocketChatService.java \ No newline at end of file diff --git a/backend/websocketchat/src/main/java/com/example/backend/websocketchat/WebSocketChatService.java b/backend/websocketchat/src/main/java/com/example/backend/websocketchat/WebSocketChatService.java new file mode 100644 index 0000000000..008dbec153 --- /dev/null +++ b/backend/websocketchat/src/main/java/com/example/backend/websocketchat/WebSocketChatService.java @@ -0,0 +1,41 @@ +package com.example.backend.websocketchat; + +import org.springframework.messaging.simp.SimpMessagingTemplate; +import org.springframework.messaging.simp.user.SimpUser; +import org.springframework.messaging.simp.user.SimpUserRegistry; +import org.springframework.stereotype.Service; + +import com.example.backend.websocketchat.model.MessageForwarded; + +@Service +public class WebSocketChatService { + + private final SimpMessagingTemplate messagingTemplate; + private final SimpUserRegistry userRegistry; + + public WebSocketChatService(SimpMessagingTemplate messagingTemplate, SimpUserRegistry userRegistry) { + this.messagingTemplate = messagingTemplate; + this.userRegistry = userRegistry; + } + + public void sendToCurrentUser(String topic, MessageForwarded message) { + String senderId = message.getSenderId(); + System.out.println("Sending message " + message.toString() + " to sender " + senderId); + messagingTemplate.convertAndSendToUser(senderId, topic, message); + } + + public void sendToOtherUser(String topic, MessageForwarded message) { + String recipientId = message.getRecipientId(); + boolean targetUserConnected = userRegistry.getUsers().stream() + .map(SimpUser::getName) + .anyMatch(senderId -> senderId.equals(recipientId)); + + if (targetUserConnected) { + System.out.println("Sending message " + message.toString() + " to " + recipientId); + System.out.println("Topic is " + topic); + messagingTemplate.convertAndSendToUser(recipientId, topic, message); + } else { + System.out.println("User " + recipientId + " is not connected."); + } + } +} diff --git a/backend/websocketchat/src/main/java/com/example/backend/websocketchat/WebsocketChatApplication.java b/backend/websocketchat/src/main/java/com/example/backend/websocketchat/WebsocketChatApplication.java new file mode 100644 index 0000000000..4c0aed388a --- /dev/null +++ b/backend/websocketchat/src/main/java/com/example/backend/websocketchat/WebsocketChatApplication.java @@ -0,0 +1,13 @@ +package com.example.backend.websocketchat; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class WebsocketChatApplication { + + public static void main(String[] args) { + SpringApplication.run(WebsocketChatApplication.class, args); + } + +} diff --git a/backend/websocketchat/src/main/java/com/example/backend/websocketchat/config/ChatUserPrincipal.java b/backend/websocketchat/src/main/java/com/example/backend/websocketchat/config/ChatUserPrincipal.java new file mode 100644 index 0000000000..6d65c33810 --- /dev/null +++ b/backend/websocketchat/src/main/java/com/example/backend/websocketchat/config/ChatUserPrincipal.java @@ -0,0 +1,45 @@ +package com.example.backend.websocketchat.config; + +import java.io.Serializable; +import java.security.Principal; + +import lombok.Data; + +@Data +public class ChatUserPrincipal implements Principal, Serializable { + private final String senderId; + + public ChatUserPrincipal(String senderId) { + if (senderId == null) { + throw new NullPointerException("null name is illegal"); + } + this.senderId = senderId; + } + + @Override + public String getName() { + return this.senderId; + } + + // @Override + // public boolean equals(Object obj) { + // if (this == obj) { + // return true; + // } + // if (obj instanceof ChatUserPrincipal) { + // ChatUserPrincipal other = (ChatUserPrincipal) obj; + // return this.userWSID.equals(other.getName()); + // } + // return false; + // } + + // @Override + // public int hashCode() { + // return this.userWSID.hashCode(); + // } + + @Override + public String toString() { + return "ChatUserPrincipal{SenderId='" + this.senderId + "'}"; + } +} diff --git a/backend/websocketchat/src/main/java/com/example/backend/websocketchat/config/UserHandshakeHandler.java b/backend/websocketchat/src/main/java/com/example/backend/websocketchat/config/UserHandshakeHandler.java new file mode 100644 index 0000000000..c626a9a507 --- /dev/null +++ b/backend/websocketchat/src/main/java/com/example/backend/websocketchat/config/UserHandshakeHandler.java @@ -0,0 +1,27 @@ +package com.example.backend.websocketchat.config; + +import java.security.Principal; +import java.util.Map; + +import org.springframework.http.server.ServerHttpRequest; +import org.springframework.web.socket.WebSocketHandler; +import org.springframework.web.socket.server.support.DefaultHandshakeHandler; +import org.springframework.web.util.UriComponentsBuilder; + + +public class UserHandshakeHandler extends DefaultHandshakeHandler{ + @Override + protected Principal determineUser(ServerHttpRequest request, WebSocketHandler wsHandler, + Map attributes) { + + String query = request.getURI().getQuery(); + String senderId = UriComponentsBuilder.fromUriString("?" + query) + .build() + .getQueryParams() + .getFirst("senderId"); + if (senderId == null || senderId.isEmpty()) { + throw new IllegalArgumentException("senderId is required as a query parameter"); + } + return new ChatUserPrincipal(senderId); + } +} diff --git a/backend/websocketchat/src/main/java/com/example/backend/websocketchat/config/WebSocketChatConfig.java b/backend/websocketchat/src/main/java/com/example/backend/websocketchat/config/WebSocketChatConfig.java new file mode 100644 index 0000000000..494af5bd02 --- /dev/null +++ b/backend/websocketchat/src/main/java/com/example/backend/websocketchat/config/WebSocketChatConfig.java @@ -0,0 +1,65 @@ +package com.example.backend.websocketchat.config; + +import org.springframework.context.annotation.Configuration; +import org.springframework.messaging.Message; +import org.springframework.messaging.MessageChannel; +import org.springframework.messaging.simp.config.ChannelRegistration; +import org.springframework.messaging.simp.config.MessageBrokerRegistry; +import org.springframework.messaging.simp.stomp.StompCommand; +import org.springframework.messaging.simp.stomp.StompHeaderAccessor; +import org.springframework.messaging.support.ChannelInterceptor; +import org.springframework.messaging.support.MessageHeaderAccessor; +import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker; +import org.springframework.web.socket.config.annotation.StompEndpointRegistry; +import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer; + + +@Configuration +@EnableWebSocketMessageBroker +public class WebSocketChatConfig implements WebSocketMessageBrokerConfigurer { + private final String allowedOrigin = System.getenv("FRONTEND_CORS_ALLOWED_ORIGINS"); + // private final String allowedOrigin = "*"; + + @Override + public void registerStompEndpoints(StompEndpointRegistry registry) { + // HTTP URL for the WebSocket connection used by the client + registry.addEndpoint("/chat-websocket") + .setAllowedOriginPatterns("http://localhost:3000") + .setHandshakeHandler(new UserHandshakeHandler()) + .withSockJS(); + } + + @Override + public void configureMessageBroker(MessageBrokerRegistry config) { + config.setApplicationDestinationPrefixes("/app"); + config.enableSimpleBroker("/topic", "/queue"); + config.setUserDestinationPrefix("/user"); + } + + // Intercepts messages coming from the client and handles connection and disconnection events + @Override + public void configureClientInboundChannel(ChannelRegistration registration) { + registration.interceptors(new ChannelInterceptor() { + @Override + public Message preSend(Message message, MessageChannel channel) { + StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class); + + if (accessor != null) { + // Handle connection events + if (StompCommand.CONNECT.equals(accessor.getCommand())) { + String connectedUser = accessor.getUser().getName(); + System.out.println("User connected: " + connectedUser); + } + + // Handle disconnection events + if (StompCommand.DISCONNECT.equals(accessor.getCommand())) { + String disconnectedUser = accessor.getUser().getName(); + System.out.println("User disconnected: " + disconnectedUser); + } + } + + return message; + } + }); + } +} diff --git a/backend/websocketchat/src/main/java/com/example/backend/websocketchat/controller/WebSocketChatController.java b/backend/websocketchat/src/main/java/com/example/backend/websocketchat/controller/WebSocketChatController.java new file mode 100644 index 0000000000..67ca30f04a --- /dev/null +++ b/backend/websocketchat/src/main/java/com/example/backend/websocketchat/controller/WebSocketChatController.java @@ -0,0 +1,59 @@ +package com.example.backend.websocketchat.controller; + +import java.security.Principal; +import java.time.OffsetDateTime; +import java.time.ZoneId; +import java.time.ZonedDateTime; + +import org.springframework.messaging.handler.annotation.MessageMapping; +import org.springframework.stereotype.Controller; + +import com.example.backend.websocketchat.WebSocketChatService; +import com.example.backend.websocketchat.config.ChatUserPrincipal; +import com.example.backend.websocketchat.kafka.producers.ChatlogProducer; +import com.example.backend.websocketchat.model.MessageConsumed; +import com.example.backend.websocketchat.model.MessageForwarded; + +@Controller +public class WebSocketChatController { + + private WebSocketChatService webSocketChatService; + private ChatlogProducer chatlogProducer; + + public WebSocketChatController(WebSocketChatService webSocketChatService, ChatlogProducer chatlogProducer) { + this.webSocketChatService = webSocketChatService; + this.chatlogProducer = chatlogProducer; + } + + @MessageMapping("/sendMessage") + public void processSentMessage(MessageConsumed message, Principal principal) { + ChatUserPrincipal userPrincipal = (ChatUserPrincipal) principal; + String senderId = userPrincipal.getName(); // This should return the wsid + System.out.println("Sender ID: " + senderId + " sent message: " + message.toString()); + MessageForwarded forwardedMessage = createForwardedMessage(message, senderId); + + + this.chatlogProducer.sendMessage("CHATLOGS", forwardedMessage); + + this.webSocketChatService.sendToCurrentUser("/queue/chat", forwardedMessage); + this.webSocketChatService.sendToOtherUser("/queue/chat", forwardedMessage); + } + + @MessageMapping("/sendLanguageChange") + public void processLanguageChange(MessageConsumed message, Principal principal) { + ChatUserPrincipal myUserPrincipal = (ChatUserPrincipal) principal; + String senderId = myUserPrincipal.getName(); // This should return the wsid + System.out.println("Sender ID: " + senderId + " sent language change to: " + message.toString()); + + MessageForwarded messageForwarded = createForwardedMessage(message, senderId); + + this.webSocketChatService.sendToOtherUser("/queue/language", messageForwarded); + } + + private MessageForwarded createForwardedMessage(MessageConsumed message, String senderId) { + ZonedDateTime zonedDateTime = ZonedDateTime.now(ZoneId.of("Asia/Singapore")); + OffsetDateTime currDateTime = zonedDateTime.toOffsetDateTime().withNano(0); + + return new MessageForwarded(message.getMessage(), message.getCollabId(), senderId, message.getRecipientId(), currDateTime); + } +} \ No newline at end of file diff --git a/backend/websocketchat/src/main/java/com/example/backend/websocketchat/kafka/producers/ChatlogProducer.java b/backend/websocketchat/src/main/java/com/example/backend/websocketchat/kafka/producers/ChatlogProducer.java new file mode 100644 index 0000000000..ed8bc8da00 --- /dev/null +++ b/backend/websocketchat/src/main/java/com/example/backend/websocketchat/kafka/producers/ChatlogProducer.java @@ -0,0 +1,16 @@ +package com.example.backend.websocketchat.kafka.producers; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.kafka.core.KafkaTemplate; +import org.springframework.stereotype.Component; + +@Component +public class ChatlogProducer { + + @Autowired + private KafkaTemplate kafkaTemplate; + + public void sendMessage(String topic, Object value) { + kafkaTemplate.send(topic, value); + } +} diff --git a/backend/websocketchat/src/main/java/com/example/backend/websocketchat/model/MessageConsumed.java b/backend/websocketchat/src/main/java/com/example/backend/websocketchat/model/MessageConsumed.java new file mode 100644 index 0000000000..fdf25d0db2 --- /dev/null +++ b/backend/websocketchat/src/main/java/com/example/backend/websocketchat/model/MessageConsumed.java @@ -0,0 +1,28 @@ +package com.example.backend.websocketchat.model; + +import lombok.Data; + +@Data +public class MessageConsumed { + private String message; + private String collabId; + private String recipientId; + + public MessageConsumed(String message, String collabID, String targetID) { + this.message = message; + this.collabId = collabID; + this.recipientId = targetID; + } + + public String getMessage() { + return this.message; + } + + public String getRecipientId() { + return this.recipientId; + } + + public String getCollabId() { + return this.collabId; + } +} diff --git a/backend/websocketchat/src/main/java/com/example/backend/websocketchat/model/MessageForwarded.java b/backend/websocketchat/src/main/java/com/example/backend/websocketchat/model/MessageForwarded.java new file mode 100644 index 0000000000..a174b3f55a --- /dev/null +++ b/backend/websocketchat/src/main/java/com/example/backend/websocketchat/model/MessageForwarded.java @@ -0,0 +1,44 @@ +package com.example.backend.websocketchat.model; + +import java.time.LocalDateTime; +import java.time.OffsetDateTime; +import java.time.ZonedDateTime; + +import lombok.Data; + +@Data +public class MessageForwarded { + String message; + String collabId; + String recipientId; + String senderId; + OffsetDateTime timestamp; + + public MessageForwarded(String message, String collabId, String senderId, String recipientId, OffsetDateTime timestamp) { + this.message = message; + this.collabId = collabId; + this.senderId = senderId; + this.recipientId = recipientId; + this.timestamp = timestamp; + } + + public OffsetDateTime timestamp() { + return this.timestamp; + } + + public String getSenderId() { + return this.senderId; + } + + public String getMessage() { + return this.message; + } + + public String getCollabId() { + return this.collabId; + } + + public String getRecipientId() { + return this.recipientId; + } +} diff --git a/backend/websocketchat/src/main/resources/application.properties b/backend/websocketchat/src/main/resources/application.properties new file mode 100644 index 0000000000..cc219ad115 --- /dev/null +++ b/backend/websocketchat/src/main/resources/application.properties @@ -0,0 +1,15 @@ +spring.application.name=websocketchat +server.port=3007 + +# Kafka Configuration +spring.kafka.bootstrap-servers=kafka:9092 +spring.kafka.consumer.group-id=chat-service +spring.kafka.consumer.auto-offset-reset=earliest +spring.kafka.consumer.properties.spring.json.trusted.packages=* + +# # Producer and Consumer serializers +spring.kafka.producer.value-serializer=org.springframework.kafka.support.serializer.JsonSerializer +spring.kafka.consumer.value-deserializer=org.springframework.kafka.support.serializer.JsonDeserializer + +# # WebSocket Configuration +# spring.websocket.user-destination-prefix=/user \ No newline at end of file diff --git a/backend/websocketchat/src/main/resources/static/app.js b/backend/websocketchat/src/main/resources/static/app.js new file mode 100644 index 0000000000..2eb52c0e42 --- /dev/null +++ b/backend/websocketchat/src/main/resources/static/app.js @@ -0,0 +1,57 @@ +let stompClient; + +// Add event listeners for buttons +document.getElementById("connectButton").addEventListener("click", connect); +document + .getElementById("sendMessageButton") + .addEventListener("click", sendMatchRequest); + +// Function to connect to the WebSocket server +function connect() { + const socket = new SockJS("/matching-websocket"); // Connect to the WebSocket endpoint + stompClient = Stomp.over(socket); + + stompClient.connect( + {}, + (frame) => { + // Connection successful + console.log("Connected: " + frame); // Add print statement for connection success + alert("WebSocket connection established"); // Optional alert to notify success in UI + + // Subscribe to the user-specific queue for receiving match notifications + stompClient.subscribe("/user/queue/matches", (message) => { + console.log("Received a message from the server: ", message.body); // Add print statement for received messages + document.getElementById( + "messages" + ).innerHTML += `

Received: ${message.body}

`; + }); + }, + (error) => { + // Connection error handling + console.error("WebSocket connection failed: " + error); // Print error if connection fails + alert("WebSocket connection failed. Check console for details."); // Notify user of connection failure + } + ); +} + +// Function to send a test match request through WebSocket +function sendMatchRequest() { + // Create a hardcoded test match request object + const matchRequest = JSON.stringify({ + userEmail: "testuser@example.com", + topics: ["test_topic_1"], + programmingLanguages: ["Java"], + difficulties: ["medium"], + }); + + // Check if stompClient is connected before sending + if (stompClient && stompClient.connected) { + // Send the test match request through the WebSocket + stompClient.send("/app/matchRequest", {}, matchRequest); + console.log("Test match request sent: ", matchRequest); // Add print statement for sent match request + alert("Match request sent successfully"); // Notify the user + } else { + console.error("Cannot send match request: WebSocket is not connected"); + alert("Cannot send match request: WebSocket is not connected"); // Notify user of connection issue + } +} diff --git a/backend/websocketchat/src/main/resources/static/index.html b/backend/websocketchat/src/main/resources/static/index.html new file mode 100644 index 0000000000..c39d899fb8 --- /dev/null +++ b/backend/websocketchat/src/main/resources/static/index.html @@ -0,0 +1,19 @@ + + + + + + WebSocket Test + + + + + +

WebSocket Chat Test

+ + + + +
+ + diff --git a/backend/websocketchat/src/test/java/com/example/backend/websocket/WebsocketApplicationTests.java b/backend/websocketchat/src/test/java/com/example/backend/websocket/WebsocketApplicationTests.java new file mode 100644 index 0000000000..8860edcb00 --- /dev/null +++ b/backend/websocketchat/src/test/java/com/example/backend/websocket/WebsocketApplicationTests.java @@ -0,0 +1,13 @@ +package com.example.backend.websocket; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class WebsocketApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/config/backend-config.yaml b/config/backend-config.yaml new file mode 100644 index 0000000000..bff00022e5 --- /dev/null +++ b/config/backend-config.yaml @@ -0,0 +1,6 @@ +apiVersion: v1 +kind: ConfigMap +metadata: + name: backend-config +data: + # for environment variables \ No newline at end of file diff --git a/config/backend.yaml b/config/backend.yaml new file mode 100644 index 0000000000..fb73abcfab --- /dev/null +++ b/config/backend.yaml @@ -0,0 +1,54 @@ +apiVersion: apps/v1 +kind: Deployment +metadata: + name: backend-deployment + labels: + app: backend +spec: + replicas: 1 + selector: + matchLabels: + app: backend + template: + metadata: + labels: + app: backend + spec: + containers: + - name: collaboration + image: + ports: + - containerPort: 3001 + - name: matching + image: + ports: + - containerPort: 3002 + - name: question + image: + ports: + - containerPort: 3003 + - name: user + image: + ports: + - containerPort: 3004 +--- +apiVersion: v1 +kind: Service +metadata: + name: backend-service +spec: + selector: + app: backend + ports: + - name: port-collaboration + port: 3001 + targetPort: 3001 + - name: port-matching + port: 3002 + targetPort: 3002 + - name: port-question + port: 3003 + targetPort: 3003 + - name: port-user + port: 3004 + targetPort: 3004 \ No newline at end of file diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000000..cd90173a18 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,171 @@ +version: "3.8" + +services: + zookeeper: + image: confluentinc/cp-zookeeper:7.7.1 + container_name: zookeeper + platform: linux/arm64 + ports: + - "2181:2181" + environment: + ZOOKEEPER_CLIENT_PORT: 2181 + ZOOKEEPER_TICK_TIME: 2000 + networks: + - peer-prep-network + + kafka: + image: confluentinc/cp-kafka:7.7.1 + container_name: broker + platform: linux/arm64 + ports: + - "9092:9092" + environment: + KAFKA_BROKER_ID: 1 + KAFKA_ZOOKEEPER_CONNECT: "zookeeper:2181" + KAFKA_LISTENERS: PLAINTEXT://kafka:9092 + KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://kafka:9092 + KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1 + depends_on: + - zookeeper + restart: always + networks: + - peer-prep-network + + matching: + build: ./backend/matching + container_name: matching-container + ports: + - "3002:3002" + env_file: + - ./backend/matching/.env + volumes: + - ./backend/matching/src:/app/src + depends_on: + - kafka + networks: + - peer-prep-network + + matchverification: + build: ./backend/matchverification + container_name: match-verification-container + ports: + - "3006:3006" + env_file: + - ./backend/matchverification/.env + volumes: + - ./backend/matchverification/src:/app/src + depends_on: + - matching + networks: + - peer-prep-network + + collaboration: + build: ./backend/collaboration + container_name: collaboration-container + ports: + - "3001:3001" + volumes: + - ./backend/collaboration:/app + - /app/node_modules + env_file: + - ./backend/collaboration/.env + networks: + - peer-prep-network + + signaling: + build: ./backend/signaling + container_name: signaling-container + ports: + - "4444:4444" + volumes: + - ./backend/signaling:/app + - /app/node_modules + networks: + - peer-prep-network + + websocket: + build: ./backend/websocket + container_name: websocket-container + ports: + - "3005:3005" + env_file: + - ./backend/websocket/.env + volumes: + - ./backend/websocket/src:/app/src + networks: + - peer-prep-network + + websocketchat: + build: ./backend/websocketchat + container_name: websocket-chat-container + ports: + - "3007:3007" + env_file: + - ./backend/websocketchat/.env + volumes: + - ./backend/websocketchat/src:/app/src + networks: + - peer-prep-network + + chatlog: + build: ./backend/chatlog + container_name: chatlog + ports: + - "3008:3008" + env_file: + - ./backend/chatlog/.env + volumes: + - ./backend/chatlog:/usr/src/app + - /usr/src/app/node_modules + networks: + - peer-prep-network + + redis: + image: redis:6.2.6 + container_name: redis-container + ports: + - "6379:6379" + networks: + - peer-prep-network + + question: + build: ./backend/question + container_name: question-container + ports: + - "3003:3003" + volumes: + - ./backend/question:/app + - /app/node_modules + env_file: + - ./backend/question/.env + networks: + - peer-prep-network + + user: + build: ./backend/user + container_name: user-container + ports: + - "3004:3004" + volumes: + - ./backend/user:/app + - /app/node_modules + env_file: + - ./backend/user/.env + networks: + - peer-prep-network + + mongo: + image: mongo + container_name: mongo-container + ports: + - "27017:27017" + volumes: + - mongo-data:/data/db + networks: + - peer-prep-network + +volumes: + mongo-data: + +networks: + peer-prep-network: diff --git a/frontend/.eslintrc.json b/frontend/.eslintrc.json new file mode 100644 index 0000000000..3722418549 --- /dev/null +++ b/frontend/.eslintrc.json @@ -0,0 +1,3 @@ +{ + "extends": ["next/core-web-vitals", "next/typescript"] +} diff --git a/frontend/.gitignore b/frontend/.gitignore new file mode 100644 index 0000000000..fd3dbb571a --- /dev/null +++ b/frontend/.gitignore @@ -0,0 +1,36 @@ +# See https://help.github.com/articles/ignoring-files/ for more about ignoring files. + +# dependencies +/node_modules +/.pnp +.pnp.js +.yarn/install-state.gz + +# testing +/coverage + +# next.js +/.next/ +/out/ + +# production +/build + +# misc +.DS_Store +*.pem + +# debug +npm-debug.log* +yarn-debug.log* +yarn-error.log* + +# local env files +.env*.local + +# vercel +.vercel + +# typescript +*.tsbuildinfo +next-env.d.ts diff --git a/frontend/README.md b/frontend/README.md new file mode 100644 index 0000000000..e215bc4ccf --- /dev/null +++ b/frontend/README.md @@ -0,0 +1,36 @@ +This is a [Next.js](https://nextjs.org) project bootstrapped with [`create-next-app`](https://nextjs.org/docs/app/api-reference/cli/create-next-app). + +## Getting Started + +First, run the development server: + +```bash +npm run dev +# or +yarn dev +# or +pnpm dev +# or +bun dev +``` + +Open [http://localhost:3000](http://localhost:3000) with your browser to see the result. + +You can start editing the page by modifying `app/page.tsx`. The page auto-updates as you edit the file. + +This project uses [`next/font`](https://nextjs.org/docs/app/building-your-application/optimizing/fonts) to automatically optimize and load [Geist](https://vercel.com/font), a new font family for Vercel. + +## Learn More + +To learn more about Next.js, take a look at the following resources: + +- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API. +- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial. + +You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js) - your feedback and contributions are welcome! + +## Deploy on Vercel + +The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js. + +Check out our [Next.js deployment documentation](https://nextjs.org/docs/app/building-your-application/deploying) for more details. diff --git a/frontend/components.json b/frontend/components.json new file mode 100644 index 0000000000..7b2ac28eea --- /dev/null +++ b/frontend/components.json @@ -0,0 +1,20 @@ +{ + "$schema": "https://ui.shadcn.com/schema.json", + "style": "default", + "rsc": true, + "tsx": true, + "tailwind": { + "config": "tailwind.config.ts", + "css": "src/app/globals.css", + "baseColor": "neutral", + "cssVariables": true, + "prefix": "" + }, + "aliases": { + "components": "@/components", + "utils": "@/lib/utils", + "ui": "@/components/ui", + "lib": "@/lib", + "hooks": "@/hooks" + } +} \ No newline at end of file diff --git a/frontend/next.config.mjs b/frontend/next.config.mjs new file mode 100644 index 0000000000..5d7b8bc728 --- /dev/null +++ b/frontend/next.config.mjs @@ -0,0 +1,7 @@ +/** @type {import('next').NextConfig} */ +const nextConfig = { + reactStrictMode: false, + transpilePackages: ["react-icons"], +}; + +export default nextConfig; diff --git a/frontend/package-lock.json b/frontend/package-lock.json new file mode 100644 index 0000000000..922c220950 --- /dev/null +++ b/frontend/package-lock.json @@ -0,0 +1,9069 @@ +{ + "name": "frontend", + "version": "0.1.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "frontend", + "version": "0.1.0", + "dependencies": { + "@hookform/resolvers": "^3.9.0", + "@monaco-editor/react": "^4.6.0", + "@next/font": "^14.2.13", + "@radix-ui/react-checkbox": "^1.1.1", + "@radix-ui/react-dialog": "^1.1.1", + "@radix-ui/react-dropdown-menu": "^2.1.1", + "@radix-ui/react-label": "^2.1.0", + "@radix-ui/react-popover": "^1.1.1", + "@radix-ui/react-select": "^2.1.1", + "@radix-ui/react-separator": "^1.1.0", + "@radix-ui/react-slot": "^1.1.0", + "@radix-ui/react-tooltip": "^1.1.3", + "@react-oauth/google": "^0.12.1", + "@stomp/stompjs": "^7.0.0", + "@tanstack/react-table": "^8.20.5", + "class-variance-authority": "^0.7.0", + "clsx": "^2.1.1", + "cmdk": "^1.0.0", + "date-fns": "^4.1.0", + "dotenv": "^16.4.5", + "framer-motion": "^11.9.0", + "js-base64": "^3.7.7", + "js-cookie": "^3.0.5", + "lucide-react": "^0.445.0", + "next": "14.2.11", + "oidc-client-ts": "^3.1.0", + "react": "^18", + "react-chat-elements": "^12.0.16", + "react-dom": "^18", + "react-hook-form": "^7.53.0", + "react-icons": "^5.3.0", + "react-modal": "^3.16.1", + "react-pro-sidebar": "^1.1.0", + "react-resizable-panels": "^2.1.6", + "react-select": "^5.8.2", + "react-spinners": "^0.14.1", + "react-syntax-highlighter": "^15.5.0", + "resize-observer-polyfill": "^1.5.1", + "shiki": "^1.22.2", + "sockjs-client": "^1.6.1", + "sweetalert2": "^11.14.1", + "tailwind-merge": "^2.5.2", + "tailwindcss-animate": "^1.0.7", + "uuid": "^10.0.0", + "y-monaco": "^0.1.6", + "y-webrtc": "^10.3.0", + "yjs": "^13.6.20", + "zod": "^3.23.8" + }, + "devDependencies": { + "@shikijs/monaco": "^1.22.2", + "@types/js-cookie": "^3.0.6", + "@types/node": "^20", + "@types/react": "^18", + "@types/react-dom": "^18", + "@types/react-modal": "^3.16.3", + "@types/react-syntax-highlighter": "^15.5.13", + "@types/sockjs-client": "^1.5.4", + "eslint": "^8", + "eslint-config-next": "14.2.11", + "postcss": "^8", + "tailwindcss": "^3.4.1", + "typescript": "^5" + } + }, + "node_modules/@alloc/quick-lru": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/@alloc/quick-lru/-/quick-lru-5.2.0.tgz", + "integrity": "sha512-UrcABB+4bUrFABwbluTIBErXwvbsU/V7TZWfmbgJfbkwiBuziS9gxdODUyuiecfdGQ85jglMW6juS3+z5TsKLw==", + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/@babel/code-frame": { + "version": "7.24.7", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.24.7.tgz", + "integrity": "sha512-BcYH1CVJBO9tvyIZ2jVeXgSIMvGZ2FDRvDdOIVQyuklNKSsx+eppDEBq/g47Ayw+RqNFE+URvOShmf+f/qwAlA==", + "license": "MIT", + "dependencies": { + "@babel/highlight": "^7.24.7", + "picocolors": "^1.0.0" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/generator": { + "version": "7.25.6", + "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.25.6.tgz", + "integrity": "sha512-VPC82gr1seXOpkjAAKoLhP50vx4vGNlF4msF64dSFq1P8RfB+QAuJWGHPXXPc8QyfVWwwB/TNNU4+ayZmHNbZw==", + "license": "MIT", + "dependencies": { + "@babel/types": "^7.25.6", + "@jridgewell/gen-mapping": "^0.3.5", + "@jridgewell/trace-mapping": "^0.3.25", + "jsesc": "^2.5.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-module-imports": { + "version": "7.24.7", + "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.24.7.tgz", + "integrity": "sha512-8AyH3C+74cgCVVXow/myrynrAGv+nTVg5vKu2nZph9x7RcRwzmh0VFallJuFTZ9mx6u4eSdXZfcOzSqTUm0HCA==", + "license": "MIT", + "dependencies": { + "@babel/traverse": "^7.24.7", + "@babel/types": "^7.24.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-string-parser": { + "version": "7.24.8", + "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.24.8.tgz", + "integrity": "sha512-pO9KhhRcuUyGnJWwyEgnRJTSIZHiT+vMD0kPeD+so0l7mxkMT19g3pjY9GTnHySck/hDzq+dtW/4VgnMkippsQ==", + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-identifier": { + "version": "7.24.7", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.24.7.tgz", + "integrity": "sha512-rR+PBcQ1SMQDDyF6X0wxtG8QyLCgUB0eRAGguqRLfkCA87l7yAP7ehq8SNj96OOGTO8OBV70KhuFYcIkHXOg0w==", + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/highlight": { + "version": "7.24.7", + "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.24.7.tgz", + "integrity": "sha512-EStJpq4OuY8xYfhGVXngigBJRWxftKX9ksiGDnmlY3o7B/V7KIAc9X4oiK87uPJSc/vs5L869bem5fhZa8caZw==", + "license": "MIT", + "dependencies": { + "@babel/helper-validator-identifier": "^7.24.7", + "chalk": "^2.4.2", + "js-tokens": "^4.0.0", + "picocolors": "^1.0.0" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/highlight/node_modules/ansi-styles": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", + "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", + "license": "MIT", + "dependencies": { + "color-convert": "^1.9.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/@babel/highlight/node_modules/chalk": { + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", + "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", + "license": "MIT", + "dependencies": { + "ansi-styles": "^3.2.1", + "escape-string-regexp": "^1.0.5", + "supports-color": "^5.3.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/@babel/highlight/node_modules/color-convert": { + "version": "1.9.3", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz", + "integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==", + "license": "MIT", + "dependencies": { + "color-name": "1.1.3" + } + }, + "node_modules/@babel/highlight/node_modules/color-name": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz", + "integrity": "sha512-72fSenhMw2HZMTVHeCA9KCmpEIbzWiQsjN+BHcBbS9vr1mtt+vJjPdksIBNUmKAW8TFUDPJK5SUU3QhE9NEXDw==", + "license": "MIT" + }, + "node_modules/@babel/highlight/node_modules/escape-string-regexp": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", + "integrity": "sha512-vbRorB5FUQWvla16U8R/qgaFIya2qGzwDrNmCZuYKrbdSUMG6I1ZCGQRefkRVhuOkIGVne7BQ35DSfo1qvJqFg==", + "license": "MIT", + "engines": { + "node": ">=0.8.0" + } + }, + "node_modules/@babel/highlight/node_modules/has-flag": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", + "integrity": "sha512-sKJf1+ceQBr4SMkvQnBDNDtf4TXpVhVGateu0t918bl30FnbE2m4vNLX+VWe/dpjlb+HugGYzW7uQXH98HPEYw==", + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/@babel/highlight/node_modules/supports-color": { + "version": "5.5.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", + "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", + "license": "MIT", + "dependencies": { + "has-flag": "^3.0.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/@babel/parser": { + "version": "7.25.6", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.25.6.tgz", + "integrity": "sha512-trGdfBdbD0l1ZPmcJ83eNxB9rbEax4ALFTF7fN386TMYbeCQbyme5cOEXQhbGXKebwGaB/J52w1mrklMcbgy6Q==", + "license": "MIT", + "dependencies": { + "@babel/types": "^7.25.6" + }, + "bin": { + "parser": "bin/babel-parser.js" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@babel/runtime": { + "version": "7.25.6", + "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.25.6.tgz", + "integrity": "sha512-VBj9MYyDb9tuLq7yzqjgzt6Q+IBQLrGZfdjOekyEirZPHxXWoTSGUTMrpsfi58Up73d13NfYLv8HT9vmznjzhQ==", + "license": "MIT", + "dependencies": { + "regenerator-runtime": "^0.14.0" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/template": { + "version": "7.25.0", + "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.25.0.tgz", + "integrity": "sha512-aOOgh1/5XzKvg1jvVz7AVrx2piJ2XBi227DHmbY6y+bM9H2FlN+IfecYu4Xl0cNiiVejlsCri89LUsbj8vJD9Q==", + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.24.7", + "@babel/parser": "^7.25.0", + "@babel/types": "^7.25.0" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/traverse": { + "version": "7.25.6", + "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.25.6.tgz", + "integrity": "sha512-9Vrcx5ZW6UwK5tvqsj0nGpp/XzqthkT0dqIc9g1AdtygFToNtTF67XzYS//dm+SAK9cp3B9R4ZO/46p63SCjlQ==", + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.24.7", + "@babel/generator": "^7.25.6", + "@babel/parser": "^7.25.6", + "@babel/template": "^7.25.0", + "@babel/types": "^7.25.6", + "debug": "^4.3.1", + "globals": "^11.1.0" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/traverse/node_modules/globals": { + "version": "11.12.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-11.12.0.tgz", + "integrity": "sha512-WOBp/EEGUiIsJSp7wcv/y6MO+lV9UoncWqxuFfm8eBwzWNgyfBd6Gz+IeKQ9jCmyhoH99g15M3T+QaVHFjizVA==", + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/@babel/types": { + "version": "7.25.6", + "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.25.6.tgz", + "integrity": "sha512-/l42B1qxpG6RdfYf343Uw1vmDjeNhneUXtzhojE7pDgfpEypmRhI6j1kr17XCVv4Cgl9HdAiQY2x0GwKm7rWCw==", + "license": "MIT", + "dependencies": { + "@babel/helper-string-parser": "^7.24.8", + "@babel/helper-validator-identifier": "^7.24.7", + "to-fast-properties": "^2.0.0" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@emotion/babel-plugin": { + "version": "11.12.0", + "resolved": "https://registry.npmjs.org/@emotion/babel-plugin/-/babel-plugin-11.12.0.tgz", + "integrity": "sha512-y2WQb+oP8Jqvvclh8Q55gLUyb7UFvgv7eJfsj7td5TToBrIUtPay2kMrZi4xjq9qw2vD0ZR5fSho0yqoFgX7Rw==", + "license": "MIT", + "dependencies": { + "@babel/helper-module-imports": "^7.16.7", + "@babel/runtime": "^7.18.3", + "@emotion/hash": "^0.9.2", + "@emotion/memoize": "^0.9.0", + "@emotion/serialize": "^1.2.0", + "babel-plugin-macros": "^3.1.0", + "convert-source-map": "^1.5.0", + "escape-string-regexp": "^4.0.0", + "find-root": "^1.1.0", + "source-map": "^0.5.7", + "stylis": "4.2.0" + } + }, + "node_modules/@emotion/cache": { + "version": "11.13.1", + "resolved": "https://registry.npmjs.org/@emotion/cache/-/cache-11.13.1.tgz", + "integrity": "sha512-iqouYkuEblRcXmylXIwwOodiEK5Ifl7JcX7o6V4jI3iW4mLXX3dmt5xwBtIkJiQEXFAI+pC8X0i67yiPkH9Ucw==", + "license": "MIT", + "dependencies": { + "@emotion/memoize": "^0.9.0", + "@emotion/sheet": "^1.4.0", + "@emotion/utils": "^1.4.0", + "@emotion/weak-memoize": "^0.4.0", + "stylis": "4.2.0" + } + }, + "node_modules/@emotion/hash": { + "version": "0.9.2", + "resolved": "https://registry.npmjs.org/@emotion/hash/-/hash-0.9.2.tgz", + "integrity": "sha512-MyqliTZGuOm3+5ZRSaaBGP3USLw6+EGykkwZns2EPC5g8jJ4z9OrdZY9apkl3+UP9+sdz76YYkwCKP5gh8iY3g==", + "license": "MIT" + }, + "node_modules/@emotion/is-prop-valid": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/@emotion/is-prop-valid/-/is-prop-valid-1.3.1.tgz", + "integrity": "sha512-/ACwoqx7XQi9knQs/G0qKvv5teDMhD7bXYns9N/wM8ah8iNb8jZ2uNO0YOgiq2o2poIvVtJS2YALasQuMSQ7Kw==", + "license": "MIT", + "dependencies": { + "@emotion/memoize": "^0.9.0" + } + }, + "node_modules/@emotion/memoize": { + "version": "0.9.0", + "resolved": "https://registry.npmjs.org/@emotion/memoize/-/memoize-0.9.0.tgz", + "integrity": "sha512-30FAj7/EoJ5mwVPOWhAyCX+FPfMDrVecJAM+Iw9NRoSl4BBAQeqj4cApHHUXOVvIPgLVDsCFoz/hGD+5QQD1GQ==", + "license": "MIT" + }, + "node_modules/@emotion/react": { + "version": "11.13.3", + "resolved": "https://registry.npmjs.org/@emotion/react/-/react-11.13.3.tgz", + "integrity": "sha512-lIsdU6JNrmYfJ5EbUCf4xW1ovy5wKQ2CkPRM4xogziOxH1nXxBSjpC9YqbFAP7circxMfYp+6x676BqWcEiixg==", + "license": "MIT", + "dependencies": { + "@babel/runtime": "^7.18.3", + "@emotion/babel-plugin": "^11.12.0", + "@emotion/cache": "^11.13.0", + "@emotion/serialize": "^1.3.1", + "@emotion/use-insertion-effect-with-fallbacks": "^1.1.0", + "@emotion/utils": "^1.4.0", + "@emotion/weak-memoize": "^0.4.0", + "hoist-non-react-statics": "^3.3.1" + }, + "peerDependencies": { + "react": ">=16.8.0" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@emotion/serialize": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/@emotion/serialize/-/serialize-1.3.2.tgz", + "integrity": "sha512-grVnMvVPK9yUVE6rkKfAJlYZgo0cu3l9iMC77V7DW6E1DUIrU68pSEXRmFZFOFB1QFo57TncmOcvcbMDWsL4yA==", + "license": "MIT", + "dependencies": { + "@emotion/hash": "^0.9.2", + "@emotion/memoize": "^0.9.0", + "@emotion/unitless": "^0.10.0", + "@emotion/utils": "^1.4.1", + "csstype": "^3.0.2" + } + }, + "node_modules/@emotion/sheet": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/@emotion/sheet/-/sheet-1.4.0.tgz", + "integrity": "sha512-fTBW9/8r2w3dXWYM4HCB1Rdp8NLibOw2+XELH5m5+AkWiL/KqYX6dc0kKYlaYyKjrQ6ds33MCdMPEwgs2z1rqg==", + "license": "MIT" + }, + "node_modules/@emotion/styled": { + "version": "11.13.0", + "resolved": "https://registry.npmjs.org/@emotion/styled/-/styled-11.13.0.tgz", + "integrity": "sha512-tkzkY7nQhW/zC4hztlwucpT8QEZ6eUzpXDRhww/Eej4tFfO0FxQYWRyg/c5CCXa4d/f174kqeXYjuQRnhzf6dA==", + "license": "MIT", + "dependencies": { + "@babel/runtime": "^7.18.3", + "@emotion/babel-plugin": "^11.12.0", + "@emotion/is-prop-valid": "^1.3.0", + "@emotion/serialize": "^1.3.0", + "@emotion/use-insertion-effect-with-fallbacks": "^1.1.0", + "@emotion/utils": "^1.4.0" + }, + "peerDependencies": { + "@emotion/react": "^11.0.0-rc.0", + "react": ">=16.8.0" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@emotion/unitless": { + "version": "0.10.0", + "resolved": "https://registry.npmjs.org/@emotion/unitless/-/unitless-0.10.0.tgz", + "integrity": "sha512-dFoMUuQA20zvtVTuxZww6OHoJYgrzfKM1t52mVySDJnMSEa08ruEvdYQbhvyu6soU+NeLVd3yKfTfT0NeV6qGg==", + "license": "MIT" + }, + "node_modules/@emotion/use-insertion-effect-with-fallbacks": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@emotion/use-insertion-effect-with-fallbacks/-/use-insertion-effect-with-fallbacks-1.1.0.tgz", + "integrity": "sha512-+wBOcIV5snwGgI2ya3u99D7/FJquOIniQT1IKyDsBmEgwvpxMNeS65Oib7OnE2d2aY+3BU4OiH+0Wchf8yk3Hw==", + "license": "MIT", + "peerDependencies": { + "react": ">=16.8.0" + } + }, + "node_modules/@emotion/utils": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/@emotion/utils/-/utils-1.4.1.tgz", + "integrity": "sha512-BymCXzCG3r72VKJxaYVwOXATqXIZ85cuvg0YOUDxMGNrKc1DJRZk8MgV5wyXRyEayIMd4FuXJIUgTBXvDNW5cA==", + "license": "MIT" + }, + "node_modules/@emotion/weak-memoize": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/@emotion/weak-memoize/-/weak-memoize-0.4.0.tgz", + "integrity": "sha512-snKqtPW01tN0ui7yu9rGv69aJXr/a/Ywvl11sUjNtEcRc+ng/mQriFL0wLXMef74iHa/EkftbDzU9F8iFbH+zg==", + "license": "MIT" + }, + "node_modules/@eslint-community/eslint-utils": { + "version": "4.4.0", + "resolved": "https://registry.npmjs.org/@eslint-community/eslint-utils/-/eslint-utils-4.4.0.tgz", + "integrity": "sha512-1/sA4dwrzBAyeUoQ6oxahHKmrZvsnLCg4RfxW3ZFGGmQkSNQPFNLV9CUEFQP1x9EYXHTo5p6xdhZM1Ne9p/AfA==", + "dev": true, + "license": "MIT", + "dependencies": { + "eslint-visitor-keys": "^3.3.0" + }, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "peerDependencies": { + "eslint": "^6.0.0 || ^7.0.0 || >=8.0.0" + } + }, + "node_modules/@eslint-community/regexpp": { + "version": "4.11.1", + "resolved": "https://registry.npmjs.org/@eslint-community/regexpp/-/regexpp-4.11.1.tgz", + "integrity": "sha512-m4DVN9ZqskZoLU5GlWZadwDnYo3vAEydiUayB9widCl9ffWx2IvPnp6n3on5rJmziJSw9Bv+Z3ChDVdMwXCY8Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^12.0.0 || ^14.0.0 || >=16.0.0" + } + }, + "node_modules/@eslint/eslintrc": { + "version": "2.1.4", + "resolved": "https://registry.npmjs.org/@eslint/eslintrc/-/eslintrc-2.1.4.tgz", + "integrity": "sha512-269Z39MS6wVJtsoUl10L60WdkhJVdPG24Q4eZTH3nnF6lpvSShEK3wQjDX9JRWAUPvPh7COouPpU9IrqaZFvtQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "ajv": "^6.12.4", + "debug": "^4.3.2", + "espree": "^9.6.0", + "globals": "^13.19.0", + "ignore": "^5.2.0", + "import-fresh": "^3.2.1", + "js-yaml": "^4.1.0", + "minimatch": "^3.1.2", + "strip-json-comments": "^3.1.1" + }, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/@eslint/js": { + "version": "8.57.1", + "resolved": "https://registry.npmjs.org/@eslint/js/-/js-8.57.1.tgz", + "integrity": "sha512-d9zaMRSTIKDLhctzH12MtXvJKSSUhaHcjV+2Z+GK+EEY7XKpP5yR4x+N3TAcHTcu963nIr+TMcCb4DBCYX1z6Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + } + }, + "node_modules/@floating-ui/core": { + "version": "1.6.8", + "resolved": "https://registry.npmjs.org/@floating-ui/core/-/core-1.6.8.tgz", + "integrity": "sha512-7XJ9cPU+yI2QeLS+FCSlqNFZJq8arvswefkZrYI1yQBbftw6FyrZOxYSh+9S7z7TpeWlRt9zJ5IhM1WIL334jA==", + "license": "MIT", + "dependencies": { + "@floating-ui/utils": "^0.2.8" + } + }, + "node_modules/@floating-ui/dom": { + "version": "1.6.11", + "resolved": "https://registry.npmjs.org/@floating-ui/dom/-/dom-1.6.11.tgz", + "integrity": "sha512-qkMCxSR24v2vGkhYDo/UzxfJN3D4syqSjyuTFz6C7XcpU1pASPRieNI0Kj5VP3/503mOfYiGY891ugBX1GlABQ==", + "license": "MIT", + "dependencies": { + "@floating-ui/core": "^1.6.0", + "@floating-ui/utils": "^0.2.8" + } + }, + "node_modules/@floating-ui/react-dom": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/@floating-ui/react-dom/-/react-dom-2.1.2.tgz", + "integrity": "sha512-06okr5cgPzMNBy+Ycse2A6udMi4bqwW/zgBF/rwjcNqWkyr82Mcg8b0vjX8OJpZFy/FKjJmw6wV7t44kK6kW7A==", + "license": "MIT", + "dependencies": { + "@floating-ui/dom": "^1.0.0" + }, + "peerDependencies": { + "react": ">=16.8.0", + "react-dom": ">=16.8.0" + } + }, + "node_modules/@floating-ui/utils": { + "version": "0.2.8", + "resolved": "https://registry.npmjs.org/@floating-ui/utils/-/utils-0.2.8.tgz", + "integrity": "sha512-kym7SodPp8/wloecOpcmSnWJsK7M0E5Wg8UcFA+uO4B9s5d0ywXOEro/8HM9x0rW+TljRzul/14UYz3TleT3ig==", + "license": "MIT" + }, + "node_modules/@hookform/resolvers": { + "version": "3.9.0", + "resolved": "https://registry.npmjs.org/@hookform/resolvers/-/resolvers-3.9.0.tgz", + "integrity": "sha512-bU0Gr4EepJ/EQsH/IwEzYLsT/PEj5C0ynLQ4m+GSHS+xKH4TfSelhluTgOaoc4kA5s7eCsQbM4wvZLzELmWzUg==", + "license": "MIT", + "peerDependencies": { + "react-hook-form": "^7.0.0" + } + }, + "node_modules/@humanwhocodes/config-array": { + "version": "0.13.0", + "resolved": "https://registry.npmjs.org/@humanwhocodes/config-array/-/config-array-0.13.0.tgz", + "integrity": "sha512-DZLEEqFWQFiyK6h5YIeynKx7JlvCYWL0cImfSRXZ9l4Sg2efkFGTuFf6vzXjK1cq6IYkU+Eg/JizXw+TD2vRNw==", + "deprecated": "Use @eslint/config-array instead", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@humanwhocodes/object-schema": "^2.0.3", + "debug": "^4.3.1", + "minimatch": "^3.0.5" + }, + "engines": { + "node": ">=10.10.0" + } + }, + "node_modules/@humanwhocodes/module-importer": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@humanwhocodes/module-importer/-/module-importer-1.0.1.tgz", + "integrity": "sha512-bxveV4V8v5Yb4ncFTT3rPSgZBOpCkjfK0y4oVVVJwIuDVBRMDXrPyXRL988i5ap9m9bnyEEjWfm5WkBmtffLfA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=12.22" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/nzakas" + } + }, + "node_modules/@humanwhocodes/object-schema": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/@humanwhocodes/object-schema/-/object-schema-2.0.3.tgz", + "integrity": "sha512-93zYdMES/c1D69yZiKDBj0V24vqNzB/koF26KPaagAfd3P/4gUlh3Dys5ogAK+Exi9QyzlD8x/08Zt7wIKcDcA==", + "deprecated": "Use @eslint/object-schema instead", + "dev": true, + "license": "BSD-3-Clause" + }, + "node_modules/@isaacs/cliui": { + "version": "8.0.2", + "resolved": "https://registry.npmjs.org/@isaacs/cliui/-/cliui-8.0.2.tgz", + "integrity": "sha512-O8jcjabXaleOG9DQ0+ARXWZBTfnP4WNAqzuiJK7ll44AmxGKv/J2M4TPjxjY3znBCfvBXFzucm1twdyFybFqEA==", + "license": "ISC", + "dependencies": { + "string-width": "^5.1.2", + "string-width-cjs": "npm:string-width@^4.2.0", + "strip-ansi": "^7.0.1", + "strip-ansi-cjs": "npm:strip-ansi@^6.0.1", + "wrap-ansi": "^8.1.0", + "wrap-ansi-cjs": "npm:wrap-ansi@^7.0.0" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/@isaacs/cliui/node_modules/ansi-regex": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.1.0.tgz", + "integrity": "sha512-7HSX4QQb4CspciLpVFwyRe79O3xsIZDDLER21kERQ71oaPodF8jL725AgJMFAYbooIqolJoRLuM81SpeUkpkvA==", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-regex?sponsor=1" + } + }, + "node_modules/@isaacs/cliui/node_modules/strip-ansi": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.1.0.tgz", + "integrity": "sha512-iq6eVVI64nQQTRYq2KtEg2d2uU7LElhTJwsH4YzIHZshxlgZms/wIc4VoDQTlG/IvVIrBKG06CrZnp0qv7hkcQ==", + "license": "MIT", + "dependencies": { + "ansi-regex": "^6.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/strip-ansi?sponsor=1" + } + }, + "node_modules/@jridgewell/gen-mapping": { + "version": "0.3.5", + "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.5.tgz", + "integrity": "sha512-IzL8ZoEDIBRWEzlCcRhOaCupYyN5gdIK+Q6fbFdPDg6HqX6jpkItn7DFIpW9LQzXG6Df9sA7+OKnq0qlz/GaQg==", + "license": "MIT", + "dependencies": { + "@jridgewell/set-array": "^1.2.1", + "@jridgewell/sourcemap-codec": "^1.4.10", + "@jridgewell/trace-mapping": "^0.3.24" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", + "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==", + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/set-array": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@jridgewell/set-array/-/set-array-1.2.1.tgz", + "integrity": "sha512-R8gLRTZeyp03ymzP/6Lil/28tGeGEzhx1q2k703KGWRAI1VdvPIXdG70VJc2pAMw3NA6JKL5hhFu1sJX0Mnn/A==", + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.0.tgz", + "integrity": "sha512-gv3ZRaISU3fjPAgNsriBRqGWQL6quFx04YMPW/zD8XMLsU32mhCCbfbO6KZFLjvYpCZ8zyDEgqsgf+PwPaM7GQ==", + "license": "MIT" + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.25", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.25.tgz", + "integrity": "sha512-vNk6aEwybGtawWmy/PzwnGDOjCkLWSD2wqvjGGAgOAwCGWySYXfYoxt00IJkTF+8Lb57DwOb3Aa0o9CApepiYQ==", + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, + "node_modules/@monaco-editor/loader": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/@monaco-editor/loader/-/loader-1.4.0.tgz", + "integrity": "sha512-00ioBig0x642hytVspPl7DbQyaSWRaolYie/UFNjoTdvoKPzo6xrXLhTk9ixgIKcLH5b5vDOjVNiGyY+uDCUlg==", + "dependencies": { + "state-local": "^1.0.6" + }, + "peerDependencies": { + "monaco-editor": ">= 0.21.0 < 1" + } + }, + "node_modules/@monaco-editor/react": { + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/@monaco-editor/react/-/react-4.6.0.tgz", + "integrity": "sha512-RFkU9/i7cN2bsq/iTkurMWOEErmYcY6JiQI3Jn+WeR/FGISH8JbHERjpS9oRuSOPvDMJI0Z8nJeKkbOs9sBYQw==", + "license": "MIT", + "dependencies": { + "@monaco-editor/loader": "^1.4.0" + }, + "peerDependencies": { + "monaco-editor": ">= 0.25.0 < 1", + "react": "^16.8.0 || ^17.0.0 || ^18.0.0", + "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0" + } + }, + "node_modules/@next/env": { + "version": "14.2.11", + "resolved": "https://registry.npmjs.org/@next/env/-/env-14.2.11.tgz", + "integrity": "sha512-HYsQRSIXwiNqvzzYThrBwq6RhXo3E0n8j8nQnAs8i4fCEo2Zf/3eS0IiRA8XnRg9Ha0YnpkyJZIZg1qEwemrHw==", + "license": "MIT" + }, + "node_modules/@next/eslint-plugin-next": { + "version": "14.2.11", + "resolved": "https://registry.npmjs.org/@next/eslint-plugin-next/-/eslint-plugin-next-14.2.11.tgz", + "integrity": "sha512-7mw+xW7Y03Ph4NTCcAzYe+vu4BNjEHZUfZayyF3Y1D9RX6c5NIe25m1grHEAkyUuaqjRxOYhnCNeglOkIqLkBA==", + "dev": true, + "license": "MIT", + "dependencies": { + "glob": "10.3.10" + } + }, + "node_modules/@next/font": { + "version": "14.2.13", + "resolved": "https://registry.npmjs.org/@next/font/-/font-14.2.13.tgz", + "integrity": "sha512-xtleJ172yNVSVoQoMIwPHnM9zSPOzNB964mZMOFmRaLWgWMgmlhCVI42dlDSGc6d9nQ/WHCmCZaJMloS1HHGXg==", + "license": "MIT", + "peerDependencies": { + "next": "*" + } + }, + "node_modules/@next/swc-darwin-arm64": { + "version": "14.2.11", + "resolved": "https://registry.npmjs.org/@next/swc-darwin-arm64/-/swc-darwin-arm64-14.2.11.tgz", + "integrity": "sha512-eiY9u7wEJZWp/Pga07Qy3ZmNEfALmmSS1HtsJF3y1QEyaExu7boENz11fWqDmZ3uvcyAxCMhTrA1jfVxITQW8g==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@next/swc-darwin-x64": { + "version": "14.2.11", + "resolved": "https://registry.npmjs.org/@next/swc-darwin-x64/-/swc-darwin-x64-14.2.11.tgz", + "integrity": "sha512-lnB0zYCld4yE0IX3ANrVMmtAbziBb7MYekcmR6iE9bujmgERl6+FK+b0MBq0pl304lYe7zO4yxJus9H/Af8jbg==", + "cpu": [ + "x64" + ], + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@next/swc-linux-arm64-gnu": { + "version": "14.2.11", + "resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-gnu/-/swc-linux-arm64-gnu-14.2.11.tgz", + "integrity": "sha512-Ulo9TZVocYmUAtzvZ7FfldtwUoQY0+9z3BiXZCLSUwU2bp7GqHA7/bqrfsArDlUb2xeGwn3ZuBbKtNK8TR0A8w==", + "cpu": [ + "arm64" + ], + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@next/swc-linux-arm64-musl": { + "version": "14.2.11", + "resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-musl/-/swc-linux-arm64-musl-14.2.11.tgz", + "integrity": "sha512-fH377DnKGyUnkWlmUpFF1T90m0dADBfK11dF8sOQkiELF9M+YwDRCGe8ZyDzvQcUd20Rr5U7vpZRrAxKwd3Rzg==", + "cpu": [ + "arm64" + ], + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@next/swc-linux-x64-gnu": { + "version": "14.2.11", + "resolved": "https://registry.npmjs.org/@next/swc-linux-x64-gnu/-/swc-linux-x64-gnu-14.2.11.tgz", + "integrity": "sha512-a0TH4ZZp4NS0LgXP/488kgvWelNpwfgGTUCDXVhPGH6pInb7yIYNgM4kmNWOxBFt+TIuOH6Pi9NnGG4XWFUyXQ==", + "cpu": [ + "x64" + ], + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@next/swc-linux-x64-musl": { + "version": "14.2.11", + "resolved": "https://registry.npmjs.org/@next/swc-linux-x64-musl/-/swc-linux-x64-musl-14.2.11.tgz", + "integrity": "sha512-DYYZcO4Uir2gZxA4D2JcOAKVs8ZxbOFYPpXSVIgeoQbREbeEHxysVsg3nY4FrQy51e5opxt5mOHl/LzIyZBoKA==", + "cpu": [ + "x64" + ], + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@next/swc-win32-arm64-msvc": { + "version": "14.2.11", + "resolved": "https://registry.npmjs.org/@next/swc-win32-arm64-msvc/-/swc-win32-arm64-msvc-14.2.11.tgz", + "integrity": "sha512-PwqHeKG3/kKfPpM6of1B9UJ+Er6ySUy59PeFu0Un0LBzJTRKKAg2V6J60Yqzp99m55mLa+YTbU6xj61ImTv9mg==", + "cpu": [ + "arm64" + ], + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@next/swc-win32-ia32-msvc": { + "version": "14.2.11", + "resolved": "https://registry.npmjs.org/@next/swc-win32-ia32-msvc/-/swc-win32-ia32-msvc-14.2.11.tgz", + "integrity": "sha512-0U7PWMnOYIvM74GY6rbH6w7v+vNPDVH1gUhlwHpfInJnNe5LkmUZqhp7FNWeNa5wbVgRcRi1F1cyxp4dmeLLvA==", + "cpu": [ + "ia32" + ], + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@next/swc-win32-x64-msvc": { + "version": "14.2.11", + "resolved": "https://registry.npmjs.org/@next/swc-win32-x64-msvc/-/swc-win32-x64-msvc-14.2.11.tgz", + "integrity": "sha512-gQpS7mcgovWoaTG1FbS5/ojF7CGfql1Q0ZLsMrhcsi2Sr9HEqsUZ70MPJyaYBXbk6iEAP7UXMD9HC8KY1qNwvA==", + "cpu": [ + "x64" + ], + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@nodelib/fs.scandir": { + "version": "2.1.5", + "resolved": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz", + "integrity": "sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g==", + "license": "MIT", + "dependencies": { + "@nodelib/fs.stat": "2.0.5", + "run-parallel": "^1.1.9" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/@nodelib/fs.stat": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/@nodelib/fs.stat/-/fs.stat-2.0.5.tgz", + "integrity": "sha512-RkhPPp2zrqDAQA/2jNhnztcPAlv64XdhIp7a7454A5ovI7Bukxgt7MX7udwAu3zg1DcpPU0rz3VV1SeaqvY4+A==", + "license": "MIT", + "engines": { + "node": ">= 8" + } + }, + "node_modules/@nodelib/fs.walk": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/@nodelib/fs.walk/-/fs.walk-1.2.8.tgz", + "integrity": "sha512-oGB+UxlgWcgQkgwo8GcEGwemoTFt3FIO9ababBmaGwXIoBKZ+GTy0pP185beGg7Llih/NSHSV2XAs1lnznocSg==", + "license": "MIT", + "dependencies": { + "@nodelib/fs.scandir": "2.1.5", + "fastq": "^1.6.0" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/@nolyfill/is-core-module": { + "version": "1.0.39", + "resolved": "https://registry.npmjs.org/@nolyfill/is-core-module/-/is-core-module-1.0.39.tgz", + "integrity": "sha512-nn5ozdjYQpUCZlWGuxcJY/KpxkWQs4DcbMCmKojjyrYDEAGy4Ce19NN4v5MduafTwJlbKc99UA8YhSVqq9yPZA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12.4.0" + } + }, + "node_modules/@pkgjs/parseargs": { + "version": "0.11.0", + "resolved": "https://registry.npmjs.org/@pkgjs/parseargs/-/parseargs-0.11.0.tgz", + "integrity": "sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">=14" + } + }, + "node_modules/@popperjs/core": { + "version": "2.11.8", + "resolved": "https://registry.npmjs.org/@popperjs/core/-/core-2.11.8.tgz", + "integrity": "sha512-P1st0aksCrn9sGZhp8GMYwBnQsbvAWsZAX44oXNNvLHGqAOcoVxmjZiohstwQ7SqKnbR47akdNi+uleWD8+g6A==", + "license": "MIT", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/popperjs" + } + }, + "node_modules/@radix-ui/number": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@radix-ui/number/-/number-1.1.0.tgz", + "integrity": "sha512-V3gRzhVNU1ldS5XhAPTom1fOIo4ccrjjJgmE+LI2h/WaFpHmx0MQApT+KZHnx8abG6Avtfcz4WoEciMnpFT3HQ==", + "license": "MIT" + }, + "node_modules/@radix-ui/primitive": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@radix-ui/primitive/-/primitive-1.1.0.tgz", + "integrity": "sha512-4Z8dn6Upk0qk4P74xBhZ6Hd/w0mPEzOOLxy4xiPXOXqjF7jZS0VAKk7/x/H6FyY2zCkYJqePf1G5KmkmNJ4RBA==", + "license": "MIT" + }, + "node_modules/@radix-ui/react-arrow": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-arrow/-/react-arrow-1.1.0.tgz", + "integrity": "sha512-FmlW1rCg7hBpEBwFbjHwCW6AmWLQM6g/v0Sn8XbP9NvmSZ2San1FpQeyPtufzOMSIx7Y4dzjlHoifhp+7NkZhw==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-primitive": "2.0.0" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-checkbox": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@radix-ui/react-checkbox/-/react-checkbox-1.1.1.tgz", + "integrity": "sha512-0i/EKJ222Afa1FE0C6pNJxDq1itzcl3HChE9DwskA4th4KRse8ojx8a1nVcOjwJdbpDLcz7uol77yYnQNMHdKw==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.1.0", + "@radix-ui/react-compose-refs": "1.1.0", + "@radix-ui/react-context": "1.1.0", + "@radix-ui/react-presence": "1.1.0", + "@radix-ui/react-primitive": "2.0.0", + "@radix-ui/react-use-controllable-state": "1.1.0", + "@radix-ui/react-use-previous": "1.1.0", + "@radix-ui/react-use-size": "1.1.0" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-collection": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-collection/-/react-collection-1.1.0.tgz", + "integrity": "sha512-GZsZslMJEyo1VKm5L1ZJY8tGDxZNPAoUeQUIbKeJfoi7Q4kmig5AsgLMYYuyYbfjd8fBmFORAIwYAkXMnXZgZw==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-compose-refs": "1.1.0", + "@radix-ui/react-context": "1.1.0", + "@radix-ui/react-primitive": "2.0.0", + "@radix-ui/react-slot": "1.1.0" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-compose-refs": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-compose-refs/-/react-compose-refs-1.1.0.tgz", + "integrity": "sha512-b4inOtiaOnYf9KWyO3jAeeCG6FeyfY6ldiEPanbUjWd+xIk5wZeHa8yVwmrJ2vderhu/BQvzCrJI0lHd+wIiqw==", + "license": "MIT", + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-context": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-context/-/react-context-1.1.0.tgz", + "integrity": "sha512-OKrckBy+sMEgYM/sMmqmErVn0kZqrHPJze+Ql3DzYsDDp0hl0L62nx/2122/Bvps1qz645jlcu2tD9lrRSdf8A==", + "license": "MIT", + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-dialog": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@radix-ui/react-dialog/-/react-dialog-1.1.1.tgz", + "integrity": "sha512-zysS+iU4YP3STKNS6USvFVqI4qqx8EpiwmT5TuCApVEBca+eRCbONi4EgzfNSuVnOXvC5UPHHMjs8RXO6DH9Bg==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.1.0", + "@radix-ui/react-compose-refs": "1.1.0", + "@radix-ui/react-context": "1.1.0", + "@radix-ui/react-dismissable-layer": "1.1.0", + "@radix-ui/react-focus-guards": "1.1.0", + "@radix-ui/react-focus-scope": "1.1.0", + "@radix-ui/react-id": "1.1.0", + "@radix-ui/react-portal": "1.1.1", + "@radix-ui/react-presence": "1.1.0", + "@radix-ui/react-primitive": "2.0.0", + "@radix-ui/react-slot": "1.1.0", + "@radix-ui/react-use-controllable-state": "1.1.0", + "aria-hidden": "^1.1.1", + "react-remove-scroll": "2.5.7" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-direction": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-direction/-/react-direction-1.1.0.tgz", + "integrity": "sha512-BUuBvgThEiAXh2DWu93XsT+a3aWrGqolGlqqw5VU1kG7p/ZH2cuDlM1sRLNnY3QcBS69UIz2mcKhMxDsdewhjg==", + "license": "MIT", + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-dismissable-layer": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-dismissable-layer/-/react-dismissable-layer-1.1.0.tgz", + "integrity": "sha512-/UovfmmXGptwGcBQawLzvn2jOfM0t4z3/uKffoBlj724+n3FvBbZ7M0aaBOmkp6pqFYpO4yx8tSVJjx3Fl2jig==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.1.0", + "@radix-ui/react-compose-refs": "1.1.0", + "@radix-ui/react-primitive": "2.0.0", + "@radix-ui/react-use-callback-ref": "1.1.0", + "@radix-ui/react-use-escape-keydown": "1.1.0" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-dropdown-menu": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/@radix-ui/react-dropdown-menu/-/react-dropdown-menu-2.1.1.tgz", + "integrity": "sha512-y8E+x9fBq9qvteD2Zwa4397pUVhYsh9iq44b5RD5qu1GMJWBCBuVg1hMyItbc6+zH00TxGRqd9Iot4wzf3OoBQ==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.1.0", + "@radix-ui/react-compose-refs": "1.1.0", + "@radix-ui/react-context": "1.1.0", + "@radix-ui/react-id": "1.1.0", + "@radix-ui/react-menu": "2.1.1", + "@radix-ui/react-primitive": "2.0.0", + "@radix-ui/react-use-controllable-state": "1.1.0" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-focus-guards": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-focus-guards/-/react-focus-guards-1.1.0.tgz", + "integrity": "sha512-w6XZNUPVv6xCpZUqb/yN9DL6auvpGX3C/ee6Hdi16v2UUy25HV2Q5bcflsiDyT/g5RwbPQ/GIT1vLkeRb+ITBw==", + "license": "MIT", + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-focus-scope": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-focus-scope/-/react-focus-scope-1.1.0.tgz", + "integrity": "sha512-200UD8zylvEyL8Bx+z76RJnASR2gRMuxlgFCPAe/Q/679a/r0eK3MBVYMb7vZODZcffZBdob1EGnky78xmVvcA==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-compose-refs": "1.1.0", + "@radix-ui/react-primitive": "2.0.0", + "@radix-ui/react-use-callback-ref": "1.1.0" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-id": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-id/-/react-id-1.1.0.tgz", + "integrity": "sha512-EJUrI8yYh7WOjNOqpoJaf1jlFIH2LvtgAl+YcFqNCa+4hj64ZXmPkAKOFs/ukjz3byN6bdb/AVUqHkI8/uWWMA==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-use-layout-effect": "1.1.0" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-label": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-label/-/react-label-2.1.0.tgz", + "integrity": "sha512-peLblDlFw/ngk3UWq0VnYaOLy6agTZZ+MUO/WhVfm14vJGML+xH4FAl2XQGLqdefjNb7ApRg6Yn7U42ZhmYXdw==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-primitive": "2.0.0" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-menu": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/@radix-ui/react-menu/-/react-menu-2.1.1.tgz", + "integrity": "sha512-oa3mXRRVjHi6DZu/ghuzdylyjaMXLymx83irM7hTxutQbD+7IhPKdMdRHD26Rm+kHRrWcrUkkRPv5pd47a2xFQ==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.1.0", + "@radix-ui/react-collection": "1.1.0", + "@radix-ui/react-compose-refs": "1.1.0", + "@radix-ui/react-context": "1.1.0", + "@radix-ui/react-direction": "1.1.0", + "@radix-ui/react-dismissable-layer": "1.1.0", + "@radix-ui/react-focus-guards": "1.1.0", + "@radix-ui/react-focus-scope": "1.1.0", + "@radix-ui/react-id": "1.1.0", + "@radix-ui/react-popper": "1.2.0", + "@radix-ui/react-portal": "1.1.1", + "@radix-ui/react-presence": "1.1.0", + "@radix-ui/react-primitive": "2.0.0", + "@radix-ui/react-roving-focus": "1.1.0", + "@radix-ui/react-slot": "1.1.0", + "@radix-ui/react-use-callback-ref": "1.1.0", + "aria-hidden": "^1.1.1", + "react-remove-scroll": "2.5.7" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-popover": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@radix-ui/react-popover/-/react-popover-1.1.1.tgz", + "integrity": "sha512-3y1A3isulwnWhvTTwmIreiB8CF4L+qRjZnK1wYLO7pplddzXKby/GnZ2M7OZY3qgnl6p9AodUIHRYGXNah8Y7g==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.1.0", + "@radix-ui/react-compose-refs": "1.1.0", + "@radix-ui/react-context": "1.1.0", + "@radix-ui/react-dismissable-layer": "1.1.0", + "@radix-ui/react-focus-guards": "1.1.0", + "@radix-ui/react-focus-scope": "1.1.0", + "@radix-ui/react-id": "1.1.0", + "@radix-ui/react-popper": "1.2.0", + "@radix-ui/react-portal": "1.1.1", + "@radix-ui/react-presence": "1.1.0", + "@radix-ui/react-primitive": "2.0.0", + "@radix-ui/react-slot": "1.1.0", + "@radix-ui/react-use-controllable-state": "1.1.0", + "aria-hidden": "^1.1.1", + "react-remove-scroll": "2.5.7" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-popper": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-popper/-/react-popper-1.2.0.tgz", + "integrity": "sha512-ZnRMshKF43aBxVWPWvbj21+7TQCvhuULWJ4gNIKYpRlQt5xGRhLx66tMp8pya2UkGHTSlhpXwmjqltDYHhw7Vg==", + "license": "MIT", + "dependencies": { + "@floating-ui/react-dom": "^2.0.0", + "@radix-ui/react-arrow": "1.1.0", + "@radix-ui/react-compose-refs": "1.1.0", + "@radix-ui/react-context": "1.1.0", + "@radix-ui/react-primitive": "2.0.0", + "@radix-ui/react-use-callback-ref": "1.1.0", + "@radix-ui/react-use-layout-effect": "1.1.0", + "@radix-ui/react-use-rect": "1.1.0", + "@radix-ui/react-use-size": "1.1.0", + "@radix-ui/rect": "1.1.0" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-portal": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@radix-ui/react-portal/-/react-portal-1.1.1.tgz", + "integrity": "sha512-A3UtLk85UtqhzFqtoC8Q0KvR2GbXF3mtPgACSazajqq6A41mEQgo53iPzY4i6BwDxlIFqWIhiQ2G729n+2aw/g==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-primitive": "2.0.0", + "@radix-ui/react-use-layout-effect": "1.1.0" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-presence": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-presence/-/react-presence-1.1.0.tgz", + "integrity": "sha512-Gq6wuRN/asf9H/E/VzdKoUtT8GC9PQc9z40/vEr0VCJ4u5XvvhWIrSsCB6vD2/cH7ugTdSfYq9fLJCcM00acrQ==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-compose-refs": "1.1.0", + "@radix-ui/react-use-layout-effect": "1.1.0" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-primitive": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-primitive/-/react-primitive-2.0.0.tgz", + "integrity": "sha512-ZSpFm0/uHa8zTvKBDjLFWLo8dkr4MBsiDLz0g3gMUwqgLHz9rTaRRGYDgvZPtBJgYCBKXkS9fzmoySgr8CO6Cw==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-slot": "1.1.0" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-roving-focus": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-roving-focus/-/react-roving-focus-1.1.0.tgz", + "integrity": "sha512-EA6AMGeq9AEeQDeSH0aZgG198qkfHSbvWTf1HvoDmOB5bBG/qTxjYMWUKMnYiV6J/iP/J8MEFSuB2zRU2n7ODA==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.1.0", + "@radix-ui/react-collection": "1.1.0", + "@radix-ui/react-compose-refs": "1.1.0", + "@radix-ui/react-context": "1.1.0", + "@radix-ui/react-direction": "1.1.0", + "@radix-ui/react-id": "1.1.0", + "@radix-ui/react-primitive": "2.0.0", + "@radix-ui/react-use-callback-ref": "1.1.0", + "@radix-ui/react-use-controllable-state": "1.1.0" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-select": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/@radix-ui/react-select/-/react-select-2.1.1.tgz", + "integrity": "sha512-8iRDfyLtzxlprOo9IicnzvpsO1wNCkuwzzCM+Z5Rb5tNOpCdMvcc2AkzX0Fz+Tz9v6NJ5B/7EEgyZveo4FBRfQ==", + "license": "MIT", + "dependencies": { + "@radix-ui/number": "1.1.0", + "@radix-ui/primitive": "1.1.0", + "@radix-ui/react-collection": "1.1.0", + "@radix-ui/react-compose-refs": "1.1.0", + "@radix-ui/react-context": "1.1.0", + "@radix-ui/react-direction": "1.1.0", + "@radix-ui/react-dismissable-layer": "1.1.0", + "@radix-ui/react-focus-guards": "1.1.0", + "@radix-ui/react-focus-scope": "1.1.0", + "@radix-ui/react-id": "1.1.0", + "@radix-ui/react-popper": "1.2.0", + "@radix-ui/react-portal": "1.1.1", + "@radix-ui/react-primitive": "2.0.0", + "@radix-ui/react-slot": "1.1.0", + "@radix-ui/react-use-callback-ref": "1.1.0", + "@radix-ui/react-use-controllable-state": "1.1.0", + "@radix-ui/react-use-layout-effect": "1.1.0", + "@radix-ui/react-use-previous": "1.1.0", + "@radix-ui/react-visually-hidden": "1.1.0", + "aria-hidden": "^1.1.1", + "react-remove-scroll": "2.5.7" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-separator": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-separator/-/react-separator-1.1.0.tgz", + "integrity": "sha512-3uBAs+egzvJBDZAzvb/n4NxxOYpnspmWxO2u5NbZ8Y6FM/NdrGSF9bop3Cf6F6C71z1rTSn8KV0Fo2ZVd79lGA==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-primitive": "2.0.0" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-slot": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-slot/-/react-slot-1.1.0.tgz", + "integrity": "sha512-FUCf5XMfmW4dtYl69pdS4DbxKy8nj4M7SafBgPllysxmdachynNflAdp/gCsnYWNDnge6tI9onzMp5ARYc1KNw==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-compose-refs": "1.1.0" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-tooltip": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/@radix-ui/react-tooltip/-/react-tooltip-1.1.3.tgz", + "integrity": "sha512-Z4w1FIS0BqVFI2c1jZvb/uDVJijJjJ2ZMuPV81oVgTZ7g3BZxobplnMVvXtFWgtozdvYJ+MFWtwkM5S2HnAong==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.1.0", + "@radix-ui/react-compose-refs": "1.1.0", + "@radix-ui/react-context": "1.1.1", + "@radix-ui/react-dismissable-layer": "1.1.1", + "@radix-ui/react-id": "1.1.0", + "@radix-ui/react-popper": "1.2.0", + "@radix-ui/react-portal": "1.1.2", + "@radix-ui/react-presence": "1.1.1", + "@radix-ui/react-primitive": "2.0.0", + "@radix-ui/react-slot": "1.1.0", + "@radix-ui/react-use-controllable-state": "1.1.0", + "@radix-ui/react-visually-hidden": "1.1.0" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-tooltip/node_modules/@radix-ui/react-context": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@radix-ui/react-context/-/react-context-1.1.1.tgz", + "integrity": "sha512-UASk9zi+crv9WteK/NU4PLvOoL3OuE6BWVKNF6hPRBtYBDXQ2u5iu3O59zUlJiTVvkyuycnqrztsHVJwcK9K+Q==", + "license": "MIT", + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-tooltip/node_modules/@radix-ui/react-dismissable-layer": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@radix-ui/react-dismissable-layer/-/react-dismissable-layer-1.1.1.tgz", + "integrity": "sha512-QSxg29lfr/xcev6kSz7MAlmDnzbP1eI/Dwn3Tp1ip0KT5CUELsxkekFEMVBEoykI3oV39hKT4TKZzBNMbcTZYQ==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.1.0", + "@radix-ui/react-compose-refs": "1.1.0", + "@radix-ui/react-primitive": "2.0.0", + "@radix-ui/react-use-callback-ref": "1.1.0", + "@radix-ui/react-use-escape-keydown": "1.1.0" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-tooltip/node_modules/@radix-ui/react-portal": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@radix-ui/react-portal/-/react-portal-1.1.2.tgz", + "integrity": "sha512-WeDYLGPxJb/5EGBoedyJbT0MpoULmwnIPMJMSldkuiMsBAv7N1cRdsTWZWht9vpPOiN3qyiGAtbK2is47/uMFg==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-primitive": "2.0.0", + "@radix-ui/react-use-layout-effect": "1.1.0" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-tooltip/node_modules/@radix-ui/react-presence": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@radix-ui/react-presence/-/react-presence-1.1.1.tgz", + "integrity": "sha512-IeFXVi4YS1K0wVZzXNrbaaUvIJ3qdY+/Ih4eHFhWA9SwGR9UDX7Ck8abvL57C4cv3wwMvUE0OG69Qc3NCcTe/A==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-compose-refs": "1.1.0", + "@radix-ui/react-use-layout-effect": "1.1.0" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-use-callback-ref": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-callback-ref/-/react-use-callback-ref-1.1.0.tgz", + "integrity": "sha512-CasTfvsy+frcFkbXtSJ2Zu9JHpN8TYKxkgJGWbjiZhFivxaeW7rMeZt7QELGVLaYVfFMsKHjb7Ak0nMEe+2Vfw==", + "license": "MIT", + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-use-controllable-state": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-controllable-state/-/react-use-controllable-state-1.1.0.tgz", + "integrity": "sha512-MtfMVJiSr2NjzS0Aa90NPTnvTSg6C/JLCV7ma0W6+OMV78vd8OyRpID+Ng9LxzsPbLeuBnWBA1Nq30AtBIDChw==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-use-callback-ref": "1.1.0" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-use-escape-keydown": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-escape-keydown/-/react-use-escape-keydown-1.1.0.tgz", + "integrity": "sha512-L7vwWlR1kTTQ3oh7g1O0CBF3YCyyTj8NmhLR+phShpyA50HCfBFKVJTpshm9PzLiKmehsrQzTYTpX9HvmC9rhw==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-use-callback-ref": "1.1.0" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-use-layout-effect": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-layout-effect/-/react-use-layout-effect-1.1.0.tgz", + "integrity": "sha512-+FPE0rOdziWSrH9athwI1R0HDVbWlEhd+FR+aSDk4uWGmSJ9Z54sdZVDQPZAinJhJXwfT+qnj969mCsT2gfm5w==", + "license": "MIT", + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-use-previous": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-previous/-/react-use-previous-1.1.0.tgz", + "integrity": "sha512-Z/e78qg2YFnnXcW88A4JmTtm4ADckLno6F7OXotmkQfeuCVaKuYzqAATPhVzl3delXE7CxIV8shofPn3jPc5Og==", + "license": "MIT", + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-use-rect": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-rect/-/react-use-rect-1.1.0.tgz", + "integrity": "sha512-0Fmkebhr6PiseyZlYAOtLS+nb7jLmpqTrJyv61Pe68MKYW6OWdRE2kI70TaYY27u7H0lajqM3hSMMLFq18Z7nQ==", + "license": "MIT", + "dependencies": { + "@radix-ui/rect": "1.1.0" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-use-size": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-size/-/react-use-size-1.1.0.tgz", + "integrity": "sha512-XW3/vWuIXHa+2Uwcc2ABSfcCledmXhhQPlGbfcRXbiUQI5Icjcg19BGCZVKKInYbvUCut/ufbbLLPFC5cbb1hw==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-use-layout-effect": "1.1.0" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-visually-hidden": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-visually-hidden/-/react-visually-hidden-1.1.0.tgz", + "integrity": "sha512-N8MDZqtgCgG5S3aV60INAB475osJousYpZ4cTJ2cFbMpdHS5Y6loLTH8LPtkj2QN0x93J30HT/M3qJXM0+lyeQ==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-primitive": "2.0.0" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/rect": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@radix-ui/rect/-/rect-1.1.0.tgz", + "integrity": "sha512-A9+lCBZoaMJlVKcRBz2YByCG+Cp2t6nAnMnNba+XiWxnj6r4JUFqfsgwocMBZU9LPtdxC6wB56ySYpc7LQIoJg==", + "license": "MIT" + }, + "node_modules/@react-oauth/google": { + "version": "0.12.1", + "resolved": "https://registry.npmjs.org/@react-oauth/google/-/google-0.12.1.tgz", + "integrity": "sha512-qagsy22t+7UdkYAiT5ZhfM4StXi9PPNvw0zuwNmabrWyMKddczMtBIOARflbaIj+wHiQjnMAsZmzsUYuXeyoSg==", + "license": "MIT", + "peerDependencies": { + "react": ">=16.8.0", + "react-dom": ">=16.8.0" + } + }, + "node_modules/@rtsao/scc": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@rtsao/scc/-/scc-1.1.0.tgz", + "integrity": "sha512-zt6OdqaDoOnJ1ZYsCYGt9YmWzDXl4vQdKTyJev62gFhRGKdx7mcT54V9KIjg+d2wi9EXsPvAPKe7i7WjfVWB8g==", + "dev": true, + "license": "MIT" + }, + "node_modules/@rushstack/eslint-patch": { + "version": "1.10.4", + "resolved": "https://registry.npmjs.org/@rushstack/eslint-patch/-/eslint-patch-1.10.4.tgz", + "integrity": "sha512-WJgX9nzTqknM393q1QJDJmoW28kUfEnybeTfVNcNAPnIx210RXm2DiXiHzfNPJNIUUb1tJnz/l4QGtJ30PgWmA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@shikijs/core": { + "version": "1.22.2", + "resolved": "https://registry.npmjs.org/@shikijs/core/-/core-1.22.2.tgz", + "integrity": "sha512-bvIQcd8BEeR1yFvOYv6HDiyta2FFVePbzeowf5pPS1avczrPK+cjmaxxh0nx5QzbON7+Sv0sQfQVciO7bN72sg==", + "license": "MIT", + "dependencies": { + "@shikijs/engine-javascript": "1.22.2", + "@shikijs/engine-oniguruma": "1.22.2", + "@shikijs/types": "1.22.2", + "@shikijs/vscode-textmate": "^9.3.0", + "@types/hast": "^3.0.4", + "hast-util-to-html": "^9.0.3" + } + }, + "node_modules/@shikijs/core/node_modules/@types/hast": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/@types/hast/-/hast-3.0.4.tgz", + "integrity": "sha512-WPs+bbQw5aCj+x6laNGWLH3wviHtoCv/P3+otBhbOhJgG8qtpdAMlTCxLtsTWA7LH1Oh/bFCHsBn0TPS5m30EQ==", + "license": "MIT", + "dependencies": { + "@types/unist": "*" + } + }, + "node_modules/@shikijs/engine-javascript": { + "version": "1.22.2", + "resolved": "https://registry.npmjs.org/@shikijs/engine-javascript/-/engine-javascript-1.22.2.tgz", + "integrity": "sha512-iOvql09ql6m+3d1vtvP8fLCVCK7BQD1pJFmHIECsujB0V32BJ0Ab6hxk1ewVSMFA58FI0pR2Had9BKZdyQrxTw==", + "license": "MIT", + "dependencies": { + "@shikijs/types": "1.22.2", + "@shikijs/vscode-textmate": "^9.3.0", + "oniguruma-to-js": "0.4.3" + } + }, + "node_modules/@shikijs/engine-oniguruma": { + "version": "1.22.2", + "resolved": "https://registry.npmjs.org/@shikijs/engine-oniguruma/-/engine-oniguruma-1.22.2.tgz", + "integrity": "sha512-GIZPAGzQOy56mGvWMoZRPggn0dTlBf1gutV5TdceLCZlFNqWmuc7u+CzD0Gd9vQUTgLbrt0KLzz6FNprqYAxlA==", + "license": "MIT", + "dependencies": { + "@shikijs/types": "1.22.2", + "@shikijs/vscode-textmate": "^9.3.0" + } + }, + "node_modules/@shikijs/monaco": { + "version": "1.22.2", + "resolved": "https://registry.npmjs.org/@shikijs/monaco/-/monaco-1.22.2.tgz", + "integrity": "sha512-B4uAlNLUC1C57PGbhYjKVfRwRuh1hmj0/dOZt0IbdH3xjkF/kA99fcXOe9ODtDX2W7s+hef9h4pYT2ZAAAhMwQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@shikijs/core": "1.22.2", + "@shikijs/types": "1.22.2", + "@shikijs/vscode-textmate": "^9.3.0" + } + }, + "node_modules/@shikijs/types": { + "version": "1.22.2", + "resolved": "https://registry.npmjs.org/@shikijs/types/-/types-1.22.2.tgz", + "integrity": "sha512-NCWDa6LGZqTuzjsGfXOBWfjS/fDIbDdmVDug+7ykVe1IKT4c1gakrvlfFYp5NhAXH/lyqLM8wsAPo5wNy73Feg==", + "license": "MIT", + "dependencies": { + "@shikijs/vscode-textmate": "^9.3.0", + "@types/hast": "^3.0.4" + } + }, + "node_modules/@shikijs/types/node_modules/@types/hast": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/@types/hast/-/hast-3.0.4.tgz", + "integrity": "sha512-WPs+bbQw5aCj+x6laNGWLH3wviHtoCv/P3+otBhbOhJgG8qtpdAMlTCxLtsTWA7LH1Oh/bFCHsBn0TPS5m30EQ==", + "license": "MIT", + "dependencies": { + "@types/unist": "*" + } + }, + "node_modules/@shikijs/vscode-textmate": { + "version": "9.3.0", + "resolved": "https://registry.npmjs.org/@shikijs/vscode-textmate/-/vscode-textmate-9.3.0.tgz", + "integrity": "sha512-jn7/7ky30idSkd/O5yDBfAnVt+JJpepofP/POZ1iMOxK59cOfqIgg/Dj0eFsjOTMw+4ycJN0uhZH/Eb0bs/EUA==", + "license": "MIT" + }, + "node_modules/@stomp/stompjs": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/@stomp/stompjs/-/stompjs-7.0.0.tgz", + "integrity": "sha512-fGdq4wPDnSV/KyOsjq4P+zLc8MFWC3lMmP5FBgLWKPJTYcuCbAIrnRGjB7q2jHZdYCOD5vxLuFoKIYLy5/u8Pw==", + "license": "Apache-2.0" + }, + "node_modules/@swc/counter": { + "version": "0.1.3", + "resolved": "https://registry.npmjs.org/@swc/counter/-/counter-0.1.3.tgz", + "integrity": "sha512-e2BR4lsJkkRlKZ/qCHPw9ZaSxc0MVUd7gtbtaB7aMvHeJVYe8sOB8DBZkP2DtISHGSku9sCK6T6cnY0CtXrOCQ==", + "license": "Apache-2.0" + }, + "node_modules/@swc/helpers": { + "version": "0.5.5", + "resolved": "https://registry.npmjs.org/@swc/helpers/-/helpers-0.5.5.tgz", + "integrity": "sha512-KGYxvIOXcceOAbEk4bi/dVLEK9z8sZ0uBB3Il5b1rhfClSpcX0yfRO0KmTkqR2cnQDymwLB+25ZyMzICg/cm/A==", + "license": "Apache-2.0", + "dependencies": { + "@swc/counter": "^0.1.3", + "tslib": "^2.4.0" + } + }, + "node_modules/@tanstack/react-table": { + "version": "8.20.5", + "resolved": "https://registry.npmjs.org/@tanstack/react-table/-/react-table-8.20.5.tgz", + "integrity": "sha512-WEHopKw3znbUZ61s9i0+i9g8drmDo6asTWbrQh8Us63DAk/M0FkmIqERew6P71HI75ksZ2Pxyuf4vvKh9rAkiA==", + "license": "MIT", + "dependencies": { + "@tanstack/table-core": "8.20.5" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/tannerlinsley" + }, + "peerDependencies": { + "react": ">=16.8", + "react-dom": ">=16.8" + } + }, + "node_modules/@tanstack/table-core": { + "version": "8.20.5", + "resolved": "https://registry.npmjs.org/@tanstack/table-core/-/table-core-8.20.5.tgz", + "integrity": "sha512-P9dF7XbibHph2PFRz8gfBKEXEY/HJPOhym8CHmjF8y3q5mWpKx9xtZapXQUWCgkqvsK0R46Azuz+VaxD4Xl+Tg==", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/tannerlinsley" + } + }, + "node_modules/@types/hast": { + "version": "2.3.10", + "resolved": "https://registry.npmjs.org/@types/hast/-/hast-2.3.10.tgz", + "integrity": "sha512-McWspRw8xx8J9HurkVBfYj0xKoE25tOFlHGdx4MJ5xORQrMGZNqJhVQWaIbm6Oyla5kYOXtDiopzKRJzEOkwJw==", + "license": "MIT", + "dependencies": { + "@types/unist": "^2" + } + }, + "node_modules/@types/js-cookie": { + "version": "3.0.6", + "resolved": "https://registry.npmjs.org/@types/js-cookie/-/js-cookie-3.0.6.tgz", + "integrity": "sha512-wkw9yd1kEXOPnvEeEV1Go1MmxtBJL0RR79aOTAApecWFVu7w0NNXNqhcWgvw2YgZDYadliXkl14pa3WXw5jlCQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/json-schema": { + "version": "7.0.15", + "resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.15.tgz", + "integrity": "sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/json5": { + "version": "0.0.29", + "resolved": "https://registry.npmjs.org/@types/json5/-/json5-0.0.29.tgz", + "integrity": "sha512-dRLjCWHYg4oaA77cxO64oO+7JwCwnIzkZPdrrC71jQmQtlhM556pwKo5bUzqvZndkVbeFLIIi+9TC40JNF5hNQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/mdast": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/@types/mdast/-/mdast-4.0.4.tgz", + "integrity": "sha512-kGaNbPh1k7AFzgpud/gMdvIm5xuECykRR+JnWKQno9TAXVa6WIVCGTPvYGekIDL4uwCZQSYbUxNBSb1aUo79oA==", + "license": "MIT", + "dependencies": { + "@types/unist": "*" + } + }, + "node_modules/@types/node": { + "version": "20.16.5", + "resolved": "https://registry.npmjs.org/@types/node/-/node-20.16.5.tgz", + "integrity": "sha512-VwYCweNo3ERajwy0IUlqqcyZ8/A7Zwa9ZP3MnENWcB11AejO+tLy3pu850goUW2FC/IJMdZUfKpX/yxL1gymCA==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": "~6.19.2" + } + }, + "node_modules/@types/parse-json": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@types/parse-json/-/parse-json-4.0.2.tgz", + "integrity": "sha512-dISoDXWWQwUquiKsyZ4Ng+HX2KsPL7LyHKHQwgGFEA3IaKac4Obd+h2a/a6waisAoepJlBcx9paWqjA8/HVjCw==", + "license": "MIT" + }, + "node_modules/@types/prop-types": { + "version": "15.7.13", + "resolved": "https://registry.npmjs.org/@types/prop-types/-/prop-types-15.7.13.tgz", + "integrity": "sha512-hCZTSvwbzWGvhqxp/RqVqwU999pBf2vp7hzIjiYOsl8wqOmUxkQ6ddw1cV3l8811+kdUFus/q4d1Y3E3SyEifA==", + "license": "MIT" + }, + "node_modules/@types/react": { + "version": "18.3.7", + "resolved": "https://registry.npmjs.org/@types/react/-/react-18.3.7.tgz", + "integrity": "sha512-KUnDCJF5+AiZd8owLIeVHqmW9yM4sqmDVf2JRJiBMFkGvkoZ4/WyV2lL4zVsoinmRS/W3FeEdZLEWFRofnT2FQ==", + "license": "MIT", + "dependencies": { + "@types/prop-types": "*", + "csstype": "^3.0.2" + } + }, + "node_modules/@types/react-dom": { + "version": "18.3.0", + "resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-18.3.0.tgz", + "integrity": "sha512-EhwApuTmMBmXuFOikhQLIBUn6uFg81SwLMOAUgodJF14SOBOCMdU04gDoYi0WOJJHD144TL32z4yDqCW3dnkQg==", + "devOptional": true, + "license": "MIT", + "dependencies": { + "@types/react": "*" + } + }, + "node_modules/@types/react-modal": { + "version": "3.16.3", + "resolved": "https://registry.npmjs.org/@types/react-modal/-/react-modal-3.16.3.tgz", + "integrity": "sha512-xXuGavyEGaFQDgBv4UVm8/ZsG+qxeQ7f77yNrW3n+1J6XAstUy5rYHeIHPh1KzsGc6IkCIdu6lQ2xWzu1jBTLg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/react": "*" + } + }, + "node_modules/@types/react-syntax-highlighter": { + "version": "15.5.13", + "resolved": "https://registry.npmjs.org/@types/react-syntax-highlighter/-/react-syntax-highlighter-15.5.13.tgz", + "integrity": "sha512-uLGJ87j6Sz8UaBAooU0T6lWJ0dBmjZgN1PZTrj05TNql2/XpC6+4HhMT5syIdFUUt+FASfCeLLv4kBygNU+8qA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/react": "*" + } + }, + "node_modules/@types/react-transition-group": { + "version": "4.4.11", + "resolved": "https://registry.npmjs.org/@types/react-transition-group/-/react-transition-group-4.4.11.tgz", + "integrity": "sha512-RM05tAniPZ5DZPzzNFP+DmrcOdD0efDUxMy3145oljWSl3x9ZV5vhme98gTxFrj2lhXvmGNnUiuDyJgY9IKkNA==", + "license": "MIT", + "dependencies": { + "@types/react": "*" + } + }, + "node_modules/@types/semver": { + "version": "7.5.8", + "resolved": "https://registry.npmjs.org/@types/semver/-/semver-7.5.8.tgz", + "integrity": "sha512-I8EUhyrgfLrcTkzV3TSsGyl1tSuPrEDzr0yd5m90UgNxQkyDXULk3b6MlQqTCpZpNtWe1K0hzclnZkTcLBe2UQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/sockjs-client": { + "version": "1.5.4", + "resolved": "https://registry.npmjs.org/@types/sockjs-client/-/sockjs-client-1.5.4.tgz", + "integrity": "sha512-zk+uFZeWyvJ5ZFkLIwoGA/DfJ+pYzcZ8eH4H/EILCm2OBZyHH6Hkdna1/UWL/CFruh5wj6ES7g75SvUB0VsH5w==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/unist": { + "version": "2.0.11", + "resolved": "https://registry.npmjs.org/@types/unist/-/unist-2.0.11.tgz", + "integrity": "sha512-CmBKiL6NNo/OqgmMn95Fk9Whlp2mtvIv+KNpQKN2F4SjvrEesubTRWGYSg+BnWZOnlCaSTU1sMpsBOzgbYhnsA==", + "license": "MIT" + }, + "node_modules/@typescript-eslint/eslint-plugin": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-7.2.0.tgz", + "integrity": "sha512-mdekAHOqS9UjlmyF/LSs6AIEvfceV749GFxoBAjwAv0nkevfKHWQFDMcBZWUiIC5ft6ePWivXoS36aKQ0Cy3sw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@eslint-community/regexpp": "^4.5.1", + "@typescript-eslint/scope-manager": "7.2.0", + "@typescript-eslint/type-utils": "7.2.0", + "@typescript-eslint/utils": "7.2.0", + "@typescript-eslint/visitor-keys": "7.2.0", + "debug": "^4.3.4", + "graphemer": "^1.4.0", + "ignore": "^5.2.4", + "natural-compare": "^1.4.0", + "semver": "^7.5.4", + "ts-api-utils": "^1.0.1" + }, + "engines": { + "node": "^16.0.0 || >=18.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "@typescript-eslint/parser": "^7.0.0", + "eslint": "^8.56.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@typescript-eslint/parser": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-7.2.0.tgz", + "integrity": "sha512-5FKsVcHTk6TafQKQbuIVkXq58Fnbkd2wDL4LB7AURN7RUOu1utVP+G8+6u3ZhEroW3DF6hyo3ZEXxgKgp4KeCg==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "@typescript-eslint/scope-manager": "7.2.0", + "@typescript-eslint/types": "7.2.0", + "@typescript-eslint/typescript-estree": "7.2.0", + "@typescript-eslint/visitor-keys": "7.2.0", + "debug": "^4.3.4" + }, + "engines": { + "node": "^16.0.0 || >=18.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "eslint": "^8.56.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@typescript-eslint/scope-manager": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-7.2.0.tgz", + "integrity": "sha512-Qh976RbQM/fYtjx9hs4XkayYujB/aPwglw2choHmf3zBjB4qOywWSdt9+KLRdHubGcoSwBnXUH2sR3hkyaERRg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/types": "7.2.0", + "@typescript-eslint/visitor-keys": "7.2.0" + }, + "engines": { + "node": "^16.0.0 || >=18.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + } + }, + "node_modules/@typescript-eslint/type-utils": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-7.2.0.tgz", + "integrity": "sha512-xHi51adBHo9O9330J8GQYQwrKBqbIPJGZZVQTHHmy200hvkLZFWJIFtAG/7IYTWUyun6DE6w5InDReePJYJlJA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/typescript-estree": "7.2.0", + "@typescript-eslint/utils": "7.2.0", + "debug": "^4.3.4", + "ts-api-utils": "^1.0.1" + }, + "engines": { + "node": "^16.0.0 || >=18.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "eslint": "^8.56.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@typescript-eslint/types": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-7.2.0.tgz", + "integrity": "sha512-XFtUHPI/abFhm4cbCDc5Ykc8npOKBSJePY3a3s+lwumt7XWJuzP5cZcfZ610MIPHjQjNsOLlYK8ASPaNG8UiyA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^16.0.0 || >=18.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + } + }, + "node_modules/@typescript-eslint/typescript-estree": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-7.2.0.tgz", + "integrity": "sha512-cyxS5WQQCoBwSakpMrvMXuMDEbhOo9bNHHrNcEWis6XHx6KF518tkF1wBvKIn/tpq5ZpUYK7Bdklu8qY0MsFIA==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "@typescript-eslint/types": "7.2.0", + "@typescript-eslint/visitor-keys": "7.2.0", + "debug": "^4.3.4", + "globby": "^11.1.0", + "is-glob": "^4.0.3", + "minimatch": "9.0.3", + "semver": "^7.5.4", + "ts-api-utils": "^1.0.1" + }, + "engines": { + "node": "^16.0.0 || >=18.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@typescript-eslint/typescript-estree/node_modules/brace-expansion": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.1.tgz", + "integrity": "sha512-XnAIvQ8eM+kC6aULx6wuQiwVsnzsi9d3WxzV3FpWTGA19F621kwdbsAcFKXgKUHZWsy+mY6iL1sHTxWEFCytDA==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0" + } + }, + "node_modules/@typescript-eslint/typescript-estree/node_modules/minimatch": { + "version": "9.0.3", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-9.0.3.tgz", + "integrity": "sha512-RHiac9mvaRw0x3AYRgDC1CxAP7HTcNrrECeA8YYJeWnpo+2Q5CegtZjaotWTWxDG3UeGA1coE05iH1mPjT/2mg==", + "dev": true, + "license": "ISC", + "dependencies": { + "brace-expansion": "^2.0.1" + }, + "engines": { + "node": ">=16 || 14 >=14.17" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/@typescript-eslint/utils": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-7.2.0.tgz", + "integrity": "sha512-YfHpnMAGb1Eekpm3XRK8hcMwGLGsnT6L+7b2XyRv6ouDuJU1tZir1GS2i0+VXRatMwSI1/UfcyPe53ADkU+IuA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@eslint-community/eslint-utils": "^4.4.0", + "@types/json-schema": "^7.0.12", + "@types/semver": "^7.5.0", + "@typescript-eslint/scope-manager": "7.2.0", + "@typescript-eslint/types": "7.2.0", + "@typescript-eslint/typescript-estree": "7.2.0", + "semver": "^7.5.4" + }, + "engines": { + "node": "^16.0.0 || >=18.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "eslint": "^8.56.0" + } + }, + "node_modules/@typescript-eslint/visitor-keys": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-7.2.0.tgz", + "integrity": "sha512-c6EIQRHhcpl6+tO8EMR+kjkkV+ugUNXOmeASA1rlzkd8EPIriavpWoiEz1HR/VLhbVIdhqnV6E7JZm00cBDx2A==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/types": "7.2.0", + "eslint-visitor-keys": "^3.4.1" + }, + "engines": { + "node": "^16.0.0 || >=18.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + } + }, + "node_modules/@ungap/structured-clone": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@ungap/structured-clone/-/structured-clone-1.2.0.tgz", + "integrity": "sha512-zuVdFrMJiuCDQUMCzQaD6KL28MjnqqN8XnAqiEq9PNm/hCPTSGfrXCOfwj1ow4LFb/tNymJPwsNbVePc1xFqrQ==", + "license": "ISC" + }, + "node_modules/acorn": { + "version": "8.12.1", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.12.1.tgz", + "integrity": "sha512-tcpGyI9zbizT9JbV6oYE477V6mTlXvvi0T0G3SNIYE2apm/G5huBa1+K89VGeovbg+jycCrfhl3ADxErOuO6Jg==", + "dev": true, + "license": "MIT", + "bin": { + "acorn": "bin/acorn" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/acorn-jsx": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/acorn-jsx/-/acorn-jsx-5.3.2.tgz", + "integrity": "sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==", + "dev": true, + "license": "MIT", + "peerDependencies": { + "acorn": "^6.0.0 || ^7.0.0 || ^8.0.0" + } + }, + "node_modules/ajv": { + "version": "6.12.6", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.12.6.tgz", + "integrity": "sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==", + "dev": true, + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.1", + "fast-json-stable-stringify": "^2.0.0", + "json-schema-traverse": "^0.4.1", + "uri-js": "^4.2.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "license": "MIT", + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/any-promise": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/any-promise/-/any-promise-1.3.0.tgz", + "integrity": "sha512-7UvmKalWRt1wgjL1RrGxoSJW/0QZFIegpeGvZG9kjp8vrRu55XTHbwnqq2GpXm9uLbcuhxm3IqX9OB4MZR1b2A==", + "license": "MIT" + }, + "node_modules/anymatch": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.3.tgz", + "integrity": "sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw==", + "license": "ISC", + "dependencies": { + "normalize-path": "^3.0.0", + "picomatch": "^2.0.4" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/arg": { + "version": "5.0.2", + "resolved": "https://registry.npmjs.org/arg/-/arg-5.0.2.tgz", + "integrity": "sha512-PYjyFOLKQ9y57JvQ6QLo8dAgNqswh8M1RMJYdQduT6xbWSgK36P/Z/v+p888pM69jMMfS8Xd8F6I1kQ/I9HUGg==", + "license": "MIT" + }, + "node_modules/argparse": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", + "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==", + "dev": true, + "license": "Python-2.0" + }, + "node_modules/aria-hidden": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/aria-hidden/-/aria-hidden-1.2.4.tgz", + "integrity": "sha512-y+CcFFwelSXpLZk/7fMB2mUbGtX9lKycf1MWJ7CaTIERyitVlyQx6C+sxcROU2BAJ24OiZyK+8wj2i8AlBoS3A==", + "license": "MIT", + "dependencies": { + "tslib": "^2.0.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/aria-query": { + "version": "5.1.3", + "resolved": "https://registry.npmjs.org/aria-query/-/aria-query-5.1.3.tgz", + "integrity": "sha512-R5iJ5lkuHybztUfuOAznmboyjWq8O6sqNqtK7CLOqdydi54VNbORp49mb14KbWgG1QD3JFO9hJdZ+y4KutfdOQ==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "deep-equal": "^2.0.5" + } + }, + "node_modules/array-buffer-byte-length": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/array-buffer-byte-length/-/array-buffer-byte-length-1.0.1.tgz", + "integrity": "sha512-ahC5W1xgou+KTXix4sAO8Ki12Q+jf4i0+tmk3sC+zgcynshkHxzpXdImBehiUYKKKDwvfFiJl1tZt6ewscS1Mg==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.5", + "is-array-buffer": "^3.0.4" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/array-includes": { + "version": "3.1.8", + "resolved": "https://registry.npmjs.org/array-includes/-/array-includes-3.1.8.tgz", + "integrity": "sha512-itaWrbYbqpGXkGhZPGUulwnhVf5Hpy1xiCFsGqyIGglbBxmG5vSjxQen3/WGOjPpNEv1RtBLKxbmVXm8HpJStQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.7", + "define-properties": "^1.2.1", + "es-abstract": "^1.23.2", + "es-object-atoms": "^1.0.0", + "get-intrinsic": "^1.2.4", + "is-string": "^1.0.7" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/array-union": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/array-union/-/array-union-2.1.0.tgz", + "integrity": "sha512-HGyxoOTYUyCM6stUe6EJgnd4EoewAI7zMdfqO+kGjnlZmBDz/cR5pf8r/cR4Wq60sL/p0IkcjUEEPwS3GFrIyw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/array.prototype.findlast": { + "version": "1.2.5", + "resolved": "https://registry.npmjs.org/array.prototype.findlast/-/array.prototype.findlast-1.2.5.tgz", + "integrity": "sha512-CVvd6FHg1Z3POpBLxO6E6zr+rSKEQ9L6rZHAaY7lLfhKsWYUBBOuMs0e9o24oopj6H+geRCX0YJ+TJLBK2eHyQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.7", + "define-properties": "^1.2.1", + "es-abstract": "^1.23.2", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.0.0", + "es-shim-unscopables": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/array.prototype.findlastindex": { + "version": "1.2.5", + "resolved": "https://registry.npmjs.org/array.prototype.findlastindex/-/array.prototype.findlastindex-1.2.5.tgz", + "integrity": "sha512-zfETvRFA8o7EiNn++N5f/kaCw221hrpGsDmcpndVupkPzEc1Wuf3VgC0qby1BbHs7f5DVYjgtEU2LLh5bqeGfQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.7", + "define-properties": "^1.2.1", + "es-abstract": "^1.23.2", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.0.0", + "es-shim-unscopables": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/array.prototype.flat": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/array.prototype.flat/-/array.prototype.flat-1.3.2.tgz", + "integrity": "sha512-djYB+Zx2vLewY8RWlNCUdHjDXs2XOgm602S9E7P/UpHgfeHL00cRiIF+IN/G/aUJ7kGPb6yO/ErDI5V2s8iycA==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.2", + "define-properties": "^1.2.0", + "es-abstract": "^1.22.1", + "es-shim-unscopables": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/array.prototype.flatmap": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/array.prototype.flatmap/-/array.prototype.flatmap-1.3.2.tgz", + "integrity": "sha512-Ewyx0c9PmpcsByhSW4r+9zDU7sGjFc86qf/kKtuSCRdhfbk0SNLLkaT5qvcHnRGgc5NP/ly/y+qkXkqONX54CQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.2", + "define-properties": "^1.2.0", + "es-abstract": "^1.22.1", + "es-shim-unscopables": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/array.prototype.tosorted": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/array.prototype.tosorted/-/array.prototype.tosorted-1.1.4.tgz", + "integrity": "sha512-p6Fx8B7b7ZhL/gmUsAy0D15WhvDccw3mnGNbZpi3pmeJdxtWsj2jEaI4Y6oo3XiHfzuSgPwKc04MYt6KgvC/wA==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.7", + "define-properties": "^1.2.1", + "es-abstract": "^1.23.3", + "es-errors": "^1.3.0", + "es-shim-unscopables": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/arraybuffer.prototype.slice": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/arraybuffer.prototype.slice/-/arraybuffer.prototype.slice-1.0.3.tgz", + "integrity": "sha512-bMxMKAjg13EBSVscxTaYA4mRc5t1UAXa2kXiGTNfZ079HIWXEkKmkgFrh/nJqamaLSrXO5H4WFFkPEaLJWbs3A==", + "dev": true, + "license": "MIT", + "dependencies": { + "array-buffer-byte-length": "^1.0.1", + "call-bind": "^1.0.5", + "define-properties": "^1.2.1", + "es-abstract": "^1.22.3", + "es-errors": "^1.2.1", + "get-intrinsic": "^1.2.3", + "is-array-buffer": "^3.0.4", + "is-shared-array-buffer": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/ast-types-flow": { + "version": "0.0.8", + "resolved": "https://registry.npmjs.org/ast-types-flow/-/ast-types-flow-0.0.8.tgz", + "integrity": "sha512-OH/2E5Fg20h2aPrbe+QL8JZQFko0YZaF+j4mnQ7BGhfavO7OpSLa8a0y9sBwomHdSbkhTS8TQNayBfnW5DwbvQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/available-typed-arrays": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/available-typed-arrays/-/available-typed-arrays-1.0.7.tgz", + "integrity": "sha512-wvUjBtSGN7+7SjNpq/9M2Tg350UZD3q62IFZLbRAR1bSMlCo1ZaeW+BJ+D090e4hIIZLBcTDWe4Mh4jvUDajzQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "possible-typed-array-names": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/axe-core": { + "version": "4.10.0", + "resolved": "https://registry.npmjs.org/axe-core/-/axe-core-4.10.0.tgz", + "integrity": "sha512-Mr2ZakwQ7XUAjp7pAwQWRhhK8mQQ6JAaNWSjmjxil0R8BPioMtQsTLOolGYkji1rcL++3dCqZA3zWqpT+9Ew6g==", + "dev": true, + "license": "MPL-2.0", + "engines": { + "node": ">=4" + } + }, + "node_modules/axobject-query": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/axobject-query/-/axobject-query-4.1.0.tgz", + "integrity": "sha512-qIj0G9wZbMGNLjLmg1PT6v2mE9AH2zlnADJD/2tC6E00hgmhUOfEB6greHPAfLRSufHqROIUTkw6E+M3lH0PTQ==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/babel-plugin-macros": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/babel-plugin-macros/-/babel-plugin-macros-3.1.0.tgz", + "integrity": "sha512-Cg7TFGpIr01vOQNODXOOaGz2NpCU5gl8x1qJFbb6hbZxR7XrcE2vtbAsTAbJ7/xwJtUuJEw8K8Zr/AE0LHlesg==", + "license": "MIT", + "dependencies": { + "@babel/runtime": "^7.12.5", + "cosmiconfig": "^7.0.0", + "resolve": "^1.19.0" + }, + "engines": { + "node": ">=10", + "npm": ">=6" + } + }, + "node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", + "license": "MIT" + }, + "node_modules/base64-js": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", + "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] + }, + "node_modules/binary-extensions": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.3.0.tgz", + "integrity": "sha512-Ceh+7ox5qe7LJuLHoY0feh3pHuUDHAcRUeyL2VYghZwfpkNIy/+8Ocg0a3UuSoYzavmylwuLWQOf3hl0jjMMIw==", + "license": "MIT", + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/brace-expansion": { + "version": "1.1.11", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", + "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "node_modules/braces": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.3.tgz", + "integrity": "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==", + "license": "MIT", + "dependencies": { + "fill-range": "^7.1.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/buffer": { + "version": "6.0.3", + "resolved": "https://registry.npmjs.org/buffer/-/buffer-6.0.3.tgz", + "integrity": "sha512-FTiCpNxtwiZZHEZbcbTIcZjERVICn9yq/pDFkTl95/AxzD1naBctN7YO68riM/gLSDY7sdrMby8hofADYuuqOA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "dependencies": { + "base64-js": "^1.3.1", + "ieee754": "^1.2.1" + } + }, + "node_modules/busboy": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/busboy/-/busboy-1.6.0.tgz", + "integrity": "sha512-8SFQbg/0hQ9xy3UNTB0YEnsNBbWfhf7RtnzpL7TkBiTBRfrQ9Fxcnz7VJsleJpyp6rVLvXiuORqjlHi5q+PYuA==", + "dependencies": { + "streamsearch": "^1.1.0" + }, + "engines": { + "node": ">=10.16.0" + } + }, + "node_modules/call-bind": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.7.tgz", + "integrity": "sha512-GHTSNSYICQ7scH7sZ+M2rFopRoLh8t2bLSW6BbgrtLsahOIB5iyAVJf9GjWK3cYTDaMj4XdBpM1cA6pIS0Kv2w==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-define-property": "^1.0.0", + "es-errors": "^1.3.0", + "function-bind": "^1.1.2", + "get-intrinsic": "^1.2.4", + "set-function-length": "^1.2.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/callsites": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz", + "integrity": "sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/camelcase-css": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/camelcase-css/-/camelcase-css-2.0.1.tgz", + "integrity": "sha512-QOSvevhslijgYwRx6Rv7zKdMF8lbRmx+uQGx2+vDc+KI/eBnsy9kit5aj23AgGu3pa4t9AgwbnXWqS+iOY+2aA==", + "license": "MIT", + "engines": { + "node": ">= 6" + } + }, + "node_modules/caniuse-lite": { + "version": "1.0.30001660", + "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001660.tgz", + "integrity": "sha512-GacvNTTuATm26qC74pt+ad1fW15mlQ/zuTzzY1ZoIzECTP8HURDfF43kNxPgf7H1jmelCBQTTbBNxdSXOA7Bqg==", + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/caniuse-lite" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "CC-BY-4.0" + }, + "node_modules/ccount": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/ccount/-/ccount-2.0.1.tgz", + "integrity": "sha512-eyrF0jiFpY+3drT6383f1qhkbGsLSifNAjA61IUjZjmLCWjItY6LB9ft9YhoDgwfmclB2zhu51Lc7+95b8NRAg==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/chalk": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", + "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/character-entities": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/character-entities/-/character-entities-1.2.4.tgz", + "integrity": "sha512-iBMyeEHxfVnIakwOuDXpVkc54HijNgCyQB2w0VfGQThle6NXn50zU6V/u+LDhxHcDUPojn6Kpga3PTAD8W1bQw==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/character-entities-html4": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/character-entities-html4/-/character-entities-html4-2.1.0.tgz", + "integrity": "sha512-1v7fgQRj6hnSwFpq1Eu0ynr/CDEw0rXo2B61qXrLNdHZmPKgb7fqS1a2JwF0rISo9q77jDI8VMEHoApn8qDoZA==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/character-entities-legacy": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/character-entities-legacy/-/character-entities-legacy-1.1.4.tgz", + "integrity": "sha512-3Xnr+7ZFS1uxeiUDvV02wQ+QDbc55o97tIV5zHScSPJpcLm/r0DFPcoY3tYRp+VZukxuMeKgXYmsXQHO05zQeA==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/character-reference-invalid": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/character-reference-invalid/-/character-reference-invalid-1.1.4.tgz", + "integrity": "sha512-mKKUkUbhPpQlCOfIuZkvSEgktjPFIsZKRRbC6KWVEMvlzblj3i3asQv5ODsrwt0N3pHAEvjP8KTQPHkp0+6jOg==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/chokidar": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.6.0.tgz", + "integrity": "sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw==", + "license": "MIT", + "dependencies": { + "anymatch": "~3.1.2", + "braces": "~3.0.2", + "glob-parent": "~5.1.2", + "is-binary-path": "~2.1.0", + "is-glob": "~4.0.1", + "normalize-path": "~3.0.0", + "readdirp": "~3.6.0" + }, + "engines": { + "node": ">= 8.10.0" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + }, + "optionalDependencies": { + "fsevents": "~2.3.2" + } + }, + "node_modules/chokidar/node_modules/glob-parent": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz", + "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==", + "license": "ISC", + "dependencies": { + "is-glob": "^4.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/class-variance-authority": { + "version": "0.7.0", + "resolved": "https://registry.npmjs.org/class-variance-authority/-/class-variance-authority-0.7.0.tgz", + "integrity": "sha512-jFI8IQw4hczaL4ALINxqLEXQbWcNjoSkloa4IaufXCJr6QawJyw7tuRysRsrE8w2p/4gGaxKIt/hX3qz/IbD1A==", + "license": "Apache-2.0", + "dependencies": { + "clsx": "2.0.0" + }, + "funding": { + "url": "https://joebell.co.uk" + } + }, + "node_modules/class-variance-authority/node_modules/clsx": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/clsx/-/clsx-2.0.0.tgz", + "integrity": "sha512-rQ1+kcj+ttHG0MKVGBUXwayCCF1oh39BF5COIpRzuCEv8Mwjv0XucrI2ExNTOn9IlLifGClWQcU9BrZORvtw6Q==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/classnames": { + "version": "2.5.1", + "resolved": "https://registry.npmjs.org/classnames/-/classnames-2.5.1.tgz", + "integrity": "sha512-saHYOzhIQs6wy2sVxTM6bUDsQO4F50V9RQ22qBpEdCW+I+/Wmke2HOl6lS6dTpdxVhb88/I6+Hs+438c3lfUow==", + "license": "MIT" + }, + "node_modules/client-only": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/client-only/-/client-only-0.0.1.tgz", + "integrity": "sha512-IV3Ou0jSMzZrd3pZ48nLkT9DA7Ag1pnPzaiQhpW7c3RbcqqzvzzVu+L8gfqMp/8IM2MQtSiqaCxrrcfu8I8rMA==", + "license": "MIT" + }, + "node_modules/clsx": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/clsx/-/clsx-2.1.1.tgz", + "integrity": "sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/cmdk": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/cmdk/-/cmdk-1.0.0.tgz", + "integrity": "sha512-gDzVf0a09TvoJ5jnuPvygTB77+XdOSwEmJ88L6XPFPlv7T3RxbP9jgenfylrAMD0+Le1aO0nVjQUzl2g+vjz5Q==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-dialog": "1.0.5", + "@radix-ui/react-primitive": "1.0.3" + }, + "peerDependencies": { + "react": "^18.0.0", + "react-dom": "^18.0.0" + } + }, + "node_modules/cmdk/node_modules/@radix-ui/primitive": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@radix-ui/primitive/-/primitive-1.0.1.tgz", + "integrity": "sha512-yQ8oGX2GVsEYMWGxcovu1uGWPCxV5BFfeeYxqPmuAzUyLT9qmaMXSAhXpb0WrspIeqYzdJpkh2vHModJPgRIaw==", + "license": "MIT", + "dependencies": { + "@babel/runtime": "^7.13.10" + } + }, + "node_modules/cmdk/node_modules/@radix-ui/react-compose-refs": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@radix-ui/react-compose-refs/-/react-compose-refs-1.0.1.tgz", + "integrity": "sha512-fDSBgd44FKHa1FRMU59qBMPFcl2PZE+2nmqunj+BWFyYYjnhIDWL2ItDs3rrbJDQOtzt5nIebLCQc4QRfz6LJw==", + "license": "MIT", + "dependencies": { + "@babel/runtime": "^7.13.10" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/cmdk/node_modules/@radix-ui/react-context": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@radix-ui/react-context/-/react-context-1.0.1.tgz", + "integrity": "sha512-ebbrdFoYTcuZ0v4wG5tedGnp9tzcV8awzsxYph7gXUyvnNLuTIcCk1q17JEbnVhXAKG9oX3KtchwiMIAYp9NLg==", + "license": "MIT", + "dependencies": { + "@babel/runtime": "^7.13.10" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/cmdk/node_modules/@radix-ui/react-dialog": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/@radix-ui/react-dialog/-/react-dialog-1.0.5.tgz", + "integrity": "sha512-GjWJX/AUpB703eEBanuBnIWdIXg6NvJFCXcNlSZk4xdszCdhrJgBoUd1cGk67vFO+WdA2pfI/plOpqz/5GUP6Q==", + "license": "MIT", + "dependencies": { + "@babel/runtime": "^7.13.10", + "@radix-ui/primitive": "1.0.1", + "@radix-ui/react-compose-refs": "1.0.1", + "@radix-ui/react-context": "1.0.1", + "@radix-ui/react-dismissable-layer": "1.0.5", + "@radix-ui/react-focus-guards": "1.0.1", + "@radix-ui/react-focus-scope": "1.0.4", + "@radix-ui/react-id": "1.0.1", + "@radix-ui/react-portal": "1.0.4", + "@radix-ui/react-presence": "1.0.1", + "@radix-ui/react-primitive": "1.0.3", + "@radix-ui/react-slot": "1.0.2", + "@radix-ui/react-use-controllable-state": "1.0.1", + "aria-hidden": "^1.1.1", + "react-remove-scroll": "2.5.5" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0", + "react-dom": "^16.8 || ^17.0 || ^18.0" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/cmdk/node_modules/@radix-ui/react-dismissable-layer": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/@radix-ui/react-dismissable-layer/-/react-dismissable-layer-1.0.5.tgz", + "integrity": "sha512-aJeDjQhywg9LBu2t/At58hCvr7pEm0o2Ke1x33B+MhjNmmZ17sy4KImo0KPLgsnc/zN7GPdce8Cnn0SWvwZO7g==", + "license": "MIT", + "dependencies": { + "@babel/runtime": "^7.13.10", + "@radix-ui/primitive": "1.0.1", + "@radix-ui/react-compose-refs": "1.0.1", + "@radix-ui/react-primitive": "1.0.3", + "@radix-ui/react-use-callback-ref": "1.0.1", + "@radix-ui/react-use-escape-keydown": "1.0.3" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0", + "react-dom": "^16.8 || ^17.0 || ^18.0" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/cmdk/node_modules/@radix-ui/react-focus-guards": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@radix-ui/react-focus-guards/-/react-focus-guards-1.0.1.tgz", + "integrity": "sha512-Rect2dWbQ8waGzhMavsIbmSVCgYxkXLxxR3ZvCX79JOglzdEy4JXMb98lq4hPxUbLr77nP0UOGf4rcMU+s1pUA==", + "license": "MIT", + "dependencies": { + "@babel/runtime": "^7.13.10" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/cmdk/node_modules/@radix-ui/react-focus-scope": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/@radix-ui/react-focus-scope/-/react-focus-scope-1.0.4.tgz", + "integrity": "sha512-sL04Mgvf+FmyvZeYfNu1EPAaaxD+aw7cYeIB9L9Fvq8+urhltTRaEo5ysKOpHuKPclsZcSUMKlN05x4u+CINpA==", + "license": "MIT", + "dependencies": { + "@babel/runtime": "^7.13.10", + "@radix-ui/react-compose-refs": "1.0.1", + "@radix-ui/react-primitive": "1.0.3", + "@radix-ui/react-use-callback-ref": "1.0.1" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0", + "react-dom": "^16.8 || ^17.0 || ^18.0" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/cmdk/node_modules/@radix-ui/react-id": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@radix-ui/react-id/-/react-id-1.0.1.tgz", + "integrity": "sha512-tI7sT/kqYp8p96yGWY1OAnLHrqDgzHefRBKQ2YAkBS5ja7QLcZ9Z/uY7bEjPUatf8RomoXM8/1sMj1IJaE5UzQ==", + "license": "MIT", + "dependencies": { + "@babel/runtime": "^7.13.10", + "@radix-ui/react-use-layout-effect": "1.0.1" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/cmdk/node_modules/@radix-ui/react-portal": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/@radix-ui/react-portal/-/react-portal-1.0.4.tgz", + "integrity": "sha512-Qki+C/EuGUVCQTOTD5vzJzJuMUlewbzuKyUy+/iHM2uwGiru9gZeBJtHAPKAEkB5KWGi9mP/CHKcY0wt1aW45Q==", + "license": "MIT", + "dependencies": { + "@babel/runtime": "^7.13.10", + "@radix-ui/react-primitive": "1.0.3" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0", + "react-dom": "^16.8 || ^17.0 || ^18.0" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/cmdk/node_modules/@radix-ui/react-presence": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@radix-ui/react-presence/-/react-presence-1.0.1.tgz", + "integrity": "sha512-UXLW4UAbIY5ZjcvzjfRFo5gxva8QirC9hF7wRE4U5gz+TP0DbRk+//qyuAQ1McDxBt1xNMBTaciFGvEmJvAZCg==", + "license": "MIT", + "dependencies": { + "@babel/runtime": "^7.13.10", + "@radix-ui/react-compose-refs": "1.0.1", + "@radix-ui/react-use-layout-effect": "1.0.1" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0", + "react-dom": "^16.8 || ^17.0 || ^18.0" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/cmdk/node_modules/@radix-ui/react-primitive": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/@radix-ui/react-primitive/-/react-primitive-1.0.3.tgz", + "integrity": "sha512-yi58uVyoAcK/Nq1inRY56ZSjKypBNKTa/1mcL8qdl6oJeEaDbOldlzrGn7P6Q3Id5d+SYNGc5AJgc4vGhjs5+g==", + "license": "MIT", + "dependencies": { + "@babel/runtime": "^7.13.10", + "@radix-ui/react-slot": "1.0.2" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0", + "react-dom": "^16.8 || ^17.0 || ^18.0" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/cmdk/node_modules/@radix-ui/react-slot": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/@radix-ui/react-slot/-/react-slot-1.0.2.tgz", + "integrity": "sha512-YeTpuq4deV+6DusvVUW4ivBgnkHwECUu0BiN43L5UCDFgdhsRUWAghhTF5MbvNTPzmiFOx90asDSUjWuCNapwg==", + "license": "MIT", + "dependencies": { + "@babel/runtime": "^7.13.10", + "@radix-ui/react-compose-refs": "1.0.1" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/cmdk/node_modules/@radix-ui/react-use-callback-ref": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-callback-ref/-/react-use-callback-ref-1.0.1.tgz", + "integrity": "sha512-D94LjX4Sp0xJFVaoQOd3OO9k7tpBYNOXdVhkltUbGv2Qb9OXdrg/CpsjlZv7ia14Sylv398LswWBVVu5nqKzAQ==", + "license": "MIT", + "dependencies": { + "@babel/runtime": "^7.13.10" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/cmdk/node_modules/@radix-ui/react-use-controllable-state": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-controllable-state/-/react-use-controllable-state-1.0.1.tgz", + "integrity": "sha512-Svl5GY5FQeN758fWKrjM6Qb7asvXeiZltlT4U2gVfl8Gx5UAv2sMR0LWo8yhsIZh2oQ0eFdZ59aoOOMV7b47VA==", + "license": "MIT", + "dependencies": { + "@babel/runtime": "^7.13.10", + "@radix-ui/react-use-callback-ref": "1.0.1" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/cmdk/node_modules/@radix-ui/react-use-escape-keydown": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-escape-keydown/-/react-use-escape-keydown-1.0.3.tgz", + "integrity": "sha512-vyL82j40hcFicA+M4Ex7hVkB9vHgSse1ZWomAqV2Je3RleKGO5iM8KMOEtfoSB0PnIelMd2lATjTGMYqN5ylTg==", + "license": "MIT", + "dependencies": { + "@babel/runtime": "^7.13.10", + "@radix-ui/react-use-callback-ref": "1.0.1" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/cmdk/node_modules/@radix-ui/react-use-layout-effect": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-layout-effect/-/react-use-layout-effect-1.0.1.tgz", + "integrity": "sha512-v/5RegiJWYdoCvMnITBkNNx6bCj20fiaJnWtRkU18yITptraXjffz5Qbn05uOiQnOvi+dbkznkoaMltz1GnszQ==", + "license": "MIT", + "dependencies": { + "@babel/runtime": "^7.13.10" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/cmdk/node_modules/react-remove-scroll": { + "version": "2.5.5", + "resolved": "https://registry.npmjs.org/react-remove-scroll/-/react-remove-scroll-2.5.5.tgz", + "integrity": "sha512-ImKhrzJJsyXJfBZ4bzu8Bwpka14c/fQt0k+cyFp/PBhTfyDnU5hjOtM4AG/0AMyy8oKzOTR0lDgJIM7pYXI0kw==", + "license": "MIT", + "dependencies": { + "react-remove-scroll-bar": "^2.3.3", + "react-style-singleton": "^2.2.1", + "tslib": "^2.1.0", + "use-callback-ref": "^1.3.0", + "use-sidecar": "^1.1.2" + }, + "engines": { + "node": ">=10" + }, + "peerDependencies": { + "@types/react": "^16.8.0 || ^17.0.0 || ^18.0.0", + "react": "^16.8.0 || ^17.0.0 || ^18.0.0" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "license": "MIT", + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "license": "MIT" + }, + "node_modules/comma-separated-tokens": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/comma-separated-tokens/-/comma-separated-tokens-1.0.8.tgz", + "integrity": "sha512-GHuDRO12Sypu2cV70d1dkA2EUmXHgntrzbpvOB+Qy+49ypNfGgFQIC2fhhXbnyrJRynDCAARsT7Ou0M6hirpfw==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/commander": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/commander/-/commander-4.1.1.tgz", + "integrity": "sha512-NOKm8xhkzAjzFx8B2v5OAHT+u5pRQc2UCa2Vq9jYL/31o2wi9mxBA7LIFs3sV5VSC49z6pEhfbMULvShKj26WA==", + "license": "MIT", + "engines": { + "node": ">= 6" + } + }, + "node_modules/concat-map": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", + "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==", + "dev": true, + "license": "MIT" + }, + "node_modules/convert-source-map": { + "version": "1.9.0", + "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-1.9.0.tgz", + "integrity": "sha512-ASFBup0Mz1uyiIjANan1jzLQami9z1PoYSZCiiYW2FczPbenXc45FZdBZLzOT+r6+iciuEModtmCti+hjaAk0A==", + "license": "MIT" + }, + "node_modules/cosmiconfig": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/cosmiconfig/-/cosmiconfig-7.1.0.tgz", + "integrity": "sha512-AdmX6xUzdNASswsFtmwSt7Vj8po9IuqXm0UXz7QKPuEUmPB4XyjGfaAr2PSuELMwkRMVH1EpIkX5bTZGRB3eCA==", + "license": "MIT", + "dependencies": { + "@types/parse-json": "^4.0.0", + "import-fresh": "^3.2.1", + "parse-json": "^5.0.0", + "path-type": "^4.0.0", + "yaml": "^1.10.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/cosmiconfig/node_modules/yaml": { + "version": "1.10.2", + "resolved": "https://registry.npmjs.org/yaml/-/yaml-1.10.2.tgz", + "integrity": "sha512-r3vXyErRCYJ7wg28yvBY5VSoAF8ZvlcW9/BwUzEtUsjvX/DKs24dIkuwjtuprwJJHsbyUbLApepYTR1BN4uHrg==", + "license": "ISC", + "engines": { + "node": ">= 6" + } + }, + "node_modules/cross-spawn": { + "version": "7.0.3", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.3.tgz", + "integrity": "sha512-iRDPJKUPVEND7dHPO8rkbOnPpyDygcDFtWjpeWNCgy8WP2rXcxXL8TskReQl6OrB2G7+UJrags1q15Fudc7G6w==", + "license": "MIT", + "dependencies": { + "path-key": "^3.1.0", + "shebang-command": "^2.0.0", + "which": "^2.0.1" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/cssesc": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/cssesc/-/cssesc-3.0.0.tgz", + "integrity": "sha512-/Tb/JcjK111nNScGob5MNtsntNM1aCNUDipB/TkwZFhyDrrE47SOx/18wF2bbjgc3ZzCSKW1T5nt5EbFoAz/Vg==", + "license": "MIT", + "bin": { + "cssesc": "bin/cssesc" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/csstype": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.1.3.tgz", + "integrity": "sha512-M1uQkMl8rQK/szD0LNhtqxIPLpimGm8sOBwU7lLnCpSbTyY3yeU1Vc7l4KT5zT4s/yOxHH5O7tIuuLOCnLADRw==", + "license": "MIT" + }, + "node_modules/damerau-levenshtein": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/damerau-levenshtein/-/damerau-levenshtein-1.0.8.tgz", + "integrity": "sha512-sdQSFB7+llfUcQHUQO3+B8ERRj0Oa4w9POWMI/puGtuf7gFywGmkaLCElnudfTiKZV+NvHqL0ifzdrI8Ro7ESA==", + "dev": true, + "license": "BSD-2-Clause" + }, + "node_modules/data-view-buffer": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/data-view-buffer/-/data-view-buffer-1.0.1.tgz", + "integrity": "sha512-0lht7OugA5x3iJLOWFhWK/5ehONdprk0ISXqVFn/NFrDu+cuc8iADFrGQz5BnRK7LLU3JmkbXSxaqX+/mXYtUA==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.6", + "es-errors": "^1.3.0", + "is-data-view": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/data-view-byte-length": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/data-view-byte-length/-/data-view-byte-length-1.0.1.tgz", + "integrity": "sha512-4J7wRJD3ABAzr8wP+OcIcqq2dlUKp4DVflx++hs5h5ZKydWMI6/D/fAot+yh6g2tHh8fLFTvNOaVN357NvSrOQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.7", + "es-errors": "^1.3.0", + "is-data-view": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/data-view-byte-offset": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/data-view-byte-offset/-/data-view-byte-offset-1.0.0.tgz", + "integrity": "sha512-t/Ygsytq+R995EJ5PZlD4Cu56sWa8InXySaViRzw9apusqsOO2bQP+SbYzAhR0pFKoB+43lYy8rWban9JSuXnA==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.6", + "es-errors": "^1.3.0", + "is-data-view": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/date-fns": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/date-fns/-/date-fns-4.1.0.tgz", + "integrity": "sha512-Ukq0owbQXxa/U3EGtsdVBkR1w7KOQ5gIBqdH2hkvknzZPYvBxb/aa6E8L7tmjFtkwZBu3UXBbjIgPo/Ez4xaNg==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/kossnocorp" + } + }, + "node_modules/debug": { + "version": "4.3.7", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.7.tgz", + "integrity": "sha512-Er2nc/H7RrMXZBFCEim6TCmMk02Z8vLC2Rbi1KEBggpo0fS6l0S1nnapwmIi3yW/+GOJap1Krg4w0Hg80oCqgQ==", + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/deep-equal": { + "version": "2.2.3", + "resolved": "https://registry.npmjs.org/deep-equal/-/deep-equal-2.2.3.tgz", + "integrity": "sha512-ZIwpnevOurS8bpT4192sqAowWM76JDKSHYzMLty3BZGSswgq6pBaH3DhCSW5xVAZICZyKdOBPjwww5wfgT/6PA==", + "dev": true, + "license": "MIT", + "dependencies": { + "array-buffer-byte-length": "^1.0.0", + "call-bind": "^1.0.5", + "es-get-iterator": "^1.1.3", + "get-intrinsic": "^1.2.2", + "is-arguments": "^1.1.1", + "is-array-buffer": "^3.0.2", + "is-date-object": "^1.0.5", + "is-regex": "^1.1.4", + "is-shared-array-buffer": "^1.0.2", + "isarray": "^2.0.5", + "object-is": "^1.1.5", + "object-keys": "^1.1.1", + "object.assign": "^4.1.4", + "regexp.prototype.flags": "^1.5.1", + "side-channel": "^1.0.4", + "which-boxed-primitive": "^1.0.2", + "which-collection": "^1.0.1", + "which-typed-array": "^1.1.13" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/deep-is": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.4.tgz", + "integrity": "sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/define-data-property": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/define-data-property/-/define-data-property-1.1.4.tgz", + "integrity": "sha512-rBMvIzlpA8v6E+SJZoo++HAYqsLrkg7MSfIinMPFhmkorw7X+dOXVJQs+QT69zGkzMyfDnIMN2Wid1+NbL3T+A==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-define-property": "^1.0.0", + "es-errors": "^1.3.0", + "gopd": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/define-properties": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/define-properties/-/define-properties-1.2.1.tgz", + "integrity": "sha512-8QmQKqEASLd5nx0U1B1okLElbUuuttJ/AnYmRXbbbGDWh6uS208EjD4Xqq/I9wK7u0v6O08XhTWnt5XtEbR6Dg==", + "dev": true, + "license": "MIT", + "dependencies": { + "define-data-property": "^1.0.1", + "has-property-descriptors": "^1.0.0", + "object-keys": "^1.1.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/dequal": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/dequal/-/dequal-2.0.3.tgz", + "integrity": "sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/detect-node-es": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/detect-node-es/-/detect-node-es-1.1.0.tgz", + "integrity": "sha512-ypdmJU/TbBby2Dxibuv7ZLW3Bs1QEmM7nHjEANfohJLvE0XVujisn1qPJcZxg+qDucsr+bP6fLD1rPS3AhJ7EQ==", + "license": "MIT" + }, + "node_modules/devlop": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/devlop/-/devlop-1.1.0.tgz", + "integrity": "sha512-RWmIqhcFf1lRYBvNmr7qTNuyCt/7/ns2jbpp1+PalgE/rDQcBT0fioSMUpJ93irlUhC5hrg4cYqe6U+0ImW0rA==", + "license": "MIT", + "dependencies": { + "dequal": "^2.0.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/didyoumean": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/didyoumean/-/didyoumean-1.2.2.tgz", + "integrity": "sha512-gxtyfqMg7GKyhQmb056K7M3xszy/myH8w+B4RT+QXBQsvAOdc3XymqDDPHx1BgPgsdAA5SIifona89YtRATDzw==", + "license": "Apache-2.0" + }, + "node_modules/dir-glob": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/dir-glob/-/dir-glob-3.0.1.tgz", + "integrity": "sha512-WkrWp9GR4KXfKGYzOLmTuGVi1UWFfws377n9cc55/tb6DuqyF6pcQ5AbiHEshaDpY9v6oaSr2XCDidGmMwdzIA==", + "dev": true, + "license": "MIT", + "dependencies": { + "path-type": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/dlv": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/dlv/-/dlv-1.1.3.tgz", + "integrity": "sha512-+HlytyjlPKnIG8XuRG8WvmBP8xs8P71y+SKKS6ZXWoEgLuePxtDoUEiH7WkdePWrQ5JBpE6aoVqfZfJUQkjXwA==", + "license": "MIT" + }, + "node_modules/doctrine": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/doctrine/-/doctrine-3.0.0.tgz", + "integrity": "sha512-yS+Q5i3hBf7GBkd4KG8a7eBNNWNGLTaEwwYWUijIYM7zrlYDM0BFXHjjPWlWZ1Rg7UaddZeIDmi9jF3HmqiQ2w==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "esutils": "^2.0.2" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/dom-helpers": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/dom-helpers/-/dom-helpers-5.2.1.tgz", + "integrity": "sha512-nRCa7CK3VTrM2NmGkIy4cbK7IZlgBE/PYMn55rrXefr5xXDP0LdtfPnblFDoVdcAfslJ7or6iqAUnx0CCGIWQA==", + "license": "MIT", + "dependencies": { + "@babel/runtime": "^7.8.7", + "csstype": "^3.0.2" + } + }, + "node_modules/dotenv": { + "version": "16.4.5", + "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.4.5.tgz", + "integrity": "sha512-ZmdL2rui+eB2YwhsWzjInR8LldtZHGDoQ1ugH85ppHKwpUHL7j7rN0Ti9NCnGiQbhaZ11FpR+7ao1dNsmduNUg==", + "license": "BSD-2-Clause", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://dotenvx.com" + } + }, + "node_modules/eastasianwidth": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/eastasianwidth/-/eastasianwidth-0.2.0.tgz", + "integrity": "sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA==", + "license": "MIT" + }, + "node_modules/emoji-regex": { + "version": "9.2.2", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-9.2.2.tgz", + "integrity": "sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg==", + "license": "MIT" + }, + "node_modules/enhanced-resolve": { + "version": "5.17.1", + "resolved": "https://registry.npmjs.org/enhanced-resolve/-/enhanced-resolve-5.17.1.tgz", + "integrity": "sha512-LMHl3dXhTcfv8gM4kEzIUeTQ+7fpdA0l2tUf34BddXPkz2A5xJ5L/Pchd5BL6rdccM9QGvu0sWZzK1Z1t4wwyg==", + "dev": true, + "license": "MIT", + "dependencies": { + "graceful-fs": "^4.2.4", + "tapable": "^2.2.0" + }, + "engines": { + "node": ">=10.13.0" + } + }, + "node_modules/err-code": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/err-code/-/err-code-3.0.1.tgz", + "integrity": "sha512-GiaH0KJUewYok+eeY05IIgjtAe4Yltygk9Wqp1V5yVWLdhf0hYZchRjNIT9bb0mSwRcIusT3cx7PJUf3zEIfUA==" + }, + "node_modules/error-ex": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/error-ex/-/error-ex-1.3.2.tgz", + "integrity": "sha512-7dFHNmqeFSEt2ZBsCriorKnn3Z2pj+fd9kmI6QoWw4//DL+icEBfc0U7qJCisqrTsKTjw4fNFy2pW9OqStD84g==", + "license": "MIT", + "dependencies": { + "is-arrayish": "^0.2.1" + } + }, + "node_modules/es-abstract": { + "version": "1.23.3", + "resolved": "https://registry.npmjs.org/es-abstract/-/es-abstract-1.23.3.tgz", + "integrity": "sha512-e+HfNH61Bj1X9/jLc5v1owaLYuHdeHHSQlkhCBiTK8rBvKaULl/beGMxwrMXjpYrv4pz22BlY570vVePA2ho4A==", + "dev": true, + "license": "MIT", + "dependencies": { + "array-buffer-byte-length": "^1.0.1", + "arraybuffer.prototype.slice": "^1.0.3", + "available-typed-arrays": "^1.0.7", + "call-bind": "^1.0.7", + "data-view-buffer": "^1.0.1", + "data-view-byte-length": "^1.0.1", + "data-view-byte-offset": "^1.0.0", + "es-define-property": "^1.0.0", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.0.0", + "es-set-tostringtag": "^2.0.3", + "es-to-primitive": "^1.2.1", + "function.prototype.name": "^1.1.6", + "get-intrinsic": "^1.2.4", + "get-symbol-description": "^1.0.2", + "globalthis": "^1.0.3", + "gopd": "^1.0.1", + "has-property-descriptors": "^1.0.2", + "has-proto": "^1.0.3", + "has-symbols": "^1.0.3", + "hasown": "^2.0.2", + "internal-slot": "^1.0.7", + "is-array-buffer": "^3.0.4", + "is-callable": "^1.2.7", + "is-data-view": "^1.0.1", + "is-negative-zero": "^2.0.3", + "is-regex": "^1.1.4", + "is-shared-array-buffer": "^1.0.3", + "is-string": "^1.0.7", + "is-typed-array": "^1.1.13", + "is-weakref": "^1.0.2", + "object-inspect": "^1.13.1", + "object-keys": "^1.1.1", + "object.assign": "^4.1.5", + "regexp.prototype.flags": "^1.5.2", + "safe-array-concat": "^1.1.2", + "safe-regex-test": "^1.0.3", + "string.prototype.trim": "^1.2.9", + "string.prototype.trimend": "^1.0.8", + "string.prototype.trimstart": "^1.0.8", + "typed-array-buffer": "^1.0.2", + "typed-array-byte-length": "^1.0.1", + "typed-array-byte-offset": "^1.0.2", + "typed-array-length": "^1.0.6", + "unbox-primitive": "^1.0.2", + "which-typed-array": "^1.1.15" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/es-define-property": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.0.tgz", + "integrity": "sha512-jxayLKShrEqqzJ0eumQbVhTYQM27CfT1T35+gCgDFoL82JLsXqTJ76zv6A0YLOgEnLUMvLzsDsGIrl8NFpT2gQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "get-intrinsic": "^1.2.4" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-get-iterator": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/es-get-iterator/-/es-get-iterator-1.1.3.tgz", + "integrity": "sha512-sPZmqHBe6JIiTfN5q2pEi//TwxmAFHwj/XEuYjTuse78i8KxaqMTTzxPoFKuzRpDpTJ+0NAbpfenkmH2rePtuw==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.2", + "get-intrinsic": "^1.1.3", + "has-symbols": "^1.0.3", + "is-arguments": "^1.1.1", + "is-map": "^2.0.2", + "is-set": "^2.0.2", + "is-string": "^1.0.7", + "isarray": "^2.0.5", + "stop-iteration-iterator": "^1.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/es-iterator-helpers": { + "version": "1.0.19", + "resolved": "https://registry.npmjs.org/es-iterator-helpers/-/es-iterator-helpers-1.0.19.tgz", + "integrity": "sha512-zoMwbCcH5hwUkKJkT8kDIBZSz9I6mVG//+lDCinLCGov4+r7NIy0ld8o03M0cJxl2spVf6ESYVS6/gpIfq1FFw==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.7", + "define-properties": "^1.2.1", + "es-abstract": "^1.23.3", + "es-errors": "^1.3.0", + "es-set-tostringtag": "^2.0.3", + "function-bind": "^1.1.2", + "get-intrinsic": "^1.2.4", + "globalthis": "^1.0.3", + "has-property-descriptors": "^1.0.2", + "has-proto": "^1.0.3", + "has-symbols": "^1.0.3", + "internal-slot": "^1.0.7", + "iterator.prototype": "^1.1.2", + "safe-array-concat": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-object-atoms": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.0.0.tgz", + "integrity": "sha512-MZ4iQ6JwHOBQjahnjwaC1ZtIBH+2ohjamzAO3oaHcXYup7qxjF2fixyH+Q71voWHeOkI2q/TnJao/KfXYIZWbw==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-set-tostringtag": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.0.3.tgz", + "integrity": "sha512-3T8uNMC3OQTHkFUsFq8r/BwAXLHvU/9O9mE0fBc/MY5iq/8H7ncvO947LmYA6ldWw9Uh8Yhf25zu6n7nML5QWQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "get-intrinsic": "^1.2.4", + "has-tostringtag": "^1.0.2", + "hasown": "^2.0.1" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-shim-unscopables": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/es-shim-unscopables/-/es-shim-unscopables-1.0.2.tgz", + "integrity": "sha512-J3yBRXCzDu4ULnQwxyToo/OjdMx6akgVC7K6few0a7F/0wLtmKKN7I73AH5T2836UuXRqN7Qg+IIUw/+YJksRw==", + "dev": true, + "license": "MIT", + "dependencies": { + "hasown": "^2.0.0" + } + }, + "node_modules/es-to-primitive": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/es-to-primitive/-/es-to-primitive-1.2.1.tgz", + "integrity": "sha512-QCOllgZJtaUo9miYBcLChTUaHNjJF3PYs1VidD7AwiEj1kYxKeQTctLAezAOH5ZKRH0g2IgPn6KwB4IT8iRpvA==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-callable": "^1.1.4", + "is-date-object": "^1.0.1", + "is-symbol": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/escape-string-regexp": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz", + "integrity": "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==", + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/eslint": { + "version": "8.57.1", + "resolved": "https://registry.npmjs.org/eslint/-/eslint-8.57.1.tgz", + "integrity": "sha512-ypowyDxpVSYpkXr9WPv2PAZCtNip1Mv5KTW0SCurXv/9iOpcrH9PaqUElksqEB6pChqHGDRCFTyrZlGhnLNGiA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@eslint-community/eslint-utils": "^4.2.0", + "@eslint-community/regexpp": "^4.6.1", + "@eslint/eslintrc": "^2.1.4", + "@eslint/js": "8.57.1", + "@humanwhocodes/config-array": "^0.13.0", + "@humanwhocodes/module-importer": "^1.0.1", + "@nodelib/fs.walk": "^1.2.8", + "@ungap/structured-clone": "^1.2.0", + "ajv": "^6.12.4", + "chalk": "^4.0.0", + "cross-spawn": "^7.0.2", + "debug": "^4.3.2", + "doctrine": "^3.0.0", + "escape-string-regexp": "^4.0.0", + "eslint-scope": "^7.2.2", + "eslint-visitor-keys": "^3.4.3", + "espree": "^9.6.1", + "esquery": "^1.4.2", + "esutils": "^2.0.2", + "fast-deep-equal": "^3.1.3", + "file-entry-cache": "^6.0.1", + "find-up": "^5.0.0", + "glob-parent": "^6.0.2", + "globals": "^13.19.0", + "graphemer": "^1.4.0", + "ignore": "^5.2.0", + "imurmurhash": "^0.1.4", + "is-glob": "^4.0.0", + "is-path-inside": "^3.0.3", + "js-yaml": "^4.1.0", + "json-stable-stringify-without-jsonify": "^1.0.1", + "levn": "^0.4.1", + "lodash.merge": "^4.6.2", + "minimatch": "^3.1.2", + "natural-compare": "^1.4.0", + "optionator": "^0.9.3", + "strip-ansi": "^6.0.1", + "text-table": "^0.2.0" + }, + "bin": { + "eslint": "bin/eslint.js" + }, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/eslint-config-next": { + "version": "14.2.11", + "resolved": "https://registry.npmjs.org/eslint-config-next/-/eslint-config-next-14.2.11.tgz", + "integrity": "sha512-gGIoBoHCJuLn6vaV1Ke8UurVvgb7JjQv6oRlWmI6RAAxz7KwJOYxxm2blctavA0a3eofbE9TdgKvvTb2G55OHQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@next/eslint-plugin-next": "14.2.11", + "@rushstack/eslint-patch": "^1.3.3", + "@typescript-eslint/eslint-plugin": "^5.4.2 || ^6.0.0 || 7.0.0 - 7.2.0", + "@typescript-eslint/parser": "^5.4.2 || ^6.0.0 || 7.0.0 - 7.2.0", + "eslint-import-resolver-node": "^0.3.6", + "eslint-import-resolver-typescript": "^3.5.2", + "eslint-plugin-import": "^2.28.1", + "eslint-plugin-jsx-a11y": "^6.7.1", + "eslint-plugin-react": "^7.33.2", + "eslint-plugin-react-hooks": "^4.5.0 || 5.0.0-canary-7118f5dd7-20230705" + }, + "peerDependencies": { + "eslint": "^7.23.0 || ^8.0.0", + "typescript": ">=3.3.1" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/eslint-import-resolver-node": { + "version": "0.3.9", + "resolved": "https://registry.npmjs.org/eslint-import-resolver-node/-/eslint-import-resolver-node-0.3.9.tgz", + "integrity": "sha512-WFj2isz22JahUv+B788TlO3N6zL3nNJGU8CcZbPZvVEkBPaJdCV4vy5wyghty5ROFbCRnm132v8BScu5/1BQ8g==", + "dev": true, + "license": "MIT", + "dependencies": { + "debug": "^3.2.7", + "is-core-module": "^2.13.0", + "resolve": "^1.22.4" + } + }, + "node_modules/eslint-import-resolver-node/node_modules/debug": { + "version": "3.2.7", + "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.7.tgz", + "integrity": "sha512-CFjzYYAi4ThfiQvizrFQevTTXHtnCqWfe7x1AhgEscTz6ZbLbfoLRLPugTQyBth6f8ZERVUSyWHFD/7Wu4t1XQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "ms": "^2.1.1" + } + }, + "node_modules/eslint-import-resolver-typescript": { + "version": "3.6.3", + "resolved": "https://registry.npmjs.org/eslint-import-resolver-typescript/-/eslint-import-resolver-typescript-3.6.3.tgz", + "integrity": "sha512-ud9aw4szY9cCT1EWWdGv1L1XR6hh2PaRWif0j2QjQ0pgTY/69iw+W0Z4qZv5wHahOl8isEr+k/JnyAqNQkLkIA==", + "dev": true, + "license": "ISC", + "dependencies": { + "@nolyfill/is-core-module": "1.0.39", + "debug": "^4.3.5", + "enhanced-resolve": "^5.15.0", + "eslint-module-utils": "^2.8.1", + "fast-glob": "^3.3.2", + "get-tsconfig": "^4.7.5", + "is-bun-module": "^1.0.2", + "is-glob": "^4.0.3" + }, + "engines": { + "node": "^14.18.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/unts/projects/eslint-import-resolver-ts" + }, + "peerDependencies": { + "eslint": "*", + "eslint-plugin-import": "*", + "eslint-plugin-import-x": "*" + }, + "peerDependenciesMeta": { + "eslint-plugin-import": { + "optional": true + }, + "eslint-plugin-import-x": { + "optional": true + } + } + }, + "node_modules/eslint-module-utils": { + "version": "2.11.0", + "resolved": "https://registry.npmjs.org/eslint-module-utils/-/eslint-module-utils-2.11.0.tgz", + "integrity": "sha512-gbBE5Hitek/oG6MUVj6sFuzEjA/ClzNflVrLovHi/JgLdC7fiN5gLAY1WIPW1a0V5I999MnsrvVrCOGmmVqDBQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "debug": "^3.2.7" + }, + "engines": { + "node": ">=4" + }, + "peerDependenciesMeta": { + "eslint": { + "optional": true + } + } + }, + "node_modules/eslint-module-utils/node_modules/debug": { + "version": "3.2.7", + "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.7.tgz", + "integrity": "sha512-CFjzYYAi4ThfiQvizrFQevTTXHtnCqWfe7x1AhgEscTz6ZbLbfoLRLPugTQyBth6f8ZERVUSyWHFD/7Wu4t1XQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "ms": "^2.1.1" + } + }, + "node_modules/eslint-plugin-import": { + "version": "2.30.0", + "resolved": "https://registry.npmjs.org/eslint-plugin-import/-/eslint-plugin-import-2.30.0.tgz", + "integrity": "sha512-/mHNE9jINJfiD2EKkg1BKyPyUk4zdnT54YgbOgfjSakWT5oyX/qQLVNTkehyfpcMxZXMy1zyonZ2v7hZTX43Yw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@rtsao/scc": "^1.1.0", + "array-includes": "^3.1.8", + "array.prototype.findlastindex": "^1.2.5", + "array.prototype.flat": "^1.3.2", + "array.prototype.flatmap": "^1.3.2", + "debug": "^3.2.7", + "doctrine": "^2.1.0", + "eslint-import-resolver-node": "^0.3.9", + "eslint-module-utils": "^2.9.0", + "hasown": "^2.0.2", + "is-core-module": "^2.15.1", + "is-glob": "^4.0.3", + "minimatch": "^3.1.2", + "object.fromentries": "^2.0.8", + "object.groupby": "^1.0.3", + "object.values": "^1.2.0", + "semver": "^6.3.1", + "tsconfig-paths": "^3.15.0" + }, + "engines": { + "node": ">=4" + }, + "peerDependencies": { + "eslint": "^2 || ^3 || ^4 || ^5 || ^6 || ^7.2.0 || ^8" + } + }, + "node_modules/eslint-plugin-import/node_modules/debug": { + "version": "3.2.7", + "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.7.tgz", + "integrity": "sha512-CFjzYYAi4ThfiQvizrFQevTTXHtnCqWfe7x1AhgEscTz6ZbLbfoLRLPugTQyBth6f8ZERVUSyWHFD/7Wu4t1XQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "ms": "^2.1.1" + } + }, + "node_modules/eslint-plugin-import/node_modules/doctrine": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/doctrine/-/doctrine-2.1.0.tgz", + "integrity": "sha512-35mSku4ZXK0vfCuHEDAwt55dg2jNajHZ1odvF+8SSr82EsZY4QmXfuWso8oEd8zRhVObSN18aM0CjSdoBX7zIw==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "esutils": "^2.0.2" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/eslint-plugin-import/node_modules/semver": { + "version": "6.3.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", + "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + } + }, + "node_modules/eslint-plugin-jsx-a11y": { + "version": "6.10.0", + "resolved": "https://registry.npmjs.org/eslint-plugin-jsx-a11y/-/eslint-plugin-jsx-a11y-6.10.0.tgz", + "integrity": "sha512-ySOHvXX8eSN6zz8Bywacm7CvGNhUtdjvqfQDVe6020TUK34Cywkw7m0KsCCk1Qtm9G1FayfTN1/7mMYnYO2Bhg==", + "dev": true, + "license": "MIT", + "dependencies": { + "aria-query": "~5.1.3", + "array-includes": "^3.1.8", + "array.prototype.flatmap": "^1.3.2", + "ast-types-flow": "^0.0.8", + "axe-core": "^4.10.0", + "axobject-query": "^4.1.0", + "damerau-levenshtein": "^1.0.8", + "emoji-regex": "^9.2.2", + "es-iterator-helpers": "^1.0.19", + "hasown": "^2.0.2", + "jsx-ast-utils": "^3.3.5", + "language-tags": "^1.0.9", + "minimatch": "^3.1.2", + "object.fromentries": "^2.0.8", + "safe-regex-test": "^1.0.3", + "string.prototype.includes": "^2.0.0" + }, + "engines": { + "node": ">=4.0" + }, + "peerDependencies": { + "eslint": "^3 || ^4 || ^5 || ^6 || ^7 || ^8 || ^9" + } + }, + "node_modules/eslint-plugin-react": { + "version": "7.36.1", + "resolved": "https://registry.npmjs.org/eslint-plugin-react/-/eslint-plugin-react-7.36.1.tgz", + "integrity": "sha512-/qwbqNXZoq+VP30s1d4Nc1C5GTxjJQjk4Jzs4Wq2qzxFM7dSmuG2UkIjg2USMLh3A/aVcUNrK7v0J5U1XEGGwA==", + "dev": true, + "license": "MIT", + "dependencies": { + "array-includes": "^3.1.8", + "array.prototype.findlast": "^1.2.5", + "array.prototype.flatmap": "^1.3.2", + "array.prototype.tosorted": "^1.1.4", + "doctrine": "^2.1.0", + "es-iterator-helpers": "^1.0.19", + "estraverse": "^5.3.0", + "hasown": "^2.0.2", + "jsx-ast-utils": "^2.4.1 || ^3.0.0", + "minimatch": "^3.1.2", + "object.entries": "^1.1.8", + "object.fromentries": "^2.0.8", + "object.values": "^1.2.0", + "prop-types": "^15.8.1", + "resolve": "^2.0.0-next.5", + "semver": "^6.3.1", + "string.prototype.matchall": "^4.0.11", + "string.prototype.repeat": "^1.0.0" + }, + "engines": { + "node": ">=4" + }, + "peerDependencies": { + "eslint": "^3 || ^4 || ^5 || ^6 || ^7 || ^8 || ^9.7" + } + }, + "node_modules/eslint-plugin-react-hooks": { + "version": "4.6.2", + "resolved": "https://registry.npmjs.org/eslint-plugin-react-hooks/-/eslint-plugin-react-hooks-4.6.2.tgz", + "integrity": "sha512-QzliNJq4GinDBcD8gPB5v0wh6g8q3SUi6EFF0x8N/BL9PoVs0atuGc47ozMRyOWAKdwaZ5OnbOEa3WR+dSGKuQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "peerDependencies": { + "eslint": "^3.0.0 || ^4.0.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0-0" + } + }, + "node_modules/eslint-plugin-react/node_modules/doctrine": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/doctrine/-/doctrine-2.1.0.tgz", + "integrity": "sha512-35mSku4ZXK0vfCuHEDAwt55dg2jNajHZ1odvF+8SSr82EsZY4QmXfuWso8oEd8zRhVObSN18aM0CjSdoBX7zIw==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "esutils": "^2.0.2" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/eslint-plugin-react/node_modules/resolve": { + "version": "2.0.0-next.5", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-2.0.0-next.5.tgz", + "integrity": "sha512-U7WjGVG9sH8tvjW5SmGbQuui75FiyjAX72HX15DwBBwF9dNiQZRQAg9nnPhYy+TUnE0+VcrttuvNI8oSxZcocA==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-core-module": "^2.13.0", + "path-parse": "^1.0.7", + "supports-preserve-symlinks-flag": "^1.0.0" + }, + "bin": { + "resolve": "bin/resolve" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/eslint-plugin-react/node_modules/semver": { + "version": "6.3.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", + "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + } + }, + "node_modules/eslint-scope": { + "version": "7.2.2", + "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-7.2.2.tgz", + "integrity": "sha512-dOt21O7lTMhDM+X9mB4GX+DZrZtCUJPL/wlcTqxyrx5IvO0IYtILdtrQGQp+8n5S0gwSVmOf9NQrjMOgfQZlIg==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "esrecurse": "^4.3.0", + "estraverse": "^5.2.0" + }, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/eslint-visitor-keys": { + "version": "3.4.3", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-3.4.3.tgz", + "integrity": "sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/espree": { + "version": "9.6.1", + "resolved": "https://registry.npmjs.org/espree/-/espree-9.6.1.tgz", + "integrity": "sha512-oruZaFkjorTpF32kDSI5/75ViwGeZginGGy2NoOSg3Q9bnwlnmDm4HLnkl0RE3n+njDXR037aY1+x58Z/zFdwQ==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "acorn": "^8.9.0", + "acorn-jsx": "^5.3.2", + "eslint-visitor-keys": "^3.4.1" + }, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/esquery": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/esquery/-/esquery-1.6.0.tgz", + "integrity": "sha512-ca9pw9fomFcKPvFLXhBKUK90ZvGibiGOvRJNbjljY7s7uq/5YO4BOzcYtJqExdx99rF6aAcnRxHmcUHcz6sQsg==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "estraverse": "^5.1.0" + }, + "engines": { + "node": ">=0.10" + } + }, + "node_modules/esrecurse": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/esrecurse/-/esrecurse-4.3.0.tgz", + "integrity": "sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "estraverse": "^5.2.0" + }, + "engines": { + "node": ">=4.0" + } + }, + "node_modules/estraverse": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz", + "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=4.0" + } + }, + "node_modules/esutils": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.3.tgz", + "integrity": "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/eventsource": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/eventsource/-/eventsource-2.0.2.tgz", + "integrity": "sha512-IzUmBGPR3+oUG9dUeXynyNmf91/3zUSJg1lCktzKw47OXuhco54U3r9B7O4XX+Rb1Itm9OZ2b0RkTs10bICOxA==", + "license": "MIT", + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/exenv": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/exenv/-/exenv-1.2.2.tgz", + "integrity": "sha512-Z+ktTxTwv9ILfgKCk32OX3n/doe+OcLTRtqK9pcL+JsP3J1/VW8Uvl4ZjLlKqeW4rzK4oesDOGMEMRIZqtP4Iw==", + "license": "BSD-3-Clause" + }, + "node_modules/fast-deep-equal": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", + "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", + "dev": true, + "license": "MIT" + }, + "node_modules/fast-glob": { + "version": "3.3.2", + "resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.3.2.tgz", + "integrity": "sha512-oX2ruAFQwf/Orj8m737Y5adxDQO0LAB7/S5MnxCdTNDd4p6BsyIVsv9JQsATbTSq8KHRpLwIHbVlUNatxd+1Ow==", + "license": "MIT", + "dependencies": { + "@nodelib/fs.stat": "^2.0.2", + "@nodelib/fs.walk": "^1.2.3", + "glob-parent": "^5.1.2", + "merge2": "^1.3.0", + "micromatch": "^4.0.4" + }, + "engines": { + "node": ">=8.6.0" + } + }, + "node_modules/fast-glob/node_modules/glob-parent": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz", + "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==", + "license": "ISC", + "dependencies": { + "is-glob": "^4.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/fast-json-stable-stringify": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz", + "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==", + "dev": true, + "license": "MIT" + }, + "node_modules/fast-levenshtein": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz", + "integrity": "sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw==", + "dev": true, + "license": "MIT" + }, + "node_modules/fastq": { + "version": "1.17.1", + "resolved": "https://registry.npmjs.org/fastq/-/fastq-1.17.1.tgz", + "integrity": "sha512-sRVD3lWVIXWg6By68ZN7vho9a1pQcN/WBFaAAsDDFzlJjvoGx0P8z7V1t72grFJfJhu3YPZBuu25f7Kaw2jN1w==", + "license": "ISC", + "dependencies": { + "reusify": "^1.0.4" + } + }, + "node_modules/fault": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/fault/-/fault-1.0.4.tgz", + "integrity": "sha512-CJ0HCB5tL5fYTEA7ToAq5+kTwd++Borf1/bifxd9iT70QcXr4MRrO3Llf8Ifs70q+SJcGHFtnIE/Nw6giCtECA==", + "license": "MIT", + "dependencies": { + "format": "^0.2.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/faye-websocket": { + "version": "0.11.4", + "resolved": "https://registry.npmjs.org/faye-websocket/-/faye-websocket-0.11.4.tgz", + "integrity": "sha512-CzbClwlXAuiRQAlUyfqPgvPoNKTckTPGfwZV4ZdAhVcP2lh9KUxJg2b5GkE7XbjKQ3YJnQ9z6D9ntLAlB+tP8g==", + "license": "Apache-2.0", + "dependencies": { + "websocket-driver": ">=0.5.1" + }, + "engines": { + "node": ">=0.8.0" + } + }, + "node_modules/file-entry-cache": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-6.0.1.tgz", + "integrity": "sha512-7Gps/XWymbLk2QLYK4NzpMOrYjMhdIxXuIvy2QBsLE6ljuodKvdkWs/cpyJJ3CVIVpH0Oi1Hvg1ovbMzLdFBBg==", + "dev": true, + "license": "MIT", + "dependencies": { + "flat-cache": "^3.0.4" + }, + "engines": { + "node": "^10.12.0 || >=12.0.0" + } + }, + "node_modules/fill-range": { + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz", + "integrity": "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==", + "license": "MIT", + "dependencies": { + "to-regex-range": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/find-root": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/find-root/-/find-root-1.1.0.tgz", + "integrity": "sha512-NKfW6bec6GfKc0SGx1e07QZY9PE99u0Bft/0rzSD5k3sO/vwkVUpDUKVm5Gpp5Ue3YfShPFTX2070tDs5kB9Ng==", + "license": "MIT" + }, + "node_modules/find-up": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-5.0.0.tgz", + "integrity": "sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng==", + "dev": true, + "license": "MIT", + "dependencies": { + "locate-path": "^6.0.0", + "path-exists": "^4.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/flat-cache": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/flat-cache/-/flat-cache-3.2.0.tgz", + "integrity": "sha512-CYcENa+FtcUKLmhhqyctpclsq7QF38pKjZHsGNiSQF5r4FtoKDWabFDl3hzaEQMvT1LHEysw5twgLvpYYb4vbw==", + "dev": true, + "license": "MIT", + "dependencies": { + "flatted": "^3.2.9", + "keyv": "^4.5.3", + "rimraf": "^3.0.2" + }, + "engines": { + "node": "^10.12.0 || >=12.0.0" + } + }, + "node_modules/flatted": { + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/flatted/-/flatted-3.3.1.tgz", + "integrity": "sha512-X8cqMLLie7KsNUDSdzeN8FYK9rEt4Dt67OsG/DNGnYTSDBG4uFAJFBnUeiV+zCVAvwFy56IjM9sH51jVaEhNxw==", + "dev": true, + "license": "ISC" + }, + "node_modules/for-each": { + "version": "0.3.3", + "resolved": "https://registry.npmjs.org/for-each/-/for-each-0.3.3.tgz", + "integrity": "sha512-jqYfLp7mo9vIyQf8ykW2v7A+2N4QjeCeI5+Dz9XraiO1ign81wjiH7Fb9vSOWvQfNtmSa4H2RoQTrrXivdUZmw==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-callable": "^1.1.3" + } + }, + "node_modules/foreground-child": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/foreground-child/-/foreground-child-3.3.0.tgz", + "integrity": "sha512-Ld2g8rrAyMYFXBhEqMz8ZAHBi4J4uS1i/CxGMDnjyFWddMXLVcDp051DZfu+t7+ab7Wv6SMqpWmyFIj5UbfFvg==", + "license": "ISC", + "dependencies": { + "cross-spawn": "^7.0.0", + "signal-exit": "^4.0.1" + }, + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/format": { + "version": "0.2.2", + "resolved": "https://registry.npmjs.org/format/-/format-0.2.2.tgz", + "integrity": "sha512-wzsgA6WOq+09wrU1tsJ09udeR/YZRaeArL9e1wPbFg3GG2yDnC2ldKpxs4xunpFF9DgqCqOIra3bc1HWrJ37Ww==", + "engines": { + "node": ">=0.4.x" + } + }, + "node_modules/framer-motion": { + "version": "11.9.0", + "resolved": "https://registry.npmjs.org/framer-motion/-/framer-motion-11.9.0.tgz", + "integrity": "sha512-nCfGxvsQecVLjjYDu35G2F5ls+ArE3FBfhxV0RSiisMaUKqteq5DMBFNRKwMyVj+VqKTNhawt+BV480YCHKFlQ==", + "license": "MIT", + "dependencies": { + "tslib": "^2.4.0" + }, + "peerDependencies": { + "@emotion/is-prop-valid": "*", + "react": "^18.0.0", + "react-dom": "^18.0.0" + }, + "peerDependenciesMeta": { + "@emotion/is-prop-valid": { + "optional": true + }, + "react": { + "optional": true + }, + "react-dom": { + "optional": true + } + } + }, + "node_modules/fs.realpath": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", + "integrity": "sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==", + "dev": true, + "license": "ISC" + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/function.prototype.name": { + "version": "1.1.6", + "resolved": "https://registry.npmjs.org/function.prototype.name/-/function.prototype.name-1.1.6.tgz", + "integrity": "sha512-Z5kx79swU5P27WEayXM1tBi5Ze/lbIyiNgU3qyXUOf9b2rgXYyF9Dy9Cx+IQv/Lc8WCG6L82zwUPpSS9hGehIg==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.2", + "define-properties": "^1.2.0", + "es-abstract": "^1.22.1", + "functions-have-names": "^1.2.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/functions-have-names": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/functions-have-names/-/functions-have-names-1.2.3.tgz", + "integrity": "sha512-xckBUXyTIqT97tq2x2AMb+g163b5JFysYk0x4qxNFwbfQkmNZoiRHb6sPzI9/QV33WeuvVYBUIiD4NzNIyqaRQ==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-browser-rtc": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/get-browser-rtc/-/get-browser-rtc-1.1.0.tgz", + "integrity": "sha512-MghbMJ61EJrRsDe7w1Bvqt3ZsBuqhce5nrn/XAwgwOXhcsz53/ltdxOse1h/8eKXj5slzxdsz56g5rzOFSGwfQ==" + }, + "node_modules/get-intrinsic": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.2.4.tgz", + "integrity": "sha512-5uYhsJH8VJBTv7oslg4BznJYhDoRI6waYCxMmCdnTrcCrHA/fCFKoTFz2JKKE0HdDFUF7/oQuhzumXJK7paBRQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2", + "has-proto": "^1.0.1", + "has-symbols": "^1.0.3", + "hasown": "^2.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-nonce": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/get-nonce/-/get-nonce-1.0.1.tgz", + "integrity": "sha512-FJhYRoDaiatfEkUK8HKlicmu/3SGFD51q3itKDGoSTysQJBnfOcxU5GxnhE1E6soB76MbT0MBtnKJuXyAx+96Q==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/get-symbol-description": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/get-symbol-description/-/get-symbol-description-1.0.2.tgz", + "integrity": "sha512-g0QYk1dZBxGwk+Ngc+ltRH2IBp2f7zBkBMBJZCDerh6EhlhSR6+9irMCuT/09zD6qkarHUSn529sK/yL4S27mg==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.5", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.4" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-tsconfig": { + "version": "4.8.1", + "resolved": "https://registry.npmjs.org/get-tsconfig/-/get-tsconfig-4.8.1.tgz", + "integrity": "sha512-k9PN+cFBmaLWtVz29SkUoqU5O0slLuHJXt/2P+tMVFT+phsSGXGkp9t3rQIqdz0e+06EHNGs3oM6ZX1s2zHxRg==", + "dev": true, + "license": "MIT", + "dependencies": { + "resolve-pkg-maps": "^1.0.0" + }, + "funding": { + "url": "https://github.com/privatenumber/get-tsconfig?sponsor=1" + } + }, + "node_modules/glob": { + "version": "10.3.10", + "resolved": "https://registry.npmjs.org/glob/-/glob-10.3.10.tgz", + "integrity": "sha512-fa46+tv1Ak0UPK1TOy/pZrIybNNt4HCv7SDzwyfiOZkvZLEbjsZkJBPtDHVshZjbecAoAGSC20MjLDG/qr679g==", + "license": "ISC", + "dependencies": { + "foreground-child": "^3.1.0", + "jackspeak": "^2.3.5", + "minimatch": "^9.0.1", + "minipass": "^5.0.0 || ^6.0.2 || ^7.0.0", + "path-scurry": "^1.10.1" + }, + "bin": { + "glob": "dist/esm/bin.mjs" + }, + "engines": { + "node": ">=16 || 14 >=14.17" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/glob-parent": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-6.0.2.tgz", + "integrity": "sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==", + "license": "ISC", + "dependencies": { + "is-glob": "^4.0.3" + }, + "engines": { + "node": ">=10.13.0" + } + }, + "node_modules/glob/node_modules/brace-expansion": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.1.tgz", + "integrity": "sha512-XnAIvQ8eM+kC6aULx6wuQiwVsnzsi9d3WxzV3FpWTGA19F621kwdbsAcFKXgKUHZWsy+mY6iL1sHTxWEFCytDA==", + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0" + } + }, + "node_modules/glob/node_modules/minimatch": { + "version": "9.0.5", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-9.0.5.tgz", + "integrity": "sha512-G6T0ZX48xgozx7587koeX9Ys2NYy6Gmv//P89sEte9V9whIapMNF4idKxnW2QtCcLiTWlb/wfCabAtAFWhhBow==", + "license": "ISC", + "dependencies": { + "brace-expansion": "^2.0.1" + }, + "engines": { + "node": ">=16 || 14 >=14.17" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/globals": { + "version": "13.24.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-13.24.0.tgz", + "integrity": "sha512-AhO5QUcj8llrbG09iWhPU2B204J1xnPeL8kQmVorSsy+Sjj1sk8gIyh6cUocGmH4L0UuhAJy+hJMRA4mgA4mFQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "type-fest": "^0.20.2" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/globalthis": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/globalthis/-/globalthis-1.0.4.tgz", + "integrity": "sha512-DpLKbNU4WylpxJykQujfCcwYWiV/Jhm50Goo0wrVILAv5jOr9d+H+UR3PhSCD2rCCEIg0uc+G+muBTwD54JhDQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "define-properties": "^1.2.1", + "gopd": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/globby": { + "version": "11.1.0", + "resolved": "https://registry.npmjs.org/globby/-/globby-11.1.0.tgz", + "integrity": "sha512-jhIXaOzy1sb8IyocaruWSn1TjmnBVs8Ayhcy83rmxNJ8q2uWKCAj3CnJY+KpGSXCueAPc0i05kVvVKtP1t9S3g==", + "dev": true, + "license": "MIT", + "dependencies": { + "array-union": "^2.1.0", + "dir-glob": "^3.0.1", + "fast-glob": "^3.2.9", + "ignore": "^5.2.0", + "merge2": "^1.4.1", + "slash": "^3.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/gopd": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.0.1.tgz", + "integrity": "sha512-d65bNlIadxvpb/A2abVdlqKqV563juRnZ1Wtk6s1sIR8uNsXR70xqIzVqxVf1eTqDunwT2MkczEeaezCKTZhwA==", + "dev": true, + "license": "MIT", + "dependencies": { + "get-intrinsic": "^1.1.3" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/graceful-fs": { + "version": "4.2.11", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz", + "integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==", + "license": "ISC" + }, + "node_modules/graphemer": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/graphemer/-/graphemer-1.4.0.tgz", + "integrity": "sha512-EtKwoO6kxCL9WO5xipiHTZlSzBm7WLT627TqC/uVRd0HKmq8NXyebnNYxDoBi7wt8eTWrUrKXCOVaFq9x1kgag==", + "dev": true, + "license": "MIT" + }, + "node_modules/has-bigints": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-bigints/-/has-bigints-1.0.2.tgz", + "integrity": "sha512-tSvCKtBr9lkF0Ex0aQiP9N+OpV4zi2r/Nee5VkRDbaqv35RLYMzbwQfFSZZH0kR+Rd6302UJZ2p/bJCEoR3VoQ==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/has-property-descriptors": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-property-descriptors/-/has-property-descriptors-1.0.2.tgz", + "integrity": "sha512-55JNKuIW+vq4Ke1BjOTjM2YctQIvCT7GFzHwmfZPGo5wnrgkid0YQtnAleFSqumZm4az3n2BS+erby5ipJdgrg==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-define-property": "^1.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-proto": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/has-proto/-/has-proto-1.0.3.tgz", + "integrity": "sha512-SJ1amZAJUiZS+PhsVLf5tGydlaVB8EdFpaSO4gmiUKUOxk8qzn5AIy4ZeJUmh22znIdk/uMAUT2pl3FxzVUH+Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-symbols": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.3.tgz", + "integrity": "sha512-l3LCuF6MgDNwTDKkdYGEihYjt5pRPbEg46rtlmnSPlUbgmB8LOIrKJbYYFBSbnPaJexMKtiPO8hmeRjRz2Td+A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-tostringtag": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz", + "integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==", + "dev": true, + "license": "MIT", + "dependencies": { + "has-symbols": "^1.0.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/hasown": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz", + "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==", + "license": "MIT", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/hast-util-parse-selector": { + "version": "2.2.5", + "resolved": "https://registry.npmjs.org/hast-util-parse-selector/-/hast-util-parse-selector-2.2.5.tgz", + "integrity": "sha512-7j6mrk/qqkSehsM92wQjdIgWM2/BW61u/53G6xmC8i1OmEdKLHbk419QKQUjz6LglWsfqoiHmyMRkP1BGjecNQ==", + "license": "MIT", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/hast-util-to-html": { + "version": "9.0.3", + "resolved": "https://registry.npmjs.org/hast-util-to-html/-/hast-util-to-html-9.0.3.tgz", + "integrity": "sha512-M17uBDzMJ9RPCqLMO92gNNUDuBSq10a25SDBI08iCCxmorf4Yy6sYHK57n9WAbRAAaU+DuR4W6GN9K4DFZesYg==", + "license": "MIT", + "dependencies": { + "@types/hast": "^3.0.0", + "@types/unist": "^3.0.0", + "ccount": "^2.0.0", + "comma-separated-tokens": "^2.0.0", + "hast-util-whitespace": "^3.0.0", + "html-void-elements": "^3.0.0", + "mdast-util-to-hast": "^13.0.0", + "property-information": "^6.0.0", + "space-separated-tokens": "^2.0.0", + "stringify-entities": "^4.0.0", + "zwitch": "^2.0.4" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/hast-util-to-html/node_modules/@types/hast": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/@types/hast/-/hast-3.0.4.tgz", + "integrity": "sha512-WPs+bbQw5aCj+x6laNGWLH3wviHtoCv/P3+otBhbOhJgG8qtpdAMlTCxLtsTWA7LH1Oh/bFCHsBn0TPS5m30EQ==", + "license": "MIT", + "dependencies": { + "@types/unist": "*" + } + }, + "node_modules/hast-util-to-html/node_modules/@types/unist": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/@types/unist/-/unist-3.0.3.tgz", + "integrity": "sha512-ko/gIFJRv177XgZsZcBwnqJN5x/Gien8qNOn0D5bQU/zAzVf9Zt3BlcUiLqhV9y4ARk0GbT3tnUiPNgnTXzc/Q==", + "license": "MIT" + }, + "node_modules/hast-util-to-html/node_modules/comma-separated-tokens": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/comma-separated-tokens/-/comma-separated-tokens-2.0.3.tgz", + "integrity": "sha512-Fu4hJdvzeylCfQPp9SGWidpzrMs7tTrlu6Vb8XGaRGck8QSNZJJp538Wrb60Lax4fPwR64ViY468OIUTbRlGZg==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/hast-util-to-html/node_modules/property-information": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/property-information/-/property-information-6.5.0.tgz", + "integrity": "sha512-PgTgs/BlvHxOu8QuEN7wi5A0OmXaBcHpmCSTehcs6Uuu9IkDIEo13Hy7n898RHfrQ49vKCoGeWZSaAK01nwVig==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/hast-util-to-html/node_modules/space-separated-tokens": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/space-separated-tokens/-/space-separated-tokens-2.0.2.tgz", + "integrity": "sha512-PEGlAwrG8yXGXRjW32fGbg66JAlOAwbObuqVoJpv/mRgoWDQfgH1wDPvtzWyUSNAXBGSk8h755YDbbcEy3SH2Q==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/hast-util-whitespace": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/hast-util-whitespace/-/hast-util-whitespace-3.0.0.tgz", + "integrity": "sha512-88JUN06ipLwsnv+dVn+OIYOvAuvBMy/Qoi6O7mQHxdPXpjy+Cd6xRkWwux7DKO+4sYILtLBRIKgsdpS2gQc7qw==", + "license": "MIT", + "dependencies": { + "@types/hast": "^3.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/hast-util-whitespace/node_modules/@types/hast": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/@types/hast/-/hast-3.0.4.tgz", + "integrity": "sha512-WPs+bbQw5aCj+x6laNGWLH3wviHtoCv/P3+otBhbOhJgG8qtpdAMlTCxLtsTWA7LH1Oh/bFCHsBn0TPS5m30EQ==", + "license": "MIT", + "dependencies": { + "@types/unist": "*" + } + }, + "node_modules/hastscript": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/hastscript/-/hastscript-6.0.0.tgz", + "integrity": "sha512-nDM6bvd7lIqDUiYEiu5Sl/+6ReP0BMk/2f4U/Rooccxkj0P5nm+acM5PrGJ/t5I8qPGiqZSE6hVAwZEdZIvP4w==", + "license": "MIT", + "dependencies": { + "@types/hast": "^2.0.0", + "comma-separated-tokens": "^1.0.0", + "hast-util-parse-selector": "^2.0.0", + "property-information": "^5.0.0", + "space-separated-tokens": "^1.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/highlight.js": { + "version": "10.7.3", + "resolved": "https://registry.npmjs.org/highlight.js/-/highlight.js-10.7.3.tgz", + "integrity": "sha512-tzcUFauisWKNHaRkN4Wjl/ZA07gENAjFl3J/c480dprkGTg5EQstgaNFqBfUqCq54kZRIEcreTsAgF/m2quD7A==", + "license": "BSD-3-Clause", + "engines": { + "node": "*" + } + }, + "node_modules/highlightjs-vue": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/highlightjs-vue/-/highlightjs-vue-1.0.0.tgz", + "integrity": "sha512-PDEfEF102G23vHmPhLyPboFCD+BkMGu+GuJe2d9/eH4FsCwvgBpnc9n0pGE+ffKdph38s6foEZiEjdgHdzp+IA==", + "license": "CC0-1.0" + }, + "node_modules/hoist-non-react-statics": { + "version": "3.3.2", + "resolved": "https://registry.npmjs.org/hoist-non-react-statics/-/hoist-non-react-statics-3.3.2.tgz", + "integrity": "sha512-/gGivxi8JPKWNm/W0jSmzcMPpfpPLc3dY/6GxhX2hQ9iGj3aDfklV4ET7NjKpSinLpJ5vafa9iiGIEZg10SfBw==", + "license": "BSD-3-Clause", + "dependencies": { + "react-is": "^16.7.0" + } + }, + "node_modules/html-void-elements": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/html-void-elements/-/html-void-elements-3.0.0.tgz", + "integrity": "sha512-bEqo66MRXsUGxWHV5IP0PUiAWwoEjba4VCzg0LjFJBpchPaTfyfCKTG6bc5F8ucKec3q5y6qOdGyYTSBEvhCrg==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/http-parser-js": { + "version": "0.5.8", + "resolved": "https://registry.npmjs.org/http-parser-js/-/http-parser-js-0.5.8.tgz", + "integrity": "sha512-SGeBX54F94Wgu5RH3X5jsDtf4eHyRogWX1XGT3b4HuW3tQPM4AaBzoUji/4AAJNXCEOWZ5O0DgZmJw1947gD5Q==", + "license": "MIT" + }, + "node_modules/ieee754": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz", + "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] + }, + "node_modules/ignore": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz", + "integrity": "sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 4" + } + }, + "node_modules/import-fresh": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/import-fresh/-/import-fresh-3.3.0.tgz", + "integrity": "sha512-veYYhQa+D1QBKznvhUHxb8faxlrwUnxseDAbAp457E0wLNio2bOSKnjYDhMj+YiAq61xrMGhQk9iXVk5FzgQMw==", + "license": "MIT", + "dependencies": { + "parent-module": "^1.0.0", + "resolve-from": "^4.0.0" + }, + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/imurmurhash": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz", + "integrity": "sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.8.19" + } + }, + "node_modules/inflight": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", + "integrity": "sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA==", + "deprecated": "This module is not supported, and leaks memory. Do not use it. Check out lru-cache if you want a good and tested way to coalesce async requests by a key value, which is much more comprehensive and powerful.", + "dev": true, + "license": "ISC", + "dependencies": { + "once": "^1.3.0", + "wrappy": "1" + } + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "license": "ISC" + }, + "node_modules/internal-slot": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/internal-slot/-/internal-slot-1.0.7.tgz", + "integrity": "sha512-NGnrKwXzSms2qUUih/ILZ5JBqNTSa1+ZmP6flaIp6KmSElgE9qdndzS3cqjrDovwFdmwsGsLdeFgB6suw+1e9g==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "hasown": "^2.0.0", + "side-channel": "^1.0.4" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/invariant": { + "version": "2.2.4", + "resolved": "https://registry.npmjs.org/invariant/-/invariant-2.2.4.tgz", + "integrity": "sha512-phJfQVBuaJM5raOpJjSfkiD6BpbCE4Ns//LaXl6wGYtUBY83nWS6Rf9tXm2e8VaK60JEjYldbPif/A2B1C2gNA==", + "license": "MIT", + "dependencies": { + "loose-envify": "^1.0.0" + } + }, + "node_modules/is-alphabetical": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/is-alphabetical/-/is-alphabetical-1.0.4.tgz", + "integrity": "sha512-DwzsA04LQ10FHTZuL0/grVDk4rFoVH1pjAToYwBrHSxcrBIGQuXrQMtD5U1b0U2XVgKZCTLLP8u2Qxqhy3l2Vg==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/is-alphanumerical": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/is-alphanumerical/-/is-alphanumerical-1.0.4.tgz", + "integrity": "sha512-UzoZUr+XfVz3t3v4KyGEniVL9BDRoQtY7tOyrRybkVNjDFWyo1yhXNGrrBTQxp3ib9BLAWs7k2YKBQsFRkZG9A==", + "license": "MIT", + "dependencies": { + "is-alphabetical": "^1.0.0", + "is-decimal": "^1.0.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/is-arguments": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/is-arguments/-/is-arguments-1.1.1.tgz", + "integrity": "sha512-8Q7EARjzEnKpt/PCD7e1cgUS0a6X8u5tdSiMqXhojOdoV9TsMsiO+9VLC5vAmO8N7/GmXn7yjR8qnA6bVAEzfA==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.2", + "has-tostringtag": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-array-buffer": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/is-array-buffer/-/is-array-buffer-3.0.4.tgz", + "integrity": "sha512-wcjaerHw0ydZwfhiKbXJWLDY8A7yV7KhjQOpb83hGgGfId/aQa4TOvwyzn2PuswW2gPCYEL/nEAiSVpdOj1lXw==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.2", + "get-intrinsic": "^1.2.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-arrayish": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.2.1.tgz", + "integrity": "sha512-zz06S8t0ozoDXMG+ube26zeCTNXcKIPJZJi8hBrF4idCLms4CG9QtK7qBl1boi5ODzFpjswb5JPmHCbMpjaYzg==", + "license": "MIT" + }, + "node_modules/is-async-function": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/is-async-function/-/is-async-function-2.0.0.tgz", + "integrity": "sha512-Y1JXKrfykRJGdlDwdKlLpLyMIiWqWvuSd17TvZk68PLAOGOoF4Xyav1z0Xhoi+gCYjZVeC5SI+hYFOfvXmGRCA==", + "dev": true, + "license": "MIT", + "dependencies": { + "has-tostringtag": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-bigint": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/is-bigint/-/is-bigint-1.0.4.tgz", + "integrity": "sha512-zB9CruMamjym81i2JZ3UMn54PKGsQzsJeo6xvN3HJJ4CAsQNB6iRutp2To77OfCNuoxspsIhzaPoO1zyCEhFOg==", + "dev": true, + "license": "MIT", + "dependencies": { + "has-bigints": "^1.0.1" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-binary-path": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/is-binary-path/-/is-binary-path-2.1.0.tgz", + "integrity": "sha512-ZMERYes6pDydyuGidse7OsHxtbI7WVeUEozgR/g7rd0xUimYNlvZRE/K2MgZTjWy725IfelLeVcEM97mmtRGXw==", + "license": "MIT", + "dependencies": { + "binary-extensions": "^2.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/is-boolean-object": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/is-boolean-object/-/is-boolean-object-1.1.2.tgz", + "integrity": "sha512-gDYaKHJmnj4aWxyj6YHyXVpdQawtVLHU5cb+eztPGczf6cjuTdwve5ZIEfgXqH4e57An1D1AKf8CZ3kYrQRqYA==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.2", + "has-tostringtag": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-bun-module": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/is-bun-module/-/is-bun-module-1.2.1.tgz", + "integrity": "sha512-AmidtEM6D6NmUiLOvvU7+IePxjEjOzra2h0pSrsfSAcXwl/83zLLXDByafUJy9k/rKK0pvXMLdwKwGHlX2Ke6Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "semver": "^7.6.3" + } + }, + "node_modules/is-callable": { + "version": "1.2.7", + "resolved": "https://registry.npmjs.org/is-callable/-/is-callable-1.2.7.tgz", + "integrity": "sha512-1BC0BVFhS/p0qtw6enp8e+8OD0UrK0oFLztSjNzhcKA3WDuJxxAPXzPuPtKkjEY9UUoEWlX/8fgKeu2S8i9JTA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-core-module": { + "version": "2.15.1", + "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.15.1.tgz", + "integrity": "sha512-z0vtXSwucUJtANQWldhbtbt7BnL0vxiFjIdDLAatwhDYty2bad6s+rijD6Ri4YuYJubLzIJLUidCh09e1djEVQ==", + "license": "MIT", + "dependencies": { + "hasown": "^2.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-data-view": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/is-data-view/-/is-data-view-1.0.1.tgz", + "integrity": "sha512-AHkaJrsUVW6wq6JS8y3JnM/GJF/9cf+k20+iDzlSaJrinEo5+7vRiteOSwBhHRiAyQATN1AmY4hwzxJKPmYf+w==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-typed-array": "^1.1.13" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-date-object": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/is-date-object/-/is-date-object-1.0.5.tgz", + "integrity": "sha512-9YQaSxsAiSwcvS33MBk3wTCVnWK+HhF8VZR2jRxehM16QcVOdHqPn4VPHmRK4lSr38n9JriurInLcP90xsYNfQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "has-tostringtag": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-decimal": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/is-decimal/-/is-decimal-1.0.4.tgz", + "integrity": "sha512-RGdriMmQQvZ2aqaQq3awNA6dCGtKpiDFcOzrTWrDAT2MiWrKQVPmxLGHl7Y2nNu6led0kEyoX0enY0qXYsv9zw==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/is-extglob": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", + "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-finalizationregistry": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/is-finalizationregistry/-/is-finalizationregistry-1.0.2.tgz", + "integrity": "sha512-0by5vtUJs8iFQb5TYUHHPudOR+qXYIMKtiUzvLIZITZUjknFmziyBJuLhVRc+Ds0dREFlskDNJKYIdIzu/9pfw==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.2" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-fullwidth-code-point": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/is-generator-function": { + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/is-generator-function/-/is-generator-function-1.0.10.tgz", + "integrity": "sha512-jsEjy9l3yiXEQ+PsXdmBwEPcOxaXWLspKdplFUVI9vq1iZgIekeC0L167qeu86czQaxed3q/Uzuw0swL0irL8A==", + "dev": true, + "license": "MIT", + "dependencies": { + "has-tostringtag": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-glob": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", + "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", + "license": "MIT", + "dependencies": { + "is-extglob": "^2.1.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-hexadecimal": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/is-hexadecimal/-/is-hexadecimal-1.0.4.tgz", + "integrity": "sha512-gyPJuv83bHMpocVYoqof5VDiZveEoGoFL8m3BXNb2VW8Xs+rz9kqO8LOQ5DH6EsuvilT1ApazU0pyl+ytbPtlw==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/is-map": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/is-map/-/is-map-2.0.3.tgz", + "integrity": "sha512-1Qed0/Hr2m+YqxnM09CjA2d/i6YZNfF6R2oRAOj36eUdS6qIV/huPJNSEpKbupewFs+ZsJlxsjjPbc0/afW6Lw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-negative-zero": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/is-negative-zero/-/is-negative-zero-2.0.3.tgz", + "integrity": "sha512-5KoIu2Ngpyek75jXodFvnafB6DJgr3u8uuK0LEZJjrU19DrMD3EVERaR8sjz8CCGgpZvxPl9SuE1GMVPFHx1mw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-number": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", + "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", + "license": "MIT", + "engines": { + "node": ">=0.12.0" + } + }, + "node_modules/is-number-object": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/is-number-object/-/is-number-object-1.0.7.tgz", + "integrity": "sha512-k1U0IRzLMo7ZlYIfzRu23Oh6MiIFasgpb9X76eqfFZAqwH44UI4KTBvBYIZ1dSL9ZzChTB9ShHfLkR4pdW5krQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "has-tostringtag": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-path-inside": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/is-path-inside/-/is-path-inside-3.0.3.tgz", + "integrity": "sha512-Fd4gABb+ycGAmKou8eMftCupSir5lRxqf4aD/vd0cD2qc4HL07OjCeuHMr8Ro4CoMaeCKDB0/ECBOVWjTwUvPQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/is-regex": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/is-regex/-/is-regex-1.1.4.tgz", + "integrity": "sha512-kvRdxDsxZjhzUX07ZnLydzS1TU/TJlTUHHY4YLL87e37oUA49DfkLqgy+VjFocowy29cKvcSiu+kIv728jTTVg==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.2", + "has-tostringtag": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-set": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/is-set/-/is-set-2.0.3.tgz", + "integrity": "sha512-iPAjerrse27/ygGLxw+EBR9agv9Y6uLeYVJMu+QNCoouJ1/1ri0mGrcWpfCqFZuzzx3WjtwxG098X+n4OuRkPg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-shared-array-buffer": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/is-shared-array-buffer/-/is-shared-array-buffer-1.0.3.tgz", + "integrity": "sha512-nA2hv5XIhLR3uVzDDfCIknerhx8XUKnstuOERPNNIinXG7v9u+ohXF67vxm4TPTEPU6lm61ZkwP3c9PCB97rhg==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.7" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-string": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/is-string/-/is-string-1.0.7.tgz", + "integrity": "sha512-tE2UXzivje6ofPW7l23cjDOMa09gb7xlAqG6jG5ej6uPV32TlWP3NKPigtaGeHNu9fohccRYvIiZMfOOnOYUtg==", + "dev": true, + "license": "MIT", + "dependencies": { + "has-tostringtag": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-symbol": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/is-symbol/-/is-symbol-1.0.4.tgz", + "integrity": "sha512-C/CPBqKWnvdcxqIARxyOh4v1UUEOCHpgDa0WYgpKDFMszcrPcffg5uhwSgPCLD2WWxmq6isisz87tzT01tuGhg==", + "dev": true, + "license": "MIT", + "dependencies": { + "has-symbols": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-typed-array": { + "version": "1.1.13", + "resolved": "https://registry.npmjs.org/is-typed-array/-/is-typed-array-1.1.13.tgz", + "integrity": "sha512-uZ25/bUAlUY5fR4OKT4rZQEBrzQWYV9ZJYGGsUmEJ6thodVJ1HX64ePQ6Z0qPWP+m+Uq6e9UugrE38jeYsDSMw==", + "dev": true, + "license": "MIT", + "dependencies": { + "which-typed-array": "^1.1.14" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-weakmap": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/is-weakmap/-/is-weakmap-2.0.2.tgz", + "integrity": "sha512-K5pXYOm9wqY1RgjpL3YTkF39tni1XajUIkawTLUo9EZEVUFga5gSQJF8nNS7ZwJQ02y+1YCNYcMh+HIf1ZqE+w==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-weakref": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/is-weakref/-/is-weakref-1.0.2.tgz", + "integrity": "sha512-qctsuLZmIQ0+vSSMfoVvyFe2+GSEvnmZ2ezTup1SBse9+twCCeial6EEi3Nc2KFcf6+qz2FBPnjXsk8xhKSaPQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.2" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-weakset": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/is-weakset/-/is-weakset-2.0.3.tgz", + "integrity": "sha512-LvIm3/KWzS9oRFHugab7d+M/GcBXuXX5xZkzPmN+NxihdQlZUQ4dWuSV1xR/sq6upL1TJEDrfBgRepHFdBtSNQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.7", + "get-intrinsic": "^1.2.4" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/isarray": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-2.0.5.tgz", + "integrity": "sha512-xHjhDr3cNBK0BzdUJSPXZntQUx/mwMS5Rw4A7lPJ90XGAO6ISP/ePDNuo0vhqOZU+UD5JoodwCAAoZQd3FeAKw==", + "dev": true, + "license": "MIT" + }, + "node_modules/isexe": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", + "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==", + "license": "ISC" + }, + "node_modules/isomorphic.js": { + "version": "0.2.5", + "resolved": "https://registry.npmjs.org/isomorphic.js/-/isomorphic.js-0.2.5.tgz", + "integrity": "sha512-PIeMbHqMt4DnUP3MA/Flc0HElYjMXArsw1qwJZcm9sqR8mq3l8NYizFMty0pWwE/tzIGH3EKK5+jes5mAr85yw==", + "funding": { + "type": "GitHub Sponsors ❤", + "url": "https://github.com/sponsors/dmonad" + } + }, + "node_modules/iterator.prototype": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/iterator.prototype/-/iterator.prototype-1.1.2.tgz", + "integrity": "sha512-DR33HMMr8EzwuRL8Y9D3u2BMj8+RqSE850jfGu59kS7tbmPLzGkZmVSfyCFSDxuZiEY6Rzt3T2NA/qU+NwVj1w==", + "dev": true, + "license": "MIT", + "dependencies": { + "define-properties": "^1.2.1", + "get-intrinsic": "^1.2.1", + "has-symbols": "^1.0.3", + "reflect.getprototypeof": "^1.0.4", + "set-function-name": "^2.0.1" + } + }, + "node_modules/jackspeak": { + "version": "2.3.6", + "resolved": "https://registry.npmjs.org/jackspeak/-/jackspeak-2.3.6.tgz", + "integrity": "sha512-N3yCS/NegsOBokc8GAdM8UcmfsKiSS8cipheD/nivzr700H+nsMOxJjQnvwOcRYVuFkdH0wGUvW2WbXGmrZGbQ==", + "license": "BlueOak-1.0.0", + "dependencies": { + "@isaacs/cliui": "^8.0.2" + }, + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + }, + "optionalDependencies": { + "@pkgjs/parseargs": "^0.11.0" + } + }, + "node_modules/jiti": { + "version": "1.21.6", + "resolved": "https://registry.npmjs.org/jiti/-/jiti-1.21.6.tgz", + "integrity": "sha512-2yTgeWTWzMWkHu6Jp9NKgePDaYHbntiwvYuuJLbbN9vl7DC9DvXKOB2BC3ZZ92D3cvV/aflH0osDfwpHepQ53w==", + "license": "MIT", + "bin": { + "jiti": "bin/jiti.js" + } + }, + "node_modules/js-base64": { + "version": "3.7.7", + "resolved": "https://registry.npmjs.org/js-base64/-/js-base64-3.7.7.tgz", + "integrity": "sha512-7rCnleh0z2CkXhH67J8K1Ytz0b2Y+yxTPL+/KOJoa20hfnVQ/3/T6W/KflYI4bRHRagNeXeU2bkNGI3v1oS/lw==" + }, + "node_modules/js-cookie": { + "version": "3.0.5", + "resolved": "https://registry.npmjs.org/js-cookie/-/js-cookie-3.0.5.tgz", + "integrity": "sha512-cEiJEAEoIbWfCZYKWhVwFuvPX1gETRYPw6LlaTKoxD3s2AkXzkCjnp6h0V77ozyqj0jakteJ4YqDJT830+lVGw==", + "license": "MIT", + "engines": { + "node": ">=14" + } + }, + "node_modules/js-tokens": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", + "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", + "license": "MIT" + }, + "node_modules/js-yaml": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.0.tgz", + "integrity": "sha512-wpxZs9NoxZaJESJGIZTyDEaYpl0FKSA+FB9aJiyemKhMwkxQg63h4T1KJgUGHpTqPDNRcmmYLugrRjJlBtWvRA==", + "dev": true, + "license": "MIT", + "dependencies": { + "argparse": "^2.0.1" + }, + "bin": { + "js-yaml": "bin/js-yaml.js" + } + }, + "node_modules/jsesc": { + "version": "2.5.2", + "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-2.5.2.tgz", + "integrity": "sha512-OYu7XEzjkCQ3C5Ps3QIZsQfNpqoJyZZA99wd9aWd05NCtC5pWOkShK2mkL6HXQR6/Cy2lbNdPlZBpuQHXE63gA==", + "license": "MIT", + "bin": { + "jsesc": "bin/jsesc" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/json-buffer": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/json-buffer/-/json-buffer-3.0.1.tgz", + "integrity": "sha512-4bV5BfR2mqfQTJm+V5tPPdf+ZpuhiIvTuAB5g8kcrXOZpTT/QwwVRWBywX1ozr6lEuPdbHxwaJlm9G6mI2sfSQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/json-parse-even-better-errors": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/json-parse-even-better-errors/-/json-parse-even-better-errors-2.3.1.tgz", + "integrity": "sha512-xyFwyhro/JEof6Ghe2iz2NcXoj2sloNsWr/XsERDK/oiPCfaNhl5ONfp+jQdAZRQQ0IJWNzH9zIZF7li91kh2w==", + "license": "MIT" + }, + "node_modules/json-schema-traverse": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", + "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==", + "dev": true, + "license": "MIT" + }, + "node_modules/json-stable-stringify-without-jsonify": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/json-stable-stringify-without-jsonify/-/json-stable-stringify-without-jsonify-1.0.1.tgz", + "integrity": "sha512-Bdboy+l7tA3OGW6FjyFHWkP5LuByj1Tk33Ljyq0axyzdk9//JSi2u3fP1QSmd1KNwq6VOKYGlAu87CisVir6Pw==", + "dev": true, + "license": "MIT" + }, + "node_modules/json5": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/json5/-/json5-1.0.2.tgz", + "integrity": "sha512-g1MWMLBiz8FKi1e4w0UyVL3w+iJceWAFBAaBnnGKOpNa5f8TLktkbre1+s6oICydWAm+HRUGTmI+//xv2hvXYA==", + "dev": true, + "license": "MIT", + "dependencies": { + "minimist": "^1.2.0" + }, + "bin": { + "json5": "lib/cli.js" + } + }, + "node_modules/jsx-ast-utils": { + "version": "3.3.5", + "resolved": "https://registry.npmjs.org/jsx-ast-utils/-/jsx-ast-utils-3.3.5.tgz", + "integrity": "sha512-ZZow9HBI5O6EPgSJLUb8n2NKgmVWTwCvHGwFuJlMjvLFqlGG6pjirPhtdsseaLZjSibD8eegzmYpUZwoIlj2cQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "array-includes": "^3.1.6", + "array.prototype.flat": "^1.3.1", + "object.assign": "^4.1.4", + "object.values": "^1.1.6" + }, + "engines": { + "node": ">=4.0" + } + }, + "node_modules/jwt-decode": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/jwt-decode/-/jwt-decode-4.0.0.tgz", + "integrity": "sha512-+KJGIyHgkGuIq3IEBNftfhW/LfWhXUIY6OmyVWjliu5KH1y0fw7VQ8YndE2O4qZdMSd9SqbnC8GOcZEy0Om7sA==", + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/keyv": { + "version": "4.5.4", + "resolved": "https://registry.npmjs.org/keyv/-/keyv-4.5.4.tgz", + "integrity": "sha512-oxVHkHR/EJf2CNXnWxRLW6mg7JyCCUcG0DtEGmL2ctUo1PNTin1PUil+r/+4r5MpVgC/fn1kjsx7mjSujKqIpw==", + "dev": true, + "license": "MIT", + "dependencies": { + "json-buffer": "3.0.1" + } + }, + "node_modules/language-subtag-registry": { + "version": "0.3.23", + "resolved": "https://registry.npmjs.org/language-subtag-registry/-/language-subtag-registry-0.3.23.tgz", + "integrity": "sha512-0K65Lea881pHotoGEa5gDlMxt3pctLi2RplBb7Ezh4rRdLEOtgi7n4EwK9lamnUCkKBqaeKRVebTq6BAxSkpXQ==", + "dev": true, + "license": "CC0-1.0" + }, + "node_modules/language-tags": { + "version": "1.0.9", + "resolved": "https://registry.npmjs.org/language-tags/-/language-tags-1.0.9.tgz", + "integrity": "sha512-MbjN408fEndfiQXbFQ1vnd+1NoLDsnQW41410oQBXiyXDMYH5z505juWa4KUE1LqxRC7DgOgZDbKLxHIwm27hA==", + "dev": true, + "license": "MIT", + "dependencies": { + "language-subtag-registry": "^0.3.20" + }, + "engines": { + "node": ">=0.10" + } + }, + "node_modules/levn": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/levn/-/levn-0.4.1.tgz", + "integrity": "sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "prelude-ls": "^1.2.1", + "type-check": "~0.4.0" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/lib0": { + "version": "0.2.98", + "resolved": "https://registry.npmjs.org/lib0/-/lib0-0.2.98.tgz", + "integrity": "sha512-XteTiNO0qEXqqweWx+b21p/fBnNHUA1NwAtJNJek1oPrewEZs2uiT4gWivHKr9GqCjDPAhchz0UQO8NwU3bBNA==", + "dependencies": { + "isomorphic.js": "^0.2.4" + }, + "bin": { + "0ecdsa-generate-keypair": "bin/0ecdsa-generate-keypair.js", + "0gentesthtml": "bin/gentesthtml.js", + "0serve": "bin/0serve.js" + }, + "engines": { + "node": ">=16" + }, + "funding": { + "type": "GitHub Sponsors ❤", + "url": "https://github.com/sponsors/dmonad" + } + }, + "node_modules/lilconfig": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/lilconfig/-/lilconfig-2.1.0.tgz", + "integrity": "sha512-utWOt/GHzuUxnLKxB6dk81RoOeoNeHgbrXiuGk4yyF5qlRz+iIVWu56E2fqGHFrXz0QNUhLB/8nKqvRH66JKGQ==", + "license": "MIT", + "engines": { + "node": ">=10" + } + }, + "node_modules/lines-and-columns": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/lines-and-columns/-/lines-and-columns-1.2.4.tgz", + "integrity": "sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==", + "license": "MIT" + }, + "node_modules/loaders.css": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/loaders.css/-/loaders.css-0.1.2.tgz", + "integrity": "sha512-Rhowlq24ey1VOeor+3wYOt9+MjaxBOJm1u4KlQgNC3+0xJ0LS4wq4iG57D/BPzvuD/7HHDGQOWJ+81oR2EI9bQ==", + "license": "MIT" + }, + "node_modules/locate-path": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-6.0.0.tgz", + "integrity": "sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==", + "dev": true, + "license": "MIT", + "dependencies": { + "p-locate": "^5.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/lodash.merge": { + "version": "4.6.2", + "resolved": "https://registry.npmjs.org/lodash.merge/-/lodash.merge-4.6.2.tgz", + "integrity": "sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ==", + "license": "MIT" + }, + "node_modules/loose-envify": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz", + "integrity": "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==", + "license": "MIT", + "dependencies": { + "js-tokens": "^3.0.0 || ^4.0.0" + }, + "bin": { + "loose-envify": "cli.js" + } + }, + "node_modules/lowlight": { + "version": "1.20.0", + "resolved": "https://registry.npmjs.org/lowlight/-/lowlight-1.20.0.tgz", + "integrity": "sha512-8Ktj+prEb1RoCPkEOrPMYUN/nCggB7qAWe3a7OpMjWQkh3l2RD5wKRQ+o8Q8YuI9RG/xs95waaI/E6ym/7NsTw==", + "license": "MIT", + "dependencies": { + "fault": "^1.0.0", + "highlight.js": "~10.7.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/lru-cache": { + "version": "10.4.3", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-10.4.3.tgz", + "integrity": "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==", + "license": "ISC" + }, + "node_modules/lucide-react": { + "version": "0.445.0", + "resolved": "https://registry.npmjs.org/lucide-react/-/lucide-react-0.445.0.tgz", + "integrity": "sha512-YrLf3aAHvmd4dZ8ot+mMdNFrFpJD7YRwQ2pUcBhgqbmxtrMP4xDzIorcj+8y+6kpuXBF4JB0NOCTUWIYetJjgA==", + "license": "ISC", + "peerDependencies": { + "react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0-rc" + } + }, + "node_modules/mdast-util-to-hast": { + "version": "13.2.0", + "resolved": "https://registry.npmjs.org/mdast-util-to-hast/-/mdast-util-to-hast-13.2.0.tgz", + "integrity": "sha512-QGYKEuUsYT9ykKBCMOEDLsU5JRObWQusAolFMeko/tYPufNkRffBAQjIE+99jbA87xv6FgmjLtwjh9wBWajwAA==", + "license": "MIT", + "dependencies": { + "@types/hast": "^3.0.0", + "@types/mdast": "^4.0.0", + "@ungap/structured-clone": "^1.0.0", + "devlop": "^1.0.0", + "micromark-util-sanitize-uri": "^2.0.0", + "trim-lines": "^3.0.0", + "unist-util-position": "^5.0.0", + "unist-util-visit": "^5.0.0", + "vfile": "^6.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/mdast-util-to-hast/node_modules/@types/hast": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/@types/hast/-/hast-3.0.4.tgz", + "integrity": "sha512-WPs+bbQw5aCj+x6laNGWLH3wviHtoCv/P3+otBhbOhJgG8qtpdAMlTCxLtsTWA7LH1Oh/bFCHsBn0TPS5m30EQ==", + "license": "MIT", + "dependencies": { + "@types/unist": "*" + } + }, + "node_modules/memoize-one": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/memoize-one/-/memoize-one-6.0.0.tgz", + "integrity": "sha512-rkpe71W0N0c0Xz6QD0eJETuWAJGnJ9afsl1srmwPrI+yBCkge5EycXXbYRyvL29zZVUWQCY7InPRCv3GDXuZNw==", + "license": "MIT" + }, + "node_modules/merge2": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/merge2/-/merge2-1.4.1.tgz", + "integrity": "sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==", + "license": "MIT", + "engines": { + "node": ">= 8" + } + }, + "node_modules/micromark-util-character": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/micromark-util-character/-/micromark-util-character-2.1.0.tgz", + "integrity": "sha512-KvOVV+X1yLBfs9dCBSopq/+G1PcgT3lAK07mC4BzXi5E7ahzMAF8oIupDDJ6mievI6F+lAATkbQQlQixJfT3aQ==", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" + } + }, + "node_modules/micromark-util-encode": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/micromark-util-encode/-/micromark-util-encode-2.0.0.tgz", + "integrity": "sha512-pS+ROfCXAGLWCOc8egcBvT0kf27GoWMqtdarNfDcjb6YLuV5cM3ioG45Ys2qOVqeqSbjaKg72vU+Wby3eddPsA==", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT" + }, + "node_modules/micromark-util-sanitize-uri": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/micromark-util-sanitize-uri/-/micromark-util-sanitize-uri-2.0.0.tgz", + "integrity": "sha512-WhYv5UEcZrbAtlsnPuChHUAsu/iBPOVaEVsntLBIdpibO0ddy8OzavZz3iL2xVvBZOpolujSliP65Kq0/7KIYw==", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-util-character": "^2.0.0", + "micromark-util-encode": "^2.0.0", + "micromark-util-symbol": "^2.0.0" + } + }, + "node_modules/micromark-util-symbol": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/micromark-util-symbol/-/micromark-util-symbol-2.0.0.tgz", + "integrity": "sha512-8JZt9ElZ5kyTnO94muPxIGS8oyElRJaiJO8EzV6ZSyGQ1Is8xwl4Q45qU5UOg+bGH4AikWziz0iN4sFLWs8PGw==", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT" + }, + "node_modules/micromark-util-types": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/micromark-util-types/-/micromark-util-types-2.0.0.tgz", + "integrity": "sha512-oNh6S2WMHWRZrmutsRmDDfkzKtxF+bc2VxLC9dvtrDIRFln627VsFP6fLMgTryGDljgLPjkrzQSDcPrjPyDJ5w==", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT" + }, + "node_modules/micromatch": { + "version": "4.0.8", + "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.8.tgz", + "integrity": "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==", + "license": "MIT", + "dependencies": { + "braces": "^3.0.3", + "picomatch": "^2.3.1" + }, + "engines": { + "node": ">=8.6" + } + }, + "node_modules/minimatch": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", + "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", + "dev": true, + "license": "ISC", + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, + "node_modules/minimist": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz", + "integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/minipass": { + "version": "7.1.2", + "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.2.tgz", + "integrity": "sha512-qOOzS1cBTWYF4BH8fVePDBOO9iptMnGUEZwNc/cMWnTV2nVLZ7VoNWEPHkYczZA0pdoA7dl6e7FL659nX9S2aw==", + "license": "ISC", + "engines": { + "node": ">=16 || 14 >=14.17" + } + }, + "node_modules/monaco-editor": { + "version": "0.52.0", + "resolved": "https://registry.npmjs.org/monaco-editor/-/monaco-editor-0.52.0.tgz", + "integrity": "sha512-OeWhNpABLCeTqubfqLMXGsqf6OmPU6pHM85kF3dhy6kq5hnhuVS1p3VrEW/XhWHc71P2tHyS5JFySD8mgs1crw==", + "peer": true + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "license": "MIT" + }, + "node_modules/mz": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/mz/-/mz-2.7.0.tgz", + "integrity": "sha512-z81GNO7nnYMEhrGh9LeymoE4+Yr0Wn5McHIZMK5cfQCl+NDX08sCZgUc9/6MHni9IWuFLm1Z3HTCXu2z9fN62Q==", + "license": "MIT", + "dependencies": { + "any-promise": "^1.0.0", + "object-assign": "^4.0.1", + "thenify-all": "^1.0.0" + } + }, + "node_modules/nanoid": { + "version": "3.3.7", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.7.tgz", + "integrity": "sha512-eSRppjcPIatRIMC1U6UngP8XFcz8MQWGQdt1MTBQ7NaAmvXDfvNxbvWV3x2y6CdEUciCSsDHDQZbhYaB8QEo2g==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/natural-compare": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz", + "integrity": "sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==", + "dev": true, + "license": "MIT" + }, + "node_modules/next": { + "version": "14.2.11", + "resolved": "https://registry.npmjs.org/next/-/next-14.2.11.tgz", + "integrity": "sha512-8MDFqHBhdmR2wdfaWc8+lW3A/hppFe1ggQ9vgIu/g2/2QEMYJrPoQP6b+VNk56gIug/bStysAmrpUKtj3XN8Bw==", + "license": "MIT", + "dependencies": { + "@next/env": "14.2.11", + "@swc/helpers": "0.5.5", + "busboy": "1.6.0", + "caniuse-lite": "^1.0.30001579", + "graceful-fs": "^4.2.11", + "postcss": "8.4.31", + "styled-jsx": "5.1.1" + }, + "bin": { + "next": "dist/bin/next" + }, + "engines": { + "node": ">=18.17.0" + }, + "optionalDependencies": { + "@next/swc-darwin-arm64": "14.2.11", + "@next/swc-darwin-x64": "14.2.11", + "@next/swc-linux-arm64-gnu": "14.2.11", + "@next/swc-linux-arm64-musl": "14.2.11", + "@next/swc-linux-x64-gnu": "14.2.11", + "@next/swc-linux-x64-musl": "14.2.11", + "@next/swc-win32-arm64-msvc": "14.2.11", + "@next/swc-win32-ia32-msvc": "14.2.11", + "@next/swc-win32-x64-msvc": "14.2.11" + }, + "peerDependencies": { + "@opentelemetry/api": "^1.1.0", + "@playwright/test": "^1.41.2", + "react": "^18.2.0", + "react-dom": "^18.2.0", + "sass": "^1.3.0" + }, + "peerDependenciesMeta": { + "@opentelemetry/api": { + "optional": true + }, + "@playwright/test": { + "optional": true + }, + "sass": { + "optional": true + } + } + }, + "node_modules/next/node_modules/postcss": { + "version": "8.4.31", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.4.31.tgz", + "integrity": "sha512-PS08Iboia9mts/2ygV3eLpY5ghnUcfLV/EXTOW1E2qYxJKGGBUtNjN76FYHnMs36RmARn41bC0AZmn+rR0OVpQ==", + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "nanoid": "^3.3.6", + "picocolors": "^1.0.0", + "source-map-js": "^1.0.2" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/normalize-path": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz", + "integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/object-assign": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", + "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/object-hash": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/object-hash/-/object-hash-3.0.0.tgz", + "integrity": "sha512-RSn9F68PjH9HqtltsSnqYC1XXoWe9Bju5+213R98cNGttag9q9yAOTzdbsqvIa7aNm5WffBZFpWYr2aWrklWAw==", + "license": "MIT", + "engines": { + "node": ">= 6" + } + }, + "node_modules/object-inspect": { + "version": "1.13.2", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.2.tgz", + "integrity": "sha512-IRZSRuzJiynemAXPYtPe5BoI/RESNYR7TYm50MC5Mqbd3Jmw5y790sErYw3V6SryFJD64b74qQQs9wn5Bg/k3g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/object-is": { + "version": "1.1.6", + "resolved": "https://registry.npmjs.org/object-is/-/object-is-1.1.6.tgz", + "integrity": "sha512-F8cZ+KfGlSGi09lJT7/Nd6KJZ9ygtvYC0/UYYLI9nmQKLMnydpB9yvbv9K1uSkEu7FU9vYPmVwLg328tX+ot3Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.7", + "define-properties": "^1.2.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/object-keys": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/object-keys/-/object-keys-1.1.1.tgz", + "integrity": "sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/object.assign": { + "version": "4.1.5", + "resolved": "https://registry.npmjs.org/object.assign/-/object.assign-4.1.5.tgz", + "integrity": "sha512-byy+U7gp+FVwmyzKPYhW2h5l3crpmGsxl7X2s8y43IgxvG4g3QZ6CffDtsNQy1WsmZpQbO+ybo0AlW7TY6DcBQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.5", + "define-properties": "^1.2.1", + "has-symbols": "^1.0.3", + "object-keys": "^1.1.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/object.entries": { + "version": "1.1.8", + "resolved": "https://registry.npmjs.org/object.entries/-/object.entries-1.1.8.tgz", + "integrity": "sha512-cmopxi8VwRIAw/fkijJohSfpef5PdN0pMQJN6VC/ZKvn0LIknWD8KtgY6KlQdEc4tIjcQ3HxSMmnvtzIscdaYQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.7", + "define-properties": "^1.2.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/object.fromentries": { + "version": "2.0.8", + "resolved": "https://registry.npmjs.org/object.fromentries/-/object.fromentries-2.0.8.tgz", + "integrity": "sha512-k6E21FzySsSK5a21KRADBd/NGneRegFO5pLHfdQLpRDETUNJueLXs3WCzyQ3tFRDYgbq3KHGXfTbi2bs8WQ6rQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.7", + "define-properties": "^1.2.1", + "es-abstract": "^1.23.2", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/object.groupby": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/object.groupby/-/object.groupby-1.0.3.tgz", + "integrity": "sha512-+Lhy3TQTuzXI5hevh8sBGqbmurHbbIjAi0Z4S63nthVLmLxfbj4T54a4CfZrXIrt9iP4mVAPYMo/v99taj3wjQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.7", + "define-properties": "^1.2.1", + "es-abstract": "^1.23.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/object.values": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/object.values/-/object.values-1.2.0.tgz", + "integrity": "sha512-yBYjY9QX2hnRmZHAjG/f13MzmBzxzYgQhFrke06TTyKY5zSTEqkOeukBzIdVA3j3ulu8Qa3MbVFShV7T2RmGtQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.7", + "define-properties": "^1.2.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/oidc-client-ts": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/oidc-client-ts/-/oidc-client-ts-3.1.0.tgz", + "integrity": "sha512-IDopEXjiwjkmJLYZo6BTlvwOtnlSniWZkKZoXforC/oLZHC9wkIxd25Kwtmo5yKFMMVcsp3JY6bhcNJqdYk8+g==", + "license": "Apache-2.0", + "dependencies": { + "jwt-decode": "^4.0.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", + "dev": true, + "license": "ISC", + "dependencies": { + "wrappy": "1" + } + }, + "node_modules/oniguruma-to-js": { + "version": "0.4.3", + "resolved": "https://registry.npmjs.org/oniguruma-to-js/-/oniguruma-to-js-0.4.3.tgz", + "integrity": "sha512-X0jWUcAlxORhOqqBREgPMgnshB7ZGYszBNspP+tS9hPD3l13CdaXcHbgImoHUHlrvGx/7AvFEkTRhAGYh+jzjQ==", + "license": "MIT", + "dependencies": { + "regex": "^4.3.2" + }, + "funding": { + "url": "https://github.com/sponsors/antfu" + } + }, + "node_modules/optionator": { + "version": "0.9.4", + "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.4.tgz", + "integrity": "sha512-6IpQ7mKUxRcZNLIObR0hz7lxsapSSIYNZJwXPGeF0mTVqGKFIXj1DQcMoT22S3ROcLyY/rz0PWaWZ9ayWmad9g==", + "dev": true, + "license": "MIT", + "dependencies": { + "deep-is": "^0.1.3", + "fast-levenshtein": "^2.0.6", + "levn": "^0.4.1", + "prelude-ls": "^1.2.1", + "type-check": "^0.4.0", + "word-wrap": "^1.2.5" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/p-limit": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz", + "integrity": "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "yocto-queue": "^0.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/p-locate": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-5.0.0.tgz", + "integrity": "sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw==", + "dev": true, + "license": "MIT", + "dependencies": { + "p-limit": "^3.0.2" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/parent-module": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/parent-module/-/parent-module-1.0.1.tgz", + "integrity": "sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g==", + "license": "MIT", + "dependencies": { + "callsites": "^3.0.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/parse-entities": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/parse-entities/-/parse-entities-2.0.0.tgz", + "integrity": "sha512-kkywGpCcRYhqQIchaWqZ875wzpS/bMKhz5HnN3p7wveJTkTtyAB/AlnS0f8DFSqYW1T82t6yEAkEcB+A1I3MbQ==", + "license": "MIT", + "dependencies": { + "character-entities": "^1.0.0", + "character-entities-legacy": "^1.0.0", + "character-reference-invalid": "^1.0.0", + "is-alphanumerical": "^1.0.0", + "is-decimal": "^1.0.0", + "is-hexadecimal": "^1.0.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/parse-json": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-5.2.0.tgz", + "integrity": "sha512-ayCKvm/phCGxOkYRSCM82iDwct8/EonSEgCSxWxD7ve6jHggsFl4fZVQBPRNgQoKiuV/odhFrGzQXZwbifC8Rg==", + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.0.0", + "error-ex": "^1.3.1", + "json-parse-even-better-errors": "^2.3.0", + "lines-and-columns": "^1.1.6" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/path-exists": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", + "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/path-is-absolute": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", + "integrity": "sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/path-key": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", + "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/path-parse": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz", + "integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==", + "license": "MIT" + }, + "node_modules/path-scurry": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-1.11.1.tgz", + "integrity": "sha512-Xa4Nw17FS9ApQFJ9umLiJS4orGjm7ZzwUrwamcGQuHSzDyth9boKDaycYdDcZDuqYATXw4HFXgaqWTctW/v1HA==", + "license": "BlueOak-1.0.0", + "dependencies": { + "lru-cache": "^10.2.0", + "minipass": "^5.0.0 || ^6.0.2 || ^7.0.0" + }, + "engines": { + "node": ">=16 || 14 >=14.18" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/path-type": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/path-type/-/path-type-4.0.0.tgz", + "integrity": "sha512-gDKb8aZMDeD/tZWs9P6+q0J9Mwkdl6xMV8TjnGP3qJVJ06bdMgkbBlLU8IdfOsIsFz2BW1rNVT3XuNEl8zPAvw==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/picocolors": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.0.tgz", + "integrity": "sha512-TQ92mBOW0l3LeMeyLV6mzy/kWr8lkd/hp3mTg7wYK7zJhuBStmGMBG0BdeDZS/dZx1IukaX6Bk11zcln25o1Aw==", + "license": "ISC" + }, + "node_modules/picomatch": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz", + "integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==", + "license": "MIT", + "engines": { + "node": ">=8.6" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/pify": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/pify/-/pify-2.3.0.tgz", + "integrity": "sha512-udgsAY+fTnvv7kI7aaxbqwWNb0AHiB0qBO89PZKPkoTmGOgdbrHDKD+0B2X4uTfJ/FT1R09r9gTsjUjNJotuog==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/pirates": { + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/pirates/-/pirates-4.0.6.tgz", + "integrity": "sha512-saLsH7WeYYPiD25LDuLRRY/i+6HaPYr6G1OUlN39otzkSTxKnubR9RTxS3/Kk50s1g2JTgFwWQDQyplC5/SHZg==", + "license": "MIT", + "engines": { + "node": ">= 6" + } + }, + "node_modules/possible-typed-array-names": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/possible-typed-array-names/-/possible-typed-array-names-1.0.0.tgz", + "integrity": "sha512-d7Uw+eZoloe0EHDIYoe+bQ5WXnGMOpmiZFTuMWCwpjzzkL2nTjcKiAk4hh8TjnGye2TwWOk3UXucZ+3rbmBa8Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/postcss": { + "version": "8.4.47", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.4.47.tgz", + "integrity": "sha512-56rxCq7G/XfB4EkXq9Egn5GCqugWvDFjafDOThIdMBsI15iqPqR5r15TfSr1YPYeEI19YeaXMCbY6u88Y76GLQ==", + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "nanoid": "^3.3.7", + "picocolors": "^1.1.0", + "source-map-js": "^1.2.1" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/postcss-import": { + "version": "15.1.0", + "resolved": "https://registry.npmjs.org/postcss-import/-/postcss-import-15.1.0.tgz", + "integrity": "sha512-hpr+J05B2FVYUAXHeK1YyI267J/dDDhMU6B6civm8hSY1jYJnBXxzKDKDswzJmtLHryrjhnDjqqp/49t8FALew==", + "license": "MIT", + "dependencies": { + "postcss-value-parser": "^4.0.0", + "read-cache": "^1.0.0", + "resolve": "^1.1.7" + }, + "engines": { + "node": ">=14.0.0" + }, + "peerDependencies": { + "postcss": "^8.0.0" + } + }, + "node_modules/postcss-js": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/postcss-js/-/postcss-js-4.0.1.tgz", + "integrity": "sha512-dDLF8pEO191hJMtlHFPRa8xsizHaM82MLfNkUHdUtVEV3tgTp5oj+8qbEqYM57SLfc74KSbw//4SeJma2LRVIw==", + "license": "MIT", + "dependencies": { + "camelcase-css": "^2.0.1" + }, + "engines": { + "node": "^12 || ^14 || >= 16" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + "peerDependencies": { + "postcss": "^8.4.21" + } + }, + "node_modules/postcss-load-config": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/postcss-load-config/-/postcss-load-config-4.0.2.tgz", + "integrity": "sha512-bSVhyJGL00wMVoPUzAVAnbEoWyqRxkjv64tUl427SKnPrENtq6hJwUojroMz2VB+Q1edmi4IfrAPpami5VVgMQ==", + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "lilconfig": "^3.0.0", + "yaml": "^2.3.4" + }, + "engines": { + "node": ">= 14" + }, + "peerDependencies": { + "postcss": ">=8.0.9", + "ts-node": ">=9.0.0" + }, + "peerDependenciesMeta": { + "postcss": { + "optional": true + }, + "ts-node": { + "optional": true + } + } + }, + "node_modules/postcss-load-config/node_modules/lilconfig": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/lilconfig/-/lilconfig-3.1.2.tgz", + "integrity": "sha512-eop+wDAvpItUys0FWkHIKeC9ybYrTGbU41U5K7+bttZZeohvnY7M9dZ5kB21GNWiFT2q1OoPTvncPCgSOVO5ow==", + "license": "MIT", + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/antonk52" + } + }, + "node_modules/postcss-nested": { + "version": "6.2.0", + "resolved": "https://registry.npmjs.org/postcss-nested/-/postcss-nested-6.2.0.tgz", + "integrity": "sha512-HQbt28KulC5AJzG+cZtj9kvKB93CFCdLvog1WFLf1D+xmMvPGlBstkpTEZfK5+AN9hfJocyBFCNiqyS48bpgzQ==", + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "postcss-selector-parser": "^6.1.1" + }, + "engines": { + "node": ">=12.0" + }, + "peerDependencies": { + "postcss": "^8.2.14" + } + }, + "node_modules/postcss-selector-parser": { + "version": "6.1.2", + "resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-6.1.2.tgz", + "integrity": "sha512-Q8qQfPiZ+THO/3ZrOrO0cJJKfpYCagtMUkXbnEfmgUjwXg6z/WBeOyS9APBBPCTSiDV+s4SwQGu8yFsiMRIudg==", + "license": "MIT", + "dependencies": { + "cssesc": "^3.0.0", + "util-deprecate": "^1.0.2" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/postcss-value-parser": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/postcss-value-parser/-/postcss-value-parser-4.2.0.tgz", + "integrity": "sha512-1NNCs6uurfkVbeXG4S8JFT9t19m45ICnif8zWLd5oPSZ50QnwMfK+H3jv408d4jw/7Bttv5axS5IiHoLaVNHeQ==", + "license": "MIT" + }, + "node_modules/prelude-ls": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz", + "integrity": "sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/prismjs": { + "version": "1.29.0", + "resolved": "https://registry.npmjs.org/prismjs/-/prismjs-1.29.0.tgz", + "integrity": "sha512-Kx/1w86q/epKcmte75LNrEoT+lX8pBpavuAbvJWRXar7Hz8jrtF+e3vY751p0R8H9HdArwaCTNDDzHg/ScJK1Q==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/progressbar.js": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/progressbar.js/-/progressbar.js-1.1.1.tgz", + "integrity": "sha512-FBsw3BKsUbb+hNeYfiP3xzvAAQrPi4DnGDw66bCmfuRCDLcslxyxv2GyYUdBSKFGSIBa73CUP5WMcl6F8AAXlw==", + "license": "MIT", + "dependencies": { + "lodash.merge": "^4.6.2", + "shifty": "^2.8.3" + } + }, + "node_modules/prop-types": { + "version": "15.8.1", + "resolved": "https://registry.npmjs.org/prop-types/-/prop-types-15.8.1.tgz", + "integrity": "sha512-oj87CgZICdulUohogVAR7AjlC0327U4el4L6eAvOqCeudMDVU0NThNaV+b9Df4dXgSP1gXMTnPdhfe/2qDH5cg==", + "license": "MIT", + "dependencies": { + "loose-envify": "^1.4.0", + "object-assign": "^4.1.1", + "react-is": "^16.13.1" + } + }, + "node_modules/property-information": { + "version": "5.6.0", + "resolved": "https://registry.npmjs.org/property-information/-/property-information-5.6.0.tgz", + "integrity": "sha512-YUHSPk+A30YPv+0Qf8i9Mbfe/C0hdPXk1s1jPVToV8pk8BQtpw10ct89Eo7OWkutrwqvT0eicAxlOg3dOAu8JA==", + "license": "MIT", + "dependencies": { + "xtend": "^4.0.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/punycode": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", + "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/querystringify": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/querystringify/-/querystringify-2.2.0.tgz", + "integrity": "sha512-FIqgj2EUvTa7R50u0rGsyTftzjYmv/a3hO345bZNrqabNqjtgiDMgmo4mkUjd+nzU5oF3dClKqFIPUKybUyqoQ==", + "license": "MIT" + }, + "node_modules/queue-microtask": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/queue-microtask/-/queue-microtask-1.2.3.tgz", + "integrity": "sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/randombytes": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/randombytes/-/randombytes-2.1.0.tgz", + "integrity": "sha512-vYl3iOX+4CKUWuxGi9Ukhie6fsqXqS9FE2Zaic4tNFD2N2QQaXOMFbuKK4QmDHC0JO6B1Zp41J0LpT0oR68amQ==", + "dependencies": { + "safe-buffer": "^5.1.0" + } + }, + "node_modules/react": { + "version": "18.3.1", + "resolved": "https://registry.npmjs.org/react/-/react-18.3.1.tgz", + "integrity": "sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==", + "license": "MIT", + "dependencies": { + "loose-envify": "^1.1.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/react-chat-elements": { + "version": "12.0.16", + "resolved": "https://registry.npmjs.org/react-chat-elements/-/react-chat-elements-12.0.16.tgz", + "integrity": "sha512-71+AfjiSvMuG7gcU4rZQCbh3ARjuOGNPasgtzunpBHzbV9kaAyQ6cWudr7Z/3A0SW8QzytFRzOX9ZmpfK/owOw==", + "license": "MIT", + "dependencies": { + "classnames": "^2.2.5", + "progressbar.js": "^1.1.0", + "react-icons": "^4.3.1", + "react-spinkit": "^3.0.0", + "timeago.js": "^4.0.2" + }, + "peerDependencies": { + "react": "^18.2.0", + "react-dom": "18.2.0" + } + }, + "node_modules/react-chat-elements/node_modules/react-icons": { + "version": "4.12.0", + "resolved": "https://registry.npmjs.org/react-icons/-/react-icons-4.12.0.tgz", + "integrity": "sha512-IBaDuHiShdZqmfc/TwHu6+d6k2ltNCf3AszxNmjJc1KUfXdEeRJOKyNvLmAHaarhzGmTSVygNdyu8/opXv2gaw==", + "license": "MIT", + "peerDependencies": { + "react": "*" + } + }, + "node_modules/react-dom": { + "version": "18.2.0", + "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-18.2.0.tgz", + "integrity": "sha512-6IMTriUmvsjHUjNtEDudZfuDQUoWXVxKHhlEGSk81n4YFS+r/Kl99wXiwlVXtPBtJenozv2P+hxDsw9eA7Xo6g==", + "license": "MIT", + "dependencies": { + "loose-envify": "^1.1.0", + "scheduler": "^0.23.0" + }, + "peerDependencies": { + "react": "^18.2.0" + } + }, + "node_modules/react-hook-form": { + "version": "7.53.0", + "resolved": "https://registry.npmjs.org/react-hook-form/-/react-hook-form-7.53.0.tgz", + "integrity": "sha512-M1n3HhqCww6S2hxLxciEXy2oISPnAzxY7gvwVPrtlczTM/1dDadXgUxDpHMrMTblDOcm/AXtXxHwZ3jpg1mqKQ==", + "license": "MIT", + "engines": { + "node": ">=18.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/react-hook-form" + }, + "peerDependencies": { + "react": "^16.8.0 || ^17 || ^18 || ^19" + } + }, + "node_modules/react-icons": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/react-icons/-/react-icons-5.3.0.tgz", + "integrity": "sha512-DnUk8aFbTyQPSkCfF8dbX6kQjXA9DktMeJqfjrg6cK9vwQVMxmcA3BfP4QoiztVmEHtwlTgLFsPuH2NskKT6eg==", + "license": "MIT", + "peerDependencies": { + "react": "*" + } + }, + "node_modules/react-is": { + "version": "16.13.1", + "resolved": "https://registry.npmjs.org/react-is/-/react-is-16.13.1.tgz", + "integrity": "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==", + "license": "MIT" + }, + "node_modules/react-lifecycles-compat": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/react-lifecycles-compat/-/react-lifecycles-compat-3.0.4.tgz", + "integrity": "sha512-fBASbA6LnOU9dOU2eW7aQ8xmYBSXUIWr+UmF9b1efZBazGNO+rcXT/icdKnYm2pTwcRylVUYwW7H1PHfLekVzA==", + "license": "MIT" + }, + "node_modules/react-modal": { + "version": "3.16.1", + "resolved": "https://registry.npmjs.org/react-modal/-/react-modal-3.16.1.tgz", + "integrity": "sha512-VStHgI3BVcGo7OXczvnJN7yT2TWHJPDXZWyI/a0ssFNhGZWsPmB8cF0z33ewDXq4VfYMO1vXgiv/g8Nj9NDyWg==", + "license": "MIT", + "dependencies": { + "exenv": "^1.2.0", + "prop-types": "^15.7.2", + "react-lifecycles-compat": "^3.0.0", + "warning": "^4.0.3" + }, + "engines": { + "node": ">=8" + }, + "peerDependencies": { + "react": "^0.14.0 || ^15.0.0 || ^16 || ^17 || ^18", + "react-dom": "^0.14.0 || ^15.0.0 || ^16 || ^17 || ^18" + } + }, + "node_modules/react-pro-sidebar": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/react-pro-sidebar/-/react-pro-sidebar-1.1.0.tgz", + "integrity": "sha512-rdRJ4PeMsqWq9n69AmF6et6qCbhCF1KEBgjAH8vIiLxE1k5fMxtRYo0k4asxW8qpIH6sqahiMxrxVVoObv8orQ==", + "license": "MIT", + "dependencies": { + "@emotion/react": "^11.10.5", + "@emotion/styled": "^11.10.5", + "@popperjs/core": "^2.11.6", + "classnames": "^2.3.2" + }, + "peerDependencies": { + "react": ">=16.8.0", + "react-dom": ">=16.8.0" + } + }, + "node_modules/react-remove-scroll": { + "version": "2.5.7", + "resolved": "https://registry.npmjs.org/react-remove-scroll/-/react-remove-scroll-2.5.7.tgz", + "integrity": "sha512-FnrTWO4L7/Bhhf3CYBNArEG/yROV0tKmTv7/3h9QCFvH6sndeFf1wPqOcbFVu5VAulS5dV1wGT3GZZ/1GawqiA==", + "license": "MIT", + "dependencies": { + "react-remove-scroll-bar": "^2.3.4", + "react-style-singleton": "^2.2.1", + "tslib": "^2.1.0", + "use-callback-ref": "^1.3.0", + "use-sidecar": "^1.1.2" + }, + "engines": { + "node": ">=10" + }, + "peerDependencies": { + "@types/react": "^16.8.0 || ^17.0.0 || ^18.0.0", + "react": "^16.8.0 || ^17.0.0 || ^18.0.0" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/react-remove-scroll-bar": { + "version": "2.3.6", + "resolved": "https://registry.npmjs.org/react-remove-scroll-bar/-/react-remove-scroll-bar-2.3.6.tgz", + "integrity": "sha512-DtSYaao4mBmX+HDo5YWYdBWQwYIQQshUV/dVxFxK+KM26Wjwp1gZ6rv6OC3oujI6Bfu6Xyg3TwK533AQutsn/g==", + "license": "MIT", + "dependencies": { + "react-style-singleton": "^2.2.1", + "tslib": "^2.0.0" + }, + "engines": { + "node": ">=10" + }, + "peerDependencies": { + "@types/react": "^16.8.0 || ^17.0.0 || ^18.0.0", + "react": "^16.8.0 || ^17.0.0 || ^18.0.0" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/react-resizable-panels": { + "version": "2.1.6", + "resolved": "https://registry.npmjs.org/react-resizable-panels/-/react-resizable-panels-2.1.6.tgz", + "integrity": "sha512-oIqo/7pp2TsR+Dp1qZMr1l4RBDV4Zz/0HEG5zxliBJoHqqFnG0MbmFbk+5Q1VMGfPQ4uhXxefunLC1o7v38PDQ==", + "peerDependencies": { + "react": "^16.14.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc", + "react-dom": "^16.14.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc" + } + }, + "node_modules/react-select": { + "version": "5.8.2", + "resolved": "https://registry.npmjs.org/react-select/-/react-select-5.8.2.tgz", + "integrity": "sha512-a/LkOckoI62710gGPQSQqUp7A10fGbH/ya3/IR49qaq3XoBvwymgD5mJgtiHxBDsutyEQfdKNycWVh8Cg8UCjw==", + "license": "MIT", + "dependencies": { + "@babel/runtime": "^7.12.0", + "@emotion/cache": "^11.4.0", + "@emotion/react": "^11.8.1", + "@floating-ui/dom": "^1.0.1", + "@types/react-transition-group": "^4.4.0", + "memoize-one": "^6.0.0", + "prop-types": "^15.6.0", + "react-transition-group": "^4.3.0", + "use-isomorphic-layout-effect": "^1.1.2" + }, + "peerDependencies": { + "react": "^16.8.0 || ^17.0.0 || ^18.0.0", + "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0" + } + }, + "node_modules/react-spinkit": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/react-spinkit/-/react-spinkit-3.0.0.tgz", + "integrity": "sha512-RrfGRPjqxHQiy7quPqhjPynTu0zobgQaZu1QYBMpJJ6pCSRRRK16EZMaxdE6fLVYFRJWpX/eGATWLMoVFFT5uQ==", + "license": "MIT", + "dependencies": { + "classnames": "^2.2.3", + "loaders.css": "^0.1.2", + "object-assign": "^4.1.0", + "prop-types": "^15.5.8" + } + }, + "node_modules/react-spinners": { + "version": "0.14.1", + "resolved": "https://registry.npmjs.org/react-spinners/-/react-spinners-0.14.1.tgz", + "integrity": "sha512-2Izq+qgQ08HTofCVEdcAQCXFEYfqTDdfeDQJeo/HHQiQJD4imOicNLhkfN2eh1NYEWVOX4D9ok2lhuDB0z3Aag==", + "license": "MIT", + "peerDependencies": { + "react": "^16.0.0 || ^17.0.0 || ^18.0.0", + "react-dom": "^16.0.0 || ^17.0.0 || ^18.0.0" + } + }, + "node_modules/react-style-singleton": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/react-style-singleton/-/react-style-singleton-2.2.1.tgz", + "integrity": "sha512-ZWj0fHEMyWkHzKYUr2Bs/4zU6XLmq9HsgBURm7g5pAVfyn49DgUiNgY2d4lXRlYSiCif9YBGpQleewkcqddc7g==", + "license": "MIT", + "dependencies": { + "get-nonce": "^1.0.0", + "invariant": "^2.2.4", + "tslib": "^2.0.0" + }, + "engines": { + "node": ">=10" + }, + "peerDependencies": { + "@types/react": "^16.8.0 || ^17.0.0 || ^18.0.0", + "react": "^16.8.0 || ^17.0.0 || ^18.0.0" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/react-syntax-highlighter": { + "version": "15.6.1", + "resolved": "https://registry.npmjs.org/react-syntax-highlighter/-/react-syntax-highlighter-15.6.1.tgz", + "integrity": "sha512-OqJ2/vL7lEeV5zTJyG7kmARppUjiB9h9udl4qHQjjgEos66z00Ia0OckwYfRxCSFrW8RJIBnsBwQsHZbVPspqg==", + "license": "MIT", + "dependencies": { + "@babel/runtime": "^7.3.1", + "highlight.js": "^10.4.1", + "highlightjs-vue": "^1.0.0", + "lowlight": "^1.17.0", + "prismjs": "^1.27.0", + "refractor": "^3.6.0" + }, + "peerDependencies": { + "react": ">= 0.14.0" + } + }, + "node_modules/react-transition-group": { + "version": "4.4.5", + "resolved": "https://registry.npmjs.org/react-transition-group/-/react-transition-group-4.4.5.tgz", + "integrity": "sha512-pZcd1MCJoiKiBR2NRxeCRg13uCXbydPnmB4EOeRrY7480qNWO8IIgQG6zlDkm6uRMsURXPuKq0GWtiM59a5Q6g==", + "license": "BSD-3-Clause", + "dependencies": { + "@babel/runtime": "^7.5.5", + "dom-helpers": "^5.0.1", + "loose-envify": "^1.4.0", + "prop-types": "^15.6.2" + }, + "peerDependencies": { + "react": ">=16.6.0", + "react-dom": ">=16.6.0" + } + }, + "node_modules/read-cache": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/read-cache/-/read-cache-1.0.0.tgz", + "integrity": "sha512-Owdv/Ft7IjOgm/i0xvNDZ1LrRANRfew4b2prF3OWMQLxLfu3bS8FVhCsrSCMK4lR56Y9ya+AThoTpDCTxCmpRA==", + "license": "MIT", + "dependencies": { + "pify": "^2.3.0" + } + }, + "node_modules/readable-stream": { + "version": "3.6.2", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", + "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", + "dependencies": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/readdirp": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.6.0.tgz", + "integrity": "sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==", + "license": "MIT", + "dependencies": { + "picomatch": "^2.2.1" + }, + "engines": { + "node": ">=8.10.0" + } + }, + "node_modules/reflect.getprototypeof": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/reflect.getprototypeof/-/reflect.getprototypeof-1.0.6.tgz", + "integrity": "sha512-fmfw4XgoDke3kdI6h4xcUz1dG8uaiv5q9gcEwLS4Pnth2kxT+GZ7YehS1JTMGBQmtV7Y4GFGbs2re2NqhdozUg==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.7", + "define-properties": "^1.2.1", + "es-abstract": "^1.23.1", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.4", + "globalthis": "^1.0.3", + "which-builtin-type": "^1.1.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/refractor": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/refractor/-/refractor-3.6.0.tgz", + "integrity": "sha512-MY9W41IOWxxk31o+YvFCNyNzdkc9M20NoZK5vq6jkv4I/uh2zkWcfudj0Q1fovjUQJrNewS9NMzeTtqPf+n5EA==", + "license": "MIT", + "dependencies": { + "hastscript": "^6.0.0", + "parse-entities": "^2.0.0", + "prismjs": "~1.27.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/refractor/node_modules/prismjs": { + "version": "1.27.0", + "resolved": "https://registry.npmjs.org/prismjs/-/prismjs-1.27.0.tgz", + "integrity": "sha512-t13BGPUlFDR7wRB5kQDG4jjl7XeuH6jbJGt11JHPL96qwsEHNX2+68tFXqc1/k+/jALsbSWJKUOT/hcYAZ5LkA==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/regenerator-runtime": { + "version": "0.14.1", + "resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.14.1.tgz", + "integrity": "sha512-dYnhHh0nJoMfnkZs6GmmhFknAGRrLznOu5nc9ML+EJxGvrx6H7teuevqVqCuPcPK//3eDrrjQhehXVx9cnkGdw==", + "license": "MIT" + }, + "node_modules/regex": { + "version": "4.4.0", + "resolved": "https://registry.npmjs.org/regex/-/regex-4.4.0.tgz", + "integrity": "sha512-uCUSuobNVeqUupowbdZub6ggI5/JZkYyJdDogddJr60L764oxC2pMZov1fQ3wM9bdyzUILDG+Sqx6NAKAz9rKQ==", + "license": "MIT" + }, + "node_modules/regexp.prototype.flags": { + "version": "1.5.2", + "resolved": "https://registry.npmjs.org/regexp.prototype.flags/-/regexp.prototype.flags-1.5.2.tgz", + "integrity": "sha512-NcDiDkTLuPR+++OCKB0nWafEmhg/Da8aUPLPMQbK+bxKKCm1/S5he+AqYa4PlMCVBalb4/yxIRub6qkEx5yJbw==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.6", + "define-properties": "^1.2.1", + "es-errors": "^1.3.0", + "set-function-name": "^2.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/requires-port": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/requires-port/-/requires-port-1.0.0.tgz", + "integrity": "sha512-KigOCHcocU3XODJxsu8i/j8T9tzT4adHiecwORRQ0ZZFcp7ahwXuRU1m+yuO90C5ZUyGeGfocHDI14M3L3yDAQ==", + "license": "MIT" + }, + "node_modules/resize-observer-polyfill": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/resize-observer-polyfill/-/resize-observer-polyfill-1.5.1.tgz", + "integrity": "sha512-LwZrotdHOo12nQuZlHEmtuXdqGoOD0OhaxopaNFxWzInpEgaLWoVuAMbTzixuosCx2nEG58ngzW3vxdWoxIgdg==" + }, + "node_modules/resolve": { + "version": "1.22.8", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.8.tgz", + "integrity": "sha512-oKWePCxqpd6FlLvGV1VU0x7bkPmmCNolxzjMf4NczoDnQcIWrAF+cPtZn5i6n+RfD2d9i0tzpKnG6Yk168yIyw==", + "license": "MIT", + "dependencies": { + "is-core-module": "^2.13.0", + "path-parse": "^1.0.7", + "supports-preserve-symlinks-flag": "^1.0.0" + }, + "bin": { + "resolve": "bin/resolve" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/resolve-from": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-4.0.0.tgz", + "integrity": "sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==", + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/resolve-pkg-maps": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/resolve-pkg-maps/-/resolve-pkg-maps-1.0.0.tgz", + "integrity": "sha512-seS2Tj26TBVOC2NIc2rOe2y2ZO7efxITtLZcGSOnHHNOQ7CkiUBfw0Iw2ck6xkIhPwLhKNLS8BO+hEpngQlqzw==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/privatenumber/resolve-pkg-maps?sponsor=1" + } + }, + "node_modules/reusify": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/reusify/-/reusify-1.0.4.tgz", + "integrity": "sha512-U9nH88a3fc/ekCF1l0/UP1IosiuIjyTh7hBvXVMHYgVcfGvt897Xguj2UOLDeI5BG2m7/uwyaLVT6fbtCwTyzw==", + "license": "MIT", + "engines": { + "iojs": ">=1.0.0", + "node": ">=0.10.0" + } + }, + "node_modules/rimraf": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-3.0.2.tgz", + "integrity": "sha512-JZkJMZkAGFFPP2YqXZXPbMlMBgsxzE8ILs4lMIX/2o0L9UBw9O/Y3o6wFw/i9YLapcUJWwqbi3kdxIPdC62TIA==", + "deprecated": "Rimraf versions prior to v4 are no longer supported", + "dev": true, + "license": "ISC", + "dependencies": { + "glob": "^7.1.3" + }, + "bin": { + "rimraf": "bin.js" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/rimraf/node_modules/glob": { + "version": "7.2.3", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz", + "integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==", + "deprecated": "Glob versions prior to v9 are no longer supported", + "dev": true, + "license": "ISC", + "dependencies": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.1.1", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + }, + "engines": { + "node": "*" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/run-parallel": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/run-parallel/-/run-parallel-1.2.0.tgz", + "integrity": "sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT", + "dependencies": { + "queue-microtask": "^1.2.2" + } + }, + "node_modules/safe-array-concat": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/safe-array-concat/-/safe-array-concat-1.1.2.tgz", + "integrity": "sha512-vj6RsCsWBCf19jIeHEfkRMw8DPiBb+DMXklQ/1SGDHOMlHdPUkZXFQ2YdplS23zESTijAcurb1aSgJA3AgMu1Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.7", + "get-intrinsic": "^1.2.4", + "has-symbols": "^1.0.3", + "isarray": "^2.0.5" + }, + "engines": { + "node": ">=0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/safe-regex-test": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/safe-regex-test/-/safe-regex-test-1.0.3.tgz", + "integrity": "sha512-CdASjNJPvRa7roO6Ra/gLYBTzYzzPyyBXxIMdGW3USQLyjWEls2RgW5UBTXaQVp+OrpeCK3bLem8smtmheoRuw==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.6", + "es-errors": "^1.3.0", + "is-regex": "^1.1.4" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/scheduler": { + "version": "0.23.2", + "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.23.2.tgz", + "integrity": "sha512-UOShsPwz7NrMUqhR6t0hWjFduvOzbtv7toDH1/hIrfRNIDBnnBWd0CwJTGvTpngVlmwGCdP9/Zl/tVrDqcuYzQ==", + "license": "MIT", + "dependencies": { + "loose-envify": "^1.1.0" + } + }, + "node_modules/semver": { + "version": "7.6.3", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.6.3.tgz", + "integrity": "sha512-oVekP1cKtI+CTDvHWYFUcMtsK/00wmAEfyqKfNdARm8u1wNVhSgaX7A8d4UuIlUI5e84iEwOhs7ZPYRmzU9U6A==", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/set-function-length": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/set-function-length/-/set-function-length-1.2.2.tgz", + "integrity": "sha512-pgRc4hJ4/sNjWCSS9AmnS40x3bNMDTknHgL5UaMBTMyJnU90EgWh1Rz+MC9eFu4BuN/UwZjKQuY/1v3rM7HMfg==", + "dev": true, + "license": "MIT", + "dependencies": { + "define-data-property": "^1.1.4", + "es-errors": "^1.3.0", + "function-bind": "^1.1.2", + "get-intrinsic": "^1.2.4", + "gopd": "^1.0.1", + "has-property-descriptors": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/set-function-name": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/set-function-name/-/set-function-name-2.0.2.tgz", + "integrity": "sha512-7PGFlmtwsEADb0WYyvCMa1t+yke6daIG4Wirafur5kcf+MhUnPms1UeR0CKQdTZD81yESwMHbtn+TR+dMviakQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "define-data-property": "^1.1.4", + "es-errors": "^1.3.0", + "functions-have-names": "^1.2.3", + "has-property-descriptors": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/shebang-command": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", + "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", + "license": "MIT", + "dependencies": { + "shebang-regex": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/shebang-regex": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", + "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/shifty": { + "version": "2.20.4", + "resolved": "https://registry.npmjs.org/shifty/-/shifty-2.20.4.tgz", + "integrity": "sha512-4Y0qRkg8ME5XN8yGNAwmFOmsIURGFKT9UQfNL6DDJQErYtN5HsjyoBuJn41ZQfTkuu2rIbRMn9qazjKsDpO2TA==", + "license": "MIT", + "optionalDependencies": { + "fsevents": "^2.3.2" + } + }, + "node_modules/shiki": { + "version": "1.22.2", + "resolved": "https://registry.npmjs.org/shiki/-/shiki-1.22.2.tgz", + "integrity": "sha512-3IZau0NdGKXhH2bBlUk4w1IHNxPh6A5B2sUpyY+8utLu2j/h1QpFkAaUA1bAMxOWWGtTWcAh531vnS4NJKS/lA==", + "license": "MIT", + "dependencies": { + "@shikijs/core": "1.22.2", + "@shikijs/engine-javascript": "1.22.2", + "@shikijs/engine-oniguruma": "1.22.2", + "@shikijs/types": "1.22.2", + "@shikijs/vscode-textmate": "^9.3.0", + "@types/hast": "^3.0.4" + } + }, + "node_modules/shiki/node_modules/@types/hast": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/@types/hast/-/hast-3.0.4.tgz", + "integrity": "sha512-WPs+bbQw5aCj+x6laNGWLH3wviHtoCv/P3+otBhbOhJgG8qtpdAMlTCxLtsTWA7LH1Oh/bFCHsBn0TPS5m30EQ==", + "license": "MIT", + "dependencies": { + "@types/unist": "*" + } + }, + "node_modules/side-channel": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.0.6.tgz", + "integrity": "sha512-fDW/EZ6Q9RiO8eFG8Hj+7u/oW+XrPTIChwCOM2+th2A6OblDtYYIpve9m+KvI9Z4C9qSEXlaGR6bTEYHReuglA==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.7", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.4", + "object-inspect": "^1.13.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/signal-exit": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz", + "integrity": "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==", + "license": "ISC", + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/simple-peer": { + "version": "9.11.1", + "resolved": "https://registry.npmjs.org/simple-peer/-/simple-peer-9.11.1.tgz", + "integrity": "sha512-D1SaWpOW8afq1CZGWB8xTfrT3FekjQmPValrqncJMX7QFl8YwhrPTZvMCANLtgBwwdS+7zURyqxDDEmY558tTw==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "dependencies": { + "buffer": "^6.0.3", + "debug": "^4.3.2", + "err-code": "^3.0.1", + "get-browser-rtc": "^1.1.0", + "queue-microtask": "^1.2.3", + "randombytes": "^2.1.0", + "readable-stream": "^3.6.0" + } + }, + "node_modules/slash": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/slash/-/slash-3.0.0.tgz", + "integrity": "sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/sockjs-client": { + "version": "1.6.1", + "resolved": "https://registry.npmjs.org/sockjs-client/-/sockjs-client-1.6.1.tgz", + "integrity": "sha512-2g0tjOR+fRs0amxENLi/q5TiJTqY+WXFOzb5UwXndlK6TO3U/mirZznpx6w34HVMoc3g7cY24yC/ZMIYnDlfkw==", + "license": "MIT", + "dependencies": { + "debug": "^3.2.7", + "eventsource": "^2.0.2", + "faye-websocket": "^0.11.4", + "inherits": "^2.0.4", + "url-parse": "^1.5.10" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://tidelift.com/funding/github/npm/sockjs-client" + } + }, + "node_modules/sockjs-client/node_modules/debug": { + "version": "3.2.7", + "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.7.tgz", + "integrity": "sha512-CFjzYYAi4ThfiQvizrFQevTTXHtnCqWfe7x1AhgEscTz6ZbLbfoLRLPugTQyBth6f8ZERVUSyWHFD/7Wu4t1XQ==", + "license": "MIT", + "dependencies": { + "ms": "^2.1.1" + } + }, + "node_modules/source-map": { + "version": "0.5.7", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.7.tgz", + "integrity": "sha512-LbrmJOMUSdEVxIKvdcJzQC+nQhe8FUZQTXQy6+I75skNgn3OoQ0DZA8YnFa7gp8tqtL3KPf1kmo0R5DoApeSGQ==", + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/source-map-js": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz", + "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==", + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/space-separated-tokens": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/space-separated-tokens/-/space-separated-tokens-1.1.5.tgz", + "integrity": "sha512-q/JSVd1Lptzhf5bkYm4ob4iWPjx0KiRe3sRFBNrVqbJkFaBm5vbbowy1mymoPNLRa52+oadOhJ+K49wsSeSjTA==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/state-local": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/state-local/-/state-local-1.0.7.tgz", + "integrity": "sha512-HTEHMNieakEnoe33shBYcZ7NX83ACUjCu8c40iOGEZsngj9zRnkqS9j1pqQPXwobB0ZcVTk27REb7COQ0UR59w==" + }, + "node_modules/stop-iteration-iterator": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/stop-iteration-iterator/-/stop-iteration-iterator-1.0.0.tgz", + "integrity": "sha512-iCGQj+0l0HOdZ2AEeBADlsRC+vsnDsZsbdSiH1yNSjcfKM7fdpCMfqAL/dwF5BLiw/XhRft/Wax6zQbhq2BcjQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "internal-slot": "^1.0.4" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/streamsearch": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/streamsearch/-/streamsearch-1.1.0.tgz", + "integrity": "sha512-Mcc5wHehp9aXz1ax6bZUyY5afg9u2rv5cqQI3mRrYkGC8rW2hM02jWuwjtL++LS5qinSyhj2QfLyNsuc+VsExg==", + "engines": { + "node": ">=10.0.0" + } + }, + "node_modules/string_decoder": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", + "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==", + "dependencies": { + "safe-buffer": "~5.2.0" + } + }, + "node_modules/string-width": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-5.1.2.tgz", + "integrity": "sha512-HnLOCR3vjcY8beoNLtcjZ5/nxn2afmME6lhrDrebokqMap+XbeW8n9TXpPDOqdGK5qcI3oT0GKTW6wC7EMiVqA==", + "license": "MIT", + "dependencies": { + "eastasianwidth": "^0.2.0", + "emoji-regex": "^9.2.2", + "strip-ansi": "^7.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/string-width-cjs": { + "name": "string-width", + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "license": "MIT", + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/string-width-cjs/node_modules/emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", + "license": "MIT" + }, + "node_modules/string-width/node_modules/ansi-regex": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.1.0.tgz", + "integrity": "sha512-7HSX4QQb4CspciLpVFwyRe79O3xsIZDDLER21kERQ71oaPodF8jL725AgJMFAYbooIqolJoRLuM81SpeUkpkvA==", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-regex?sponsor=1" + } + }, + "node_modules/string-width/node_modules/strip-ansi": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.1.0.tgz", + "integrity": "sha512-iq6eVVI64nQQTRYq2KtEg2d2uU7LElhTJwsH4YzIHZshxlgZms/wIc4VoDQTlG/IvVIrBKG06CrZnp0qv7hkcQ==", + "license": "MIT", + "dependencies": { + "ansi-regex": "^6.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/strip-ansi?sponsor=1" + } + }, + "node_modules/string.prototype.includes": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/string.prototype.includes/-/string.prototype.includes-2.0.0.tgz", + "integrity": "sha512-E34CkBgyeqNDcrbU76cDjL5JLcVrtSdYq0MEh/B10r17pRP4ciHLwTgnuLV8Ay6cgEMLkcBkFCKyFZ43YldYzg==", + "dev": true, + "license": "MIT", + "dependencies": { + "define-properties": "^1.1.3", + "es-abstract": "^1.17.5" + } + }, + "node_modules/string.prototype.matchall": { + "version": "4.0.11", + "resolved": "https://registry.npmjs.org/string.prototype.matchall/-/string.prototype.matchall-4.0.11.tgz", + "integrity": "sha512-NUdh0aDavY2og7IbBPenWqR9exH+E26Sv8e0/eTe1tltDGZL+GtBkDAnnyBtmekfK6/Dq3MkcGtzXFEd1LQrtg==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.7", + "define-properties": "^1.2.1", + "es-abstract": "^1.23.2", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.0.0", + "get-intrinsic": "^1.2.4", + "gopd": "^1.0.1", + "has-symbols": "^1.0.3", + "internal-slot": "^1.0.7", + "regexp.prototype.flags": "^1.5.2", + "set-function-name": "^2.0.2", + "side-channel": "^1.0.6" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/string.prototype.repeat": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/string.prototype.repeat/-/string.prototype.repeat-1.0.0.tgz", + "integrity": "sha512-0u/TldDbKD8bFCQ/4f5+mNRrXwZ8hg2w7ZR8wa16e8z9XpePWl3eGEcUD0OXpEH/VJH/2G3gjUtR3ZOiBe2S/w==", + "dev": true, + "license": "MIT", + "dependencies": { + "define-properties": "^1.1.3", + "es-abstract": "^1.17.5" + } + }, + "node_modules/string.prototype.trim": { + "version": "1.2.9", + "resolved": "https://registry.npmjs.org/string.prototype.trim/-/string.prototype.trim-1.2.9.tgz", + "integrity": "sha512-klHuCNxiMZ8MlsOihJhJEBJAiMVqU3Z2nEXWfWnIqjN0gEFS9J9+IxKozWWtQGcgoa1WUZzLjKPTr4ZHNFTFxw==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.7", + "define-properties": "^1.2.1", + "es-abstract": "^1.23.0", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/string.prototype.trimend": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/string.prototype.trimend/-/string.prototype.trimend-1.0.8.tgz", + "integrity": "sha512-p73uL5VCHCO2BZZ6krwwQE3kCzM7NKmis8S//xEC6fQonchbum4eP6kR4DLEjQFO3Wnj3Fuo8NM0kOSjVdHjZQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.7", + "define-properties": "^1.2.1", + "es-object-atoms": "^1.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/string.prototype.trimstart": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/string.prototype.trimstart/-/string.prototype.trimstart-1.0.8.tgz", + "integrity": "sha512-UXSH262CSZY1tfu3G3Secr6uGLCFVPMhIqHjlgCUtCCcgihYc/xKs9djMTMUOb2j1mVSeU8EU6NWc/iQKU6Gfg==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.7", + "define-properties": "^1.2.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/stringify-entities": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/stringify-entities/-/stringify-entities-4.0.4.tgz", + "integrity": "sha512-IwfBptatlO+QCJUo19AqvrPNqlVMpW9YEL2LIVY+Rpv2qsjCGxaDLNRgeGsQWJhfItebuJhsGSLjaBbNSQ+ieg==", + "license": "MIT", + "dependencies": { + "character-entities-html4": "^2.0.0", + "character-entities-legacy": "^3.0.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/stringify-entities/node_modules/character-entities-legacy": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/character-entities-legacy/-/character-entities-legacy-3.0.0.tgz", + "integrity": "sha512-RpPp0asT/6ufRm//AJVwpViZbGM/MkjQFxJccQRHmISF/22NBtsHqAWmL+/pmkPWoIUJdWyeVleTl1wydHATVQ==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "license": "MIT", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-ansi-cjs": { + "name": "strip-ansi", + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "license": "MIT", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-bom": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-3.0.0.tgz", + "integrity": "sha512-vavAMRXOgBVNF6nyEEmL3DBK19iRpDcoIwW+swQ+CbGiu7lju6t+JklA1MHweoWtadgt4ISVUsXLyDq34ddcwA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/strip-json-comments": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.1.1.tgz", + "integrity": "sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/styled-jsx": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/styled-jsx/-/styled-jsx-5.1.1.tgz", + "integrity": "sha512-pW7uC1l4mBZ8ugbiZrcIsiIvVx1UmTfw7UkC3Um2tmfUq9Bhk8IiyEIPl6F8agHgjzku6j0xQEZbfA5uSgSaCw==", + "license": "MIT", + "dependencies": { + "client-only": "0.0.1" + }, + "engines": { + "node": ">= 12.0.0" + }, + "peerDependencies": { + "react": ">= 16.8.0 || 17.x.x || ^18.0.0-0" + }, + "peerDependenciesMeta": { + "@babel/core": { + "optional": true + }, + "babel-plugin-macros": { + "optional": true + } + } + }, + "node_modules/stylis": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/stylis/-/stylis-4.2.0.tgz", + "integrity": "sha512-Orov6g6BB1sDfYgzWfTHDOxamtX1bE/zo104Dh9e6fqJ3PooipYyfJ0pUmrZO2wAvO8YbEyeFrkV91XTsGMSrw==", + "license": "MIT" + }, + "node_modules/sucrase": { + "version": "3.35.0", + "resolved": "https://registry.npmjs.org/sucrase/-/sucrase-3.35.0.tgz", + "integrity": "sha512-8EbVDiu9iN/nESwxeSxDKe0dunta1GOlHufmSSXxMD2z2/tMZpDMpvXQGsc+ajGo8y2uYUmixaSRUc/QPoQ0GA==", + "license": "MIT", + "dependencies": { + "@jridgewell/gen-mapping": "^0.3.2", + "commander": "^4.0.0", + "glob": "^10.3.10", + "lines-and-columns": "^1.1.6", + "mz": "^2.7.0", + "pirates": "^4.0.1", + "ts-interface-checker": "^0.1.9" + }, + "bin": { + "sucrase": "bin/sucrase", + "sucrase-node": "bin/sucrase-node" + }, + "engines": { + "node": ">=16 || 14 >=14.17" + } + }, + "node_modules/supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dev": true, + "license": "MIT", + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/supports-preserve-symlinks-flag": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz", + "integrity": "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/sweetalert2": { + "version": "11.14.1", + "resolved": "https://registry.npmjs.org/sweetalert2/-/sweetalert2-11.14.1.tgz", + "integrity": "sha512-xadhfcA4STGMh8nC5zHFFWURhRpWc4zyI3GdMDFH/m3hGWZeQQNWhX9xcG4lI9gZYsi/IlazKbwvvje3juL3Xg==", + "license": "MIT", + "funding": { + "type": "individual", + "url": "https://github.com/sponsors/limonte" + } + }, + "node_modules/tailwind-merge": { + "version": "2.5.2", + "resolved": "https://registry.npmjs.org/tailwind-merge/-/tailwind-merge-2.5.2.tgz", + "integrity": "sha512-kjEBm+pvD+6eAwzJL2Bi+02/9LFLal1Gs61+QB7HvTfQQ0aXwC5LGT8PEt1gS0CWKktKe6ysPTAy3cBC5MeiIg==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/dcastil" + } + }, + "node_modules/tailwindcss": { + "version": "3.4.11", + "resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-3.4.11.tgz", + "integrity": "sha512-qhEuBcLemjSJk5ajccN9xJFtM/h0AVCPaA6C92jNP+M2J8kX+eMJHI7R2HFKUvvAsMpcfLILMCFYSeDwpMmlUg==", + "license": "MIT", + "dependencies": { + "@alloc/quick-lru": "^5.2.0", + "arg": "^5.0.2", + "chokidar": "^3.5.3", + "didyoumean": "^1.2.2", + "dlv": "^1.1.3", + "fast-glob": "^3.3.0", + "glob-parent": "^6.0.2", + "is-glob": "^4.0.3", + "jiti": "^1.21.0", + "lilconfig": "^2.1.0", + "micromatch": "^4.0.5", + "normalize-path": "^3.0.0", + "object-hash": "^3.0.0", + "picocolors": "^1.0.0", + "postcss": "^8.4.23", + "postcss-import": "^15.1.0", + "postcss-js": "^4.0.1", + "postcss-load-config": "^4.0.1", + "postcss-nested": "^6.0.1", + "postcss-selector-parser": "^6.0.11", + "resolve": "^1.22.2", + "sucrase": "^3.32.0" + }, + "bin": { + "tailwind": "lib/cli.js", + "tailwindcss": "lib/cli.js" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/tailwindcss-animate": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/tailwindcss-animate/-/tailwindcss-animate-1.0.7.tgz", + "integrity": "sha512-bl6mpH3T7I3UFxuvDEXLxy/VuFxBk5bbzplh7tXI68mwMokNYd1t9qPBHlnyTwfa4JGC4zP516I1hYYtQ/vspA==", + "license": "MIT", + "peerDependencies": { + "tailwindcss": ">=3.0.0 || insiders" + } + }, + "node_modules/tapable": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/tapable/-/tapable-2.2.1.tgz", + "integrity": "sha512-GNzQvQTOIP6RyTfE2Qxb8ZVlNmw0n88vp1szwWRimP02mnTsx3Wtn5qRdqY9w2XduFNUgvOwhNnQsjwCp+kqaQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/text-table": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/text-table/-/text-table-0.2.0.tgz", + "integrity": "sha512-N+8UisAXDGk8PFXP4HAzVR9nbfmVJ3zYLAWiTIoqC5v5isinhr+r5uaO8+7r3BMfuNIufIsA7RdpVgacC2cSpw==", + "dev": true, + "license": "MIT" + }, + "node_modules/thenify": { + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/thenify/-/thenify-3.3.1.tgz", + "integrity": "sha512-RVZSIV5IG10Hk3enotrhvz0T9em6cyHBLkH/YAZuKqd8hRkKhSfCGIcP2KUY0EPxndzANBmNllzWPwak+bheSw==", + "license": "MIT", + "dependencies": { + "any-promise": "^1.0.0" + } + }, + "node_modules/thenify-all": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/thenify-all/-/thenify-all-1.6.0.tgz", + "integrity": "sha512-RNxQH/qI8/t3thXJDwcstUO4zeqo64+Uy/+sNVRBx4Xn2OX+OZ9oP+iJnNFqplFra2ZUVeKCSa2oVWi3T4uVmA==", + "license": "MIT", + "dependencies": { + "thenify": ">= 3.1.0 < 4" + }, + "engines": { + "node": ">=0.8" + } + }, + "node_modules/timeago.js": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/timeago.js/-/timeago.js-4.0.2.tgz", + "integrity": "sha512-a7wPxPdVlQL7lqvitHGGRsofhdwtkoSXPGATFuSOA2i1ZNQEPLrGnj68vOp2sOJTCFAQVXPeNMX/GctBaO9L2w==", + "license": "MIT" + }, + "node_modules/to-fast-properties": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/to-fast-properties/-/to-fast-properties-2.0.0.tgz", + "integrity": "sha512-/OaKK0xYrs3DmxRYqL/yDc+FxFUVYhDlXMhRmv3z915w2HF1tnN1omB354j8VUGO/hbRzyD6Y3sA7v7GS/ceog==", + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/to-regex-range": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", + "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", + "license": "MIT", + "dependencies": { + "is-number": "^7.0.0" + }, + "engines": { + "node": ">=8.0" + } + }, + "node_modules/trim-lines": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/trim-lines/-/trim-lines-3.0.1.tgz", + "integrity": "sha512-kRj8B+YHZCc9kQYdWfJB2/oUl9rA99qbowYYBtr4ui4mZyAQ2JpvVBd/6U2YloATfqBhBTSMhTpgBHtU0Mf3Rg==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/ts-api-utils": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/ts-api-utils/-/ts-api-utils-1.3.0.tgz", + "integrity": "sha512-UQMIo7pb8WRomKR1/+MFVLTroIvDVtMX3K6OUir8ynLyzB8Jeriont2bTAtmNPa1ekAgN7YPDyf6V+ygrdU+eQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=16" + }, + "peerDependencies": { + "typescript": ">=4.2.0" + } + }, + "node_modules/ts-interface-checker": { + "version": "0.1.13", + "resolved": "https://registry.npmjs.org/ts-interface-checker/-/ts-interface-checker-0.1.13.tgz", + "integrity": "sha512-Y/arvbn+rrz3JCKl9C4kVNfTfSm2/mEp5FSz5EsZSANGPSlQrpRI5M4PKF+mJnE52jOO90PnPSc3Ur3bTQw0gA==", + "license": "Apache-2.0" + }, + "node_modules/tsconfig-paths": { + "version": "3.15.0", + "resolved": "https://registry.npmjs.org/tsconfig-paths/-/tsconfig-paths-3.15.0.tgz", + "integrity": "sha512-2Ac2RgzDe/cn48GvOe3M+o82pEFewD3UPbyoUHHdKasHwJKjds4fLXWf/Ux5kATBKN20oaFGu+jbElp1pos0mg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/json5": "^0.0.29", + "json5": "^1.0.2", + "minimist": "^1.2.6", + "strip-bom": "^3.0.0" + } + }, + "node_modules/tslib": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.7.0.tgz", + "integrity": "sha512-gLXCKdN1/j47AiHiOkJN69hJmcbGTHI0ImLmbYLHykhgeN0jVGola9yVjFgzCUklsZQMW55o+dW7IXv3RCXDzA==", + "license": "0BSD" + }, + "node_modules/type-check": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz", + "integrity": "sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew==", + "dev": true, + "license": "MIT", + "dependencies": { + "prelude-ls": "^1.2.1" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/type-fest": { + "version": "0.20.2", + "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.20.2.tgz", + "integrity": "sha512-Ne+eE4r0/iWnpAxD852z3A+N0Bt5RN//NjJwRd2VFHEmrywxf5vsZlh4R6lixl6B+wz/8d+maTSAkN1FIkI3LQ==", + "dev": true, + "license": "(MIT OR CC0-1.0)", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/typed-array-buffer": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/typed-array-buffer/-/typed-array-buffer-1.0.2.tgz", + "integrity": "sha512-gEymJYKZtKXzzBzM4jqa9w6Q1Jjm7x2d+sh19AdsD4wqnMPDYyvwpsIc2Q/835kHuo3BEQ7CjelGhfTsoBb2MQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.7", + "es-errors": "^1.3.0", + "is-typed-array": "^1.1.13" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/typed-array-byte-length": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/typed-array-byte-length/-/typed-array-byte-length-1.0.1.tgz", + "integrity": "sha512-3iMJ9q0ao7WE9tWcaYKIptkNBuOIcZCCT0d4MRvuuH88fEoEH62IuQe0OtraD3ebQEoTRk8XCBoknUNc1Y67pw==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.7", + "for-each": "^0.3.3", + "gopd": "^1.0.1", + "has-proto": "^1.0.3", + "is-typed-array": "^1.1.13" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/typed-array-byte-offset": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/typed-array-byte-offset/-/typed-array-byte-offset-1.0.2.tgz", + "integrity": "sha512-Ous0vodHa56FviZucS2E63zkgtgrACj7omjwd/8lTEMEPFFyjfixMZ1ZXenpgCFBBt4EC1J2XsyVS2gkG0eTFA==", + "dev": true, + "license": "MIT", + "dependencies": { + "available-typed-arrays": "^1.0.7", + "call-bind": "^1.0.7", + "for-each": "^0.3.3", + "gopd": "^1.0.1", + "has-proto": "^1.0.3", + "is-typed-array": "^1.1.13" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/typed-array-length": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/typed-array-length/-/typed-array-length-1.0.6.tgz", + "integrity": "sha512-/OxDN6OtAk5KBpGb28T+HZc2M+ADtvRxXrKKbUwtsLgdoxgX13hyy7ek6bFRl5+aBs2yZzB0c4CnQfAtVypW/g==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.7", + "for-each": "^0.3.3", + "gopd": "^1.0.1", + "has-proto": "^1.0.3", + "is-typed-array": "^1.1.13", + "possible-typed-array-names": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/typescript": { + "version": "5.6.2", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.6.2.tgz", + "integrity": "sha512-NW8ByodCSNCwZeghjN3o+JX5OFH0Ojg6sadjEKY4huZ52TqbJTJnDo5+Tw98lSy63NZvi4n+ez5m2u5d4PkZyw==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/unbox-primitive": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/unbox-primitive/-/unbox-primitive-1.0.2.tgz", + "integrity": "sha512-61pPlCD9h51VoreyJ0BReideM3MDKMKnh6+V9L08331ipq6Q8OFXZYiqP6n/tbHx4s5I9uRhcye6BrbkizkBDw==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.2", + "has-bigints": "^1.0.2", + "has-symbols": "^1.0.3", + "which-boxed-primitive": "^1.0.2" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/undici-types": { + "version": "6.19.8", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.19.8.tgz", + "integrity": "sha512-ve2KP6f/JnbPBFyobGHuerC9g1FYGn/F8n1LWTwNxCEzd6IfqTwUQcNXgEtmmQ6DlRrC1hrSrBnCZPokRrDHjw==", + "dev": true, + "license": "MIT" + }, + "node_modules/unist-util-is": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/unist-util-is/-/unist-util-is-6.0.0.tgz", + "integrity": "sha512-2qCTHimwdxLfz+YzdGfkqNlH0tLi9xjTnHddPmJwtIG9MGsdbutfTc4P+haPD7l7Cjxf/WZj+we5qfVPvvxfYw==", + "license": "MIT", + "dependencies": { + "@types/unist": "^3.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/unist-util-is/node_modules/@types/unist": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/@types/unist/-/unist-3.0.3.tgz", + "integrity": "sha512-ko/gIFJRv177XgZsZcBwnqJN5x/Gien8qNOn0D5bQU/zAzVf9Zt3BlcUiLqhV9y4ARk0GbT3tnUiPNgnTXzc/Q==", + "license": "MIT" + }, + "node_modules/unist-util-position": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/unist-util-position/-/unist-util-position-5.0.0.tgz", + "integrity": "sha512-fucsC7HjXvkB5R3kTCO7kUjRdrS0BJt3M/FPxmHMBOm8JQi2BsHAHFsy27E0EolP8rp0NzXsJ+jNPyDWvOJZPA==", + "license": "MIT", + "dependencies": { + "@types/unist": "^3.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/unist-util-position/node_modules/@types/unist": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/@types/unist/-/unist-3.0.3.tgz", + "integrity": "sha512-ko/gIFJRv177XgZsZcBwnqJN5x/Gien8qNOn0D5bQU/zAzVf9Zt3BlcUiLqhV9y4ARk0GbT3tnUiPNgnTXzc/Q==", + "license": "MIT" + }, + "node_modules/unist-util-stringify-position": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/unist-util-stringify-position/-/unist-util-stringify-position-4.0.0.tgz", + "integrity": "sha512-0ASV06AAoKCDkS2+xw5RXJywruurpbC4JZSm7nr7MOt1ojAzvyyaO+UxZf18j8FCF6kmzCZKcAgN/yu2gm2XgQ==", + "license": "MIT", + "dependencies": { + "@types/unist": "^3.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/unist-util-stringify-position/node_modules/@types/unist": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/@types/unist/-/unist-3.0.3.tgz", + "integrity": "sha512-ko/gIFJRv177XgZsZcBwnqJN5x/Gien8qNOn0D5bQU/zAzVf9Zt3BlcUiLqhV9y4ARk0GbT3tnUiPNgnTXzc/Q==", + "license": "MIT" + }, + "node_modules/unist-util-visit": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/unist-util-visit/-/unist-util-visit-5.0.0.tgz", + "integrity": "sha512-MR04uvD+07cwl/yhVuVWAtw+3GOR/knlL55Nd/wAdblk27GCVt3lqpTivy/tkJcZoNPzTwS1Y+KMojlLDhoTzg==", + "license": "MIT", + "dependencies": { + "@types/unist": "^3.0.0", + "unist-util-is": "^6.0.0", + "unist-util-visit-parents": "^6.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/unist-util-visit-parents": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/unist-util-visit-parents/-/unist-util-visit-parents-6.0.1.tgz", + "integrity": "sha512-L/PqWzfTP9lzzEa6CKs0k2nARxTdZduw3zyh8d2NVBnsyvHjSX4TWse388YrrQKbvI8w20fGjGlhgT96WwKykw==", + "license": "MIT", + "dependencies": { + "@types/unist": "^3.0.0", + "unist-util-is": "^6.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/unist-util-visit-parents/node_modules/@types/unist": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/@types/unist/-/unist-3.0.3.tgz", + "integrity": "sha512-ko/gIFJRv177XgZsZcBwnqJN5x/Gien8qNOn0D5bQU/zAzVf9Zt3BlcUiLqhV9y4ARk0GbT3tnUiPNgnTXzc/Q==", + "license": "MIT" + }, + "node_modules/unist-util-visit/node_modules/@types/unist": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/@types/unist/-/unist-3.0.3.tgz", + "integrity": "sha512-ko/gIFJRv177XgZsZcBwnqJN5x/Gien8qNOn0D5bQU/zAzVf9Zt3BlcUiLqhV9y4ARk0GbT3tnUiPNgnTXzc/Q==", + "license": "MIT" + }, + "node_modules/uri-js": { + "version": "4.4.1", + "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz", + "integrity": "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "punycode": "^2.1.0" + } + }, + "node_modules/url-parse": { + "version": "1.5.10", + "resolved": "https://registry.npmjs.org/url-parse/-/url-parse-1.5.10.tgz", + "integrity": "sha512-WypcfiRhfeUP9vvF0j6rw0J3hrWrw6iZv3+22h6iRMJ/8z1Tj6XfLP4DsUix5MhMPnXpiHDoKyoZ/bdCkwBCiQ==", + "license": "MIT", + "dependencies": { + "querystringify": "^2.1.1", + "requires-port": "^1.0.0" + } + }, + "node_modules/use-callback-ref": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/use-callback-ref/-/use-callback-ref-1.3.2.tgz", + "integrity": "sha512-elOQwe6Q8gqZgDA8mrh44qRTQqpIHDcZ3hXTLjBe1i4ph8XpNJnO+aQf3NaG+lriLopI4HMx9VjQLfPQ6vhnoA==", + "license": "MIT", + "dependencies": { + "tslib": "^2.0.0" + }, + "engines": { + "node": ">=10" + }, + "peerDependencies": { + "@types/react": "^16.8.0 || ^17.0.0 || ^18.0.0", + "react": "^16.8.0 || ^17.0.0 || ^18.0.0" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/use-isomorphic-layout-effect": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/use-isomorphic-layout-effect/-/use-isomorphic-layout-effect-1.1.2.tgz", + "integrity": "sha512-49L8yCO3iGT/ZF9QttjwLF/ZD9Iwto5LnH5LmEdk/6cFmXddqi2ulF0edxTwjj+7mqvpVVGQWvbXZdn32wRSHA==", + "license": "MIT", + "peerDependencies": { + "react": "^16.8.0 || ^17.0.0 || ^18.0.0" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/use-sidecar": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/use-sidecar/-/use-sidecar-1.1.2.tgz", + "integrity": "sha512-epTbsLuzZ7lPClpz2TyryBfztm7m+28DlEv2ZCQ3MDr5ssiwyOwGH/e5F9CkfWjJ1t4clvI58yF822/GUkjjhw==", + "license": "MIT", + "dependencies": { + "detect-node-es": "^1.1.0", + "tslib": "^2.0.0" + }, + "engines": { + "node": ">=10" + }, + "peerDependencies": { + "@types/react": "^16.9.0 || ^17.0.0 || ^18.0.0", + "react": "^16.8.0 || ^17.0.0 || ^18.0.0" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/util-deprecate": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", + "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==", + "license": "MIT" + }, + "node_modules/uuid": { + "version": "10.0.0", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-10.0.0.tgz", + "integrity": "sha512-8XkAphELsDnEGrDxUOHB3RGvXz6TeuYSGEZBOjtTtPm2lwhGBjLgOzLHB63IUWfBpNucQjND6d3AOudO+H3RWQ==", + "funding": [ + "https://github.com/sponsors/broofa", + "https://github.com/sponsors/ctavan" + ], + "license": "MIT", + "bin": { + "uuid": "dist/bin/uuid" + } + }, + "node_modules/vfile": { + "version": "6.0.3", + "resolved": "https://registry.npmjs.org/vfile/-/vfile-6.0.3.tgz", + "integrity": "sha512-KzIbH/9tXat2u30jf+smMwFCsno4wHVdNmzFyL+T/L3UGqqk6JKfVqOFOZEpZSHADH1k40ab6NUIXZq422ov3Q==", + "license": "MIT", + "dependencies": { + "@types/unist": "^3.0.0", + "vfile-message": "^4.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/vfile-message": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/vfile-message/-/vfile-message-4.0.2.tgz", + "integrity": "sha512-jRDZ1IMLttGj41KcZvlrYAaI3CfqpLpfpf+Mfig13viT6NKvRzWZ+lXz0Y5D60w6uJIBAOGq9mSHf0gktF0duw==", + "license": "MIT", + "dependencies": { + "@types/unist": "^3.0.0", + "unist-util-stringify-position": "^4.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/vfile-message/node_modules/@types/unist": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/@types/unist/-/unist-3.0.3.tgz", + "integrity": "sha512-ko/gIFJRv177XgZsZcBwnqJN5x/Gien8qNOn0D5bQU/zAzVf9Zt3BlcUiLqhV9y4ARk0GbT3tnUiPNgnTXzc/Q==", + "license": "MIT" + }, + "node_modules/vfile/node_modules/@types/unist": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/@types/unist/-/unist-3.0.3.tgz", + "integrity": "sha512-ko/gIFJRv177XgZsZcBwnqJN5x/Gien8qNOn0D5bQU/zAzVf9Zt3BlcUiLqhV9y4ARk0GbT3tnUiPNgnTXzc/Q==", + "license": "MIT" + }, + "node_modules/warning": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/warning/-/warning-4.0.3.tgz", + "integrity": "sha512-rpJyN222KWIvHJ/F53XSZv0Zl/accqHR8et1kpaMTD/fLCRxtV8iX8czMzY7sVZupTI3zcUTg8eycS2kNF9l6w==", + "license": "MIT", + "dependencies": { + "loose-envify": "^1.0.0" + } + }, + "node_modules/websocket-driver": { + "version": "0.7.4", + "resolved": "https://registry.npmjs.org/websocket-driver/-/websocket-driver-0.7.4.tgz", + "integrity": "sha512-b17KeDIQVjvb0ssuSDF2cYXSg2iztliJ4B9WdsuB6J952qCPKmnVq4DyW5motImXHDC1cBT/1UezrJVsKw5zjg==", + "license": "Apache-2.0", + "dependencies": { + "http-parser-js": ">=0.5.1", + "safe-buffer": ">=5.1.0", + "websocket-extensions": ">=0.1.1" + }, + "engines": { + "node": ">=0.8.0" + } + }, + "node_modules/websocket-extensions": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/websocket-extensions/-/websocket-extensions-0.1.4.tgz", + "integrity": "sha512-OqedPIGOfsDlo31UNwYbCFMSaO9m9G/0faIHj5/dZFDMFqPTcx6UwqyOy3COEaEOg/9VsGIpdqn62W5KhoKSpg==", + "license": "Apache-2.0", + "engines": { + "node": ">=0.8.0" + } + }, + "node_modules/which": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", + "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", + "license": "ISC", + "dependencies": { + "isexe": "^2.0.0" + }, + "bin": { + "node-which": "bin/node-which" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/which-boxed-primitive": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/which-boxed-primitive/-/which-boxed-primitive-1.0.2.tgz", + "integrity": "sha512-bwZdv0AKLpplFY2KZRX6TvyuN7ojjr7lwkg6ml0roIy9YeuSr7JS372qlNW18UQYzgYK9ziGcerWqZOmEn9VNg==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-bigint": "^1.0.1", + "is-boolean-object": "^1.1.0", + "is-number-object": "^1.0.4", + "is-string": "^1.0.5", + "is-symbol": "^1.0.3" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/which-builtin-type": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/which-builtin-type/-/which-builtin-type-1.1.4.tgz", + "integrity": "sha512-bppkmBSsHFmIMSl8BO9TbsyzsvGjVoppt8xUiGzwiu/bhDCGxnpOKCxgqj6GuyHE0mINMDecBFPlOm2hzY084w==", + "dev": true, + "license": "MIT", + "dependencies": { + "function.prototype.name": "^1.1.6", + "has-tostringtag": "^1.0.2", + "is-async-function": "^2.0.0", + "is-date-object": "^1.0.5", + "is-finalizationregistry": "^1.0.2", + "is-generator-function": "^1.0.10", + "is-regex": "^1.1.4", + "is-weakref": "^1.0.2", + "isarray": "^2.0.5", + "which-boxed-primitive": "^1.0.2", + "which-collection": "^1.0.2", + "which-typed-array": "^1.1.15" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/which-collection": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/which-collection/-/which-collection-1.0.2.tgz", + "integrity": "sha512-K4jVyjnBdgvc86Y6BkaLZEN933SwYOuBFkdmBu9ZfkcAbdVbpITnDmjvZ/aQjRXQrv5EPkTnD1s39GiiqbngCw==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-map": "^2.0.3", + "is-set": "^2.0.3", + "is-weakmap": "^2.0.2", + "is-weakset": "^2.0.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/which-typed-array": { + "version": "1.1.15", + "resolved": "https://registry.npmjs.org/which-typed-array/-/which-typed-array-1.1.15.tgz", + "integrity": "sha512-oV0jmFtUky6CXfkqehVvBP/LSWJ2sy4vWMioiENyJLePrBO/yKyV9OyJySfAKosh+RYkIl5zJCNZ8/4JncrpdA==", + "dev": true, + "license": "MIT", + "dependencies": { + "available-typed-arrays": "^1.0.7", + "call-bind": "^1.0.7", + "for-each": "^0.3.3", + "gopd": "^1.0.1", + "has-tostringtag": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/word-wrap": { + "version": "1.2.5", + "resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.5.tgz", + "integrity": "sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/wrap-ansi": { + "version": "8.1.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-8.1.0.tgz", + "integrity": "sha512-si7QWI6zUMq56bESFvagtmzMdGOtoxfR+Sez11Mobfc7tm+VkUckk9bW2UeffTGVUbOksxmSw0AA2gs8g71NCQ==", + "license": "MIT", + "dependencies": { + "ansi-styles": "^6.1.0", + "string-width": "^5.0.1", + "strip-ansi": "^7.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, + "node_modules/wrap-ansi-cjs": { + "name": "wrap-ansi", + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", + "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, + "node_modules/wrap-ansi-cjs/node_modules/emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", + "license": "MIT" + }, + "node_modules/wrap-ansi-cjs/node_modules/string-width": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "license": "MIT", + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/wrap-ansi/node_modules/ansi-regex": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.1.0.tgz", + "integrity": "sha512-7HSX4QQb4CspciLpVFwyRe79O3xsIZDDLER21kERQ71oaPodF8jL725AgJMFAYbooIqolJoRLuM81SpeUkpkvA==", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-regex?sponsor=1" + } + }, + "node_modules/wrap-ansi/node_modules/ansi-styles": { + "version": "6.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.1.tgz", + "integrity": "sha512-bN798gFfQX+viw3R7yrGWRqnrN2oRkEkUjjl4JNn4E8GxxbjtG3FbrEIIY3l8/hrwUwIeCZvi4QuOTP4MErVug==", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/wrap-ansi/node_modules/strip-ansi": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.1.0.tgz", + "integrity": "sha512-iq6eVVI64nQQTRYq2KtEg2d2uU7LElhTJwsH4YzIHZshxlgZms/wIc4VoDQTlG/IvVIrBKG06CrZnp0qv7hkcQ==", + "license": "MIT", + "dependencies": { + "ansi-regex": "^6.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/strip-ansi?sponsor=1" + } + }, + "node_modules/wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", + "dev": true, + "license": "ISC" + }, + "node_modules/ws": { + "version": "8.18.0", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.18.0.tgz", + "integrity": "sha512-8VbfWfHLbbwu3+N6OKsOMpBdT4kXPDDB9cJk2bJ6mh9ucxdlnNvH1e+roYkKmN9Nxw2yjz7VzeO9oOz2zJ04Pw==", + "optional": true, + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, + "node_modules/xtend": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz", + "integrity": "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==", + "license": "MIT", + "engines": { + "node": ">=0.4" + } + }, + "node_modules/y-monaco": { + "version": "0.1.6", + "resolved": "https://registry.npmjs.org/y-monaco/-/y-monaco-0.1.6.tgz", + "integrity": "sha512-sYRywMmcylt+Nupl+11AvizD2am06ST8lkVbUXuaEmrtV6Tf+TD4rsEm6u9YGGowYue+Vfg1IJ97SUP2J+PVXg==", + "dependencies": { + "lib0": "^0.2.43" + }, + "engines": { + "node": ">=12.0.0", + "npm": ">=6.0.0" + }, + "peerDependencies": { + "monaco-editor": ">=0.20.0", + "yjs": "^13.3.1" + } + }, + "node_modules/y-protocols": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/y-protocols/-/y-protocols-1.0.6.tgz", + "integrity": "sha512-vHRF2L6iT3rwj1jub/K5tYcTT/mEYDUppgNPXwp8fmLpui9f7Yeq3OEtTLVF012j39QnV+KEQpNqoN7CWU7Y9Q==", + "dependencies": { + "lib0": "^0.2.85" + }, + "engines": { + "node": ">=16.0.0", + "npm": ">=8.0.0" + }, + "funding": { + "type": "GitHub Sponsors ❤", + "url": "https://github.com/sponsors/dmonad" + }, + "peerDependencies": { + "yjs": "^13.0.0" + } + }, + "node_modules/y-webrtc": { + "version": "10.3.0", + "resolved": "https://registry.npmjs.org/y-webrtc/-/y-webrtc-10.3.0.tgz", + "integrity": "sha512-KalJr7dCgUgyVFxoG3CQYbpS0O2qybegD0vI4bYnYHI0MOwoVbucED3RZ5f2o1a5HZb1qEssUKS0H/Upc6p1lA==", + "dependencies": { + "lib0": "^0.2.42", + "simple-peer": "^9.11.0", + "y-protocols": "^1.0.6" + }, + "bin": { + "y-webrtc-signaling": "bin/server.js" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "type": "GitHub Sponsors ❤", + "url": "https://github.com/sponsors/dmonad" + }, + "optionalDependencies": { + "ws": "^8.14.2" + }, + "peerDependencies": { + "yjs": "^13.6.8" + } + }, + "node_modules/yaml": { + "version": "2.5.1", + "resolved": "https://registry.npmjs.org/yaml/-/yaml-2.5.1.tgz", + "integrity": "sha512-bLQOjaX/ADgQ20isPJRvF0iRUHIxVhYvr53Of7wGcWlO2jvtUlH5m87DsmulFVxRpNLOnI4tB6p/oh8D7kpn9Q==", + "license": "ISC", + "bin": { + "yaml": "bin.mjs" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/yjs": { + "version": "13.6.20", + "resolved": "https://registry.npmjs.org/yjs/-/yjs-13.6.20.tgz", + "integrity": "sha512-Z2YZI+SYqK7XdWlloI3lhMiKnCdFCVC4PchpdO+mCYwtiTwncjUbnRK9R1JmkNfdmHyDXuWN3ibJAt0wsqTbLQ==", + "dependencies": { + "lib0": "^0.2.98" + }, + "engines": { + "node": ">=16.0.0", + "npm": ">=8.0.0" + }, + "funding": { + "type": "GitHub Sponsors ❤", + "url": "https://github.com/sponsors/dmonad" + } + }, + "node_modules/yocto-queue": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz", + "integrity": "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/zod": { + "version": "3.23.8", + "resolved": "https://registry.npmjs.org/zod/-/zod-3.23.8.tgz", + "integrity": "sha512-XBx9AXhXktjUqnepgTiE5flcKIYWi/rme0Eaj+5Y0lftuGBq+jyRu/md4WnuxqgP1ubdpNCsYEYPxrzVHD8d6g==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/colinhacks" + } + }, + "node_modules/zwitch": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/zwitch/-/zwitch-2.0.4.tgz", + "integrity": "sha512-bXE4cR/kVZhKZX/RjPEflHaKVhUVl85noU3v6b8apfQEc1x4A+zBxjZ4lN8LqGd6WZ3dl98pY4o717VFmoPp+A==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + } + } +} diff --git a/frontend/package.json b/frontend/package.json new file mode 100644 index 0000000000..a2c73514e8 --- /dev/null +++ b/frontend/package.json @@ -0,0 +1,77 @@ +{ + "name": "frontend", + "version": "0.1.0", + "private": true, + "proxy": "https://question-service-598285527681.us-central1.run.app", + "scripts": { + "dev": "next dev", + "build": "next build", + "start": "next start", + "lint": "next lint" + }, + "dependencies": { + "@hookform/resolvers": "^3.9.0", + "@monaco-editor/react": "^4.6.0", + "@next/font": "^14.2.13", + "@radix-ui/react-checkbox": "^1.1.1", + "@radix-ui/react-dialog": "^1.1.1", + "@radix-ui/react-dropdown-menu": "^2.1.1", + "@radix-ui/react-label": "^2.1.0", + "@radix-ui/react-popover": "^1.1.1", + "@radix-ui/react-select": "^2.1.1", + "@radix-ui/react-separator": "^1.1.0", + "@radix-ui/react-slot": "^1.1.0", + "@radix-ui/react-tooltip": "^1.1.3", + "@react-oauth/google": "^0.12.1", + "@stomp/stompjs": "^7.0.0", + "@tanstack/react-table": "^8.20.5", + "class-variance-authority": "^0.7.0", + "clsx": "^2.1.1", + "cmdk": "^1.0.0", + "date-fns": "^4.1.0", + "dotenv": "^16.4.5", + "framer-motion": "^11.9.0", + "js-base64": "^3.7.7", + "js-cookie": "^3.0.5", + "lucide-react": "^0.445.0", + "next": "14.2.11", + "oidc-client-ts": "^3.1.0", + "react": "^18", + "react-chat-elements": "^12.0.16", + "react-dom": "^18", + "react-hook-form": "^7.53.0", + "react-icons": "^5.3.0", + "react-modal": "^3.16.1", + "react-pro-sidebar": "^1.1.0", + "react-resizable-panels": "^2.1.6", + "react-select": "^5.8.2", + "react-spinners": "^0.14.1", + "react-syntax-highlighter": "^15.5.0", + "resize-observer-polyfill": "^1.5.1", + "shiki": "^1.22.2", + "sockjs-client": "^1.6.1", + "sweetalert2": "^11.14.1", + "tailwind-merge": "^2.5.2", + "tailwindcss-animate": "^1.0.7", + "uuid": "^10.0.0", + "y-monaco": "^0.1.6", + "y-webrtc": "^10.3.0", + "yjs": "^13.6.20", + "zod": "^3.23.8" + }, + "devDependencies": { + "@shikijs/monaco": "^1.22.2", + "@types/js-cookie": "^3.0.6", + "@types/node": "^20", + "@types/react": "^18", + "@types/react-dom": "^18", + "@types/react-modal": "^3.16.3", + "@types/react-syntax-highlighter": "^15.5.13", + "@types/sockjs-client": "^1.5.4", + "eslint": "^8", + "eslint-config-next": "14.2.11", + "postcss": "^8", + "tailwindcss": "^3.4.1", + "typescript": "^5" + } +} diff --git a/frontend/postcss.config.mjs b/frontend/postcss.config.mjs new file mode 100644 index 0000000000..1a69fd2a45 --- /dev/null +++ b/frontend/postcss.config.mjs @@ -0,0 +1,8 @@ +/** @type {import('postcss-load-config').Config} */ +const config = { + plugins: { + tailwindcss: {}, + }, +}; + +export default config; diff --git a/frontend/public/blank_profile.webp b/frontend/public/blank_profile.webp new file mode 100644 index 0000000000..f177a45b85 Binary files /dev/null and b/frontend/public/blank_profile.webp differ diff --git a/frontend/public/google_icon.svg b/frontend/public/google_icon.svg new file mode 100644 index 0000000000..6d3c0f9bd5 --- /dev/null +++ b/frontend/public/google_icon.svg @@ -0,0 +1,3 @@ + + + diff --git a/frontend/public/logo_full.svg b/frontend/public/logo_full.svg new file mode 100644 index 0000000000..5953038046 --- /dev/null +++ b/frontend/public/logo_full.svg @@ -0,0 +1,11 @@ + + + + + + + + + + + diff --git a/frontend/public/logo_no_words.svg b/frontend/public/logo_no_words.svg new file mode 100644 index 0000000000..37cf5da209 --- /dev/null +++ b/frontend/public/logo_no_words.svg @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/frontend/public/redo.svg b/frontend/public/redo.svg new file mode 100644 index 0000000000..bca4b7c2b1 --- /dev/null +++ b/frontend/public/redo.svg @@ -0,0 +1,3 @@ + + + diff --git a/frontend/public/undo.svg b/frontend/public/undo.svg new file mode 100644 index 0000000000..6db2bca732 --- /dev/null +++ b/frontend/public/undo.svg @@ -0,0 +1,3 @@ + + + diff --git a/frontend/src/api/chat.ts b/frontend/src/api/chat.ts new file mode 100644 index 0000000000..06bf1052f8 --- /dev/null +++ b/frontend/src/api/chat.ts @@ -0,0 +1,26 @@ +import { COLLABORATION_SERVICE } from "@/api/collaboration"; +import { ChatLog, SingleChatLogApiResponse } from "@/types/chat"; + +interface ChatMetaDataShape { + senderId: string + senderName: string + recipientId: string + recipientName: string +} + + +export const getChatlogs = async (collabid: string, page_num: number, limit: number, chatMetaData: ChatMetaDataShape): Promise => { + const url = `${COLLABORATION_SERVICE}/chat/${collabid}/get_chatlogs?page=${page_num}&limit=${limit}`; + const response = await fetch(url); + const data = await response.json(); + const formattedChatLogs = data.chatLogs.map((chatLog: SingleChatLogApiResponse) => { + return { + text: chatLog.message, + title: chatLog.senderId === chatMetaData.senderId ? chatMetaData.senderName : chatMetaData.recipientName, + date: new Date(chatLog.timestamp), + position: chatLog.senderId === chatMetaData.senderId ? "right" : "left", + type: "text" + }; + }) + return formattedChatLogs; +} diff --git a/frontend/src/api/collaboration.tsx b/frontend/src/api/collaboration.tsx new file mode 100644 index 0000000000..c4c43212f5 --- /dev/null +++ b/frontend/src/api/collaboration.tsx @@ -0,0 +1,114 @@ +import { NewSession, SessionExists, SessionFull } from "@/types/session"; + +export const COLLABORATION_SERVICE = "http://localhost:3001/api/collaboration"; + +export const createSession = async (data: NewSession): Promise => { + const url = `${COLLABORATION_SERVICE}/create`; + const resp = await fetch(url, { + method: "POST", + headers: { + "Content-Type": "application/json", + }, + body: JSON.stringify(data), + }); + + // Check if the response is not OK (e.g., status code 400, 500) + if (!resp.ok) { + throw new Error(`Failed to create the session: ${resp.statusText}`); + } + + // Parse and return the JSON response + const result: SessionFull = await resp.json(); + return result; +}; + +export const fetchSession = async (collabid: string): Promise => { + const url = `${COLLABORATION_SERVICE}/${collabid}`; + const response = await fetch(url); + const data = await response.json(); + return data; +}; + +export const checkSession = async ( + collabid: string +): Promise => { + const url = `${COLLABORATION_SERVICE}/${collabid}/check`; + const response = await fetch(url); + const data = await response.json(); + return data; +}; + +export const checkUserInSession = async ( + collabid: string, + userId: string, + username: string +): Promise => { + const url = `${COLLABORATION_SERVICE}/${collabid}/check/${userId}/${username}`; + const response = await fetch(url); + const data = await response.json(); + return data; +}; + +export const updateSession = async ( + collabid: string, + code: string +): Promise => { + const url = `${COLLABORATION_SERVICE}/${collabid}/update`; + const resp = await fetch(url, { + method: "POST", + headers: { + "Content-Type": "application/json", + }, + body: JSON.stringify({ + collabid: collabid, + code: code, + }), + }); + + if (!resp.ok) { + throw new Error("Failed to update the session"); + } + + return resp.json(); +}; + +export const updateSessionLanguage = async ( + collabid: string, + language: string +): Promise => { + const url = `${COLLABORATION_SERVICE}/${collabid}/updateLanguage`; + const resp = await fetch(url, { + method: "POST", + headers: { + "Content-Type": "application/json", + }, + body: JSON.stringify({ + language: language + }), + }); + + if (!resp.ok) { + throw new Error("Failed to update the session"); + } + + return resp.json(); +}; + +export const deleteSessionById = async ( + collabid: string +): Promise => { + const url = `${COLLABORATION_SERVICE}/${collabid}`; + const resp = await fetch(url, { + method: "DELETE", + headers: { + "Content-Type": "application/json", + }, + }); + + if (!resp.ok) { + const errorData = await resp.json(); + throw new Error(errorData.message || "Failed to delete session"); + } + + return resp.json(); +}; diff --git a/frontend/src/api/dashboard.tsx b/frontend/src/api/dashboard.tsx new file mode 100644 index 0000000000..e58d708ca3 --- /dev/null +++ b/frontend/src/api/dashboard.tsx @@ -0,0 +1,45 @@ +import { TCombinedSession, TQuestion, TSession } from "@/types/dashboard"; + +// retrieve from .env +const COLLAB_SERVICE = "http://localhost:3001/api/collaboration"; +const QUESTION_SERVICE = "http://localhost:3003/api/question"; + +export const getUserHistoryData = async ( + username: string +): Promise => { + const collabUrl = `${COLLAB_SERVICE}/sessions/${username}`; + const response = await fetch(collabUrl, { + method: "POST", + headers: { + "Content-Type": "application/json", + }, + }); + const sessionsData = await response.json(); + const questionIds = sessionsData.map( + (session: TSession) => session.question_id + ); + + const questionUrl = `${QUESTION_SERVICE}/all-ids`; + const questionResponse = await fetch(questionUrl, { + method: "POST", + headers: { + "Content-Type": "application/json", + }, + body: JSON.stringify({ questionIds }), + }); + const questionsData = await questionResponse.json(); + + const combinedData = sessionsData.map((session: TSession) => { + const question = questionsData.find( + (question: TQuestion) => question.questionid === session.question_id + ); + return { + // remove self from users + peer: session.users.filter((user) => user !== username)[0], + ...session, + ...question, + }; + }); + + return combinedData; +}; diff --git a/frontend/src/api/question-dashboard.tsx b/frontend/src/api/question-dashboard.tsx new file mode 100644 index 0000000000..9b827904a7 --- /dev/null +++ b/frontend/src/api/question-dashboard.tsx @@ -0,0 +1,110 @@ +import { QuestionAll, QuestionFull, NewQuestionData } from "@/types/find-match"; + +const QUESTION_SERVICE = "http://localhost:3003/api/question"; + +export const createSingleQuestion = async ( + data: NewQuestionData +): Promise => { + const url = `${QUESTION_SERVICE}/create`; + const resp = await fetch(url, { + method: "POST", + headers: { + "Content-Type": "application/json", + }, + body: JSON.stringify(data), + }); + + // Check if the response is not OK (e.g., status code 400, 500) + if (!resp.ok) { + throw new Error(`Failed to create the question: ${resp.statusText}`); + } + + // Parse and return the JSON response + const result: QuestionFull = await resp.json(); + return result; +}; + +export const getQuestionDashboardData = async ( + pagination: number, + pageSize: number, + title: string, + complexity: string[], + category: string[] +): Promise => { + const url = `${QUESTION_SERVICE}/all`; + const response = await fetch(url, { + method: "POST", + headers: { + "Content-Type": "application/json", + }, + body: JSON.stringify({ + pagination: pagination, + pageSize: pageSize, + title: title, + complexity: complexity, + category: category, + }), + }); + const data = await response.json(); + return data; +}; + +export const fetchSingleQuestion = async ( + questionId: string +): Promise => { + const url = `${QUESTION_SERVICE}/${questionId}`; + const response = await fetch(url); + const data = await response.json(); + return data; +}; + +export const updateSingleQuestion = async ({ + questionId, + title, + description, + category, + complexity, + examples, + solution, +}: QuestionFull) => { + const url = `${QUESTION_SERVICE}/${questionId}/update`; + const resp = await fetch(url, { + method: "POST", + headers: { + "Content-Type": "application/json", + }, + body: JSON.stringify({ + title: title, + description: description, + category: category, + complexity: complexity, + examples: examples, + solution: solution, + }), + }); + + if (!resp.ok) { + throw new Error("Failed to update the question"); + } + + return resp.json(); +}; + +export const deleteSingleQuestion = async (questionId: string) => { + const url = `${QUESTION_SERVICE}/${questionId}/delete`; + const resp = await fetch(url, { + method: "POST", + headers: { + "Content-Type": "application/json", + }, + body: JSON.stringify({ + questionId: questionId, + }), + }); + + if (!resp.ok) { + throw new Error("Failed to update the question"); + } + + return await resp.json(); +}; diff --git a/frontend/src/api/user.tsx b/frontend/src/api/user.tsx new file mode 100644 index 0000000000..00407dc16f --- /dev/null +++ b/frontend/src/api/user.tsx @@ -0,0 +1,361 @@ +/* eslint-disable */ + +import { AuthStatus, UploadProfilePictureResponse } from "@/types/user"; +import Cookie from "js-cookie"; +import Swal from "sweetalert2"; + +export const ToastComponent = Swal.mixin({ + toast: true, + position: "top-end", + showConfirmButton: false, + timer: 3000, + timerProgressBar: true, + didOpen: (toast) => { + toast.onmouseenter = Swal.stopTimer; + toast.onmouseleave = Swal.resumeTimer; + }, +}); + +export const setToken = (token: string) => { + Cookie.set("token", token, { expires: 1 }); +}; + +export const getToken = () => { + return Cookie.get("token"); +}; + +export const setUsername = (username: string) => { + Cookie.set("username", username, { expires: 1 }); +}; + +export const getUsername = () => { + return Cookie.get("username"); +}; + +export const setUserId = (id: string) => { + Cookie.set("id", id, { expires: 1 }); +}; + +export const getUserId = () => { + return Cookie.get("id"); +}; + +export const setIsAdmin = (isAdmin: boolean) => { + Cookie.set("isAdmin", isAdmin ? "Y" : "N", { expires: 1 }); +}; + +export const getIsAdmin = (): boolean => { + return Cookie.get("isAdmin") == "Y"; +}; + +export const getAuthStatus = () => { + if (!getToken()) return AuthStatus.UNAUTHENTICATED; + if (getIsAdmin()) return AuthStatus.ADMIN; + return AuthStatus.AUTHENTICATED; +}; + +const NEXT_PUBLIC_IAM_USER_SERVICE = process.env.NEXT_PUBLIC_IAM_USER_SERVICE; + +const NEXT_PUBLIC_IAM_AUTH_SERVICE = process.env.NEXT_PUBLIC_IAM_AUTH_SERVICE; + +export const verifyToken = async (token: string) => { + try { + const response = await fetch( + `${NEXT_PUBLIC_IAM_AUTH_SERVICE}/verify-token`, + { + method: "GET", + headers: { + Authorization: `Bearer ${token}`, + }, + } + ); + if (response.status !== 200) { + Cookie.remove("token"); + Cookie.remove("username"); + Cookie.remove("id"); + Cookie.remove("isAdmin"); + return false; + } + + const data = await response.json(); + setUsername(data.data.username); + setIsAdmin(data.data.isAdmin); + setUserId(data.data.id); + return response.status === 200; + } catch (e) { + console.error(e); + } +}; + +export const login = async (email: string, password: string) => { + ToastComponent.fire({ + icon: "info", + title: "Logging in...", + }); + const response = await fetch(`${NEXT_PUBLIC_IAM_AUTH_SERVICE}/login`, { + method: "POST", + headers: { + "Content-Type": "application/json", + }, + body: JSON.stringify({ + email, + password, + }), + }); + const data = await response.json(); + + if (response.status !== 200) { + ToastComponent.fire({ + icon: "error", + title: data.message, + }); + return false; + } + + setToken(data.data.accessToken); + setUsername(data.data.username); + setIsAdmin(data.data.isAdmin); + setUserId(data.data.id); + + return true; +}; + +export const logout = () => { + Cookie.remove("token"); + Cookie.remove("username"); + Cookie.remove("id"); + Cookie.remove("isAdmin"); + + window.location.href = "/"; +}; + +export const register = async ( + email: string, + password: string, + username: string +) => { + ToastComponent.fire({ + icon: "info", + title: "Registering...", + }); + const response = await fetch(`${NEXT_PUBLIC_IAM_USER_SERVICE}`, { + method: "POST", + headers: { + "Content-Type": "application/json", + }, + body: JSON.stringify({ + email, + password: password, + username, + }), + }); + const data = await response.json(); + + if (response.status !== 201) { + ToastComponent.fire({ + icon: "error", + title: data.message, + }); + return false; + } + + return true; +}; + +// optional userId parameter +export const getUser = async (userId = "") => { + const token = getToken(); + const url = `${NEXT_PUBLIC_IAM_USER_SERVICE}/${userId || getUserId()}`; + const response = await fetch(url, { + method: "GET", + headers: { + Authorization: `Bearer ${token}`, + }, + }); + const data = await response.json(); + + if (response.status !== 200) { + ToastComponent.fire({ + icon: "error", + title: data.message, + }); + return false; + } + + return data; +}; + +export const resetPasswordFromProfile = async (newPassword: string) => { + const userId = getUserId(); + const token = getToken(); + const url = `${NEXT_PUBLIC_IAM_USER_SERVICE}/${userId}/reset-password-from-profile`; + const response = await fetch(url, { + method: "POST", + headers: { + "Content-Type": "application/json", + Authorization: `Bearer ${token}`, + }, + body: JSON.stringify({ password: newPassword }), + }); + + const data = await response.json(); + if (response.status === 400) { + ToastComponent.fire({ + icon: "error", + title: data.message, + }); + return false; + } else if (response.status === 200) { + ToastComponent.fire({ + icon: "success", + title: data.message, + }); + return true; + } +}; + +export const updateUser = async (userData: { + username?: string; + email?: string; + bio?: string; + linkedin?: string; + github?: string; + profilePictureUrl?: string; +}) => { + const token = getToken(); + const userId = getUserId(); + const response = await fetch(`${NEXT_PUBLIC_IAM_USER_SERVICE}/${userId}`, { + method: "PATCH", + headers: { + "Content-Type": "application/json", + Authorization: `Bearer ${token}`, + }, + body: JSON.stringify(userData), + }); + const data = await response.json(); + console.log(data); + + if (response.status !== 200) { + ToastComponent.fire({ + icon: "error", + title: data.message, + }); + return false; + } + + ToastComponent.fire({ + icon: "success", + title: "Profile updated successfully", + }); + + return true; +}; + +export const getFileUrl = async ( + userId: string, + formData: FormData +): Promise => { + const res = await fetch( + `${NEXT_PUBLIC_IAM_USER_SERVICE}/${userId}/getFileUrl`, + { + method: "POST", + headers: { + Authorization: `Bearer ${getToken()}`, + }, + body: formData, + } + ); + + const data: UploadProfilePictureResponse = await res.json(); + + if (res.status !== 200) { + ToastComponent.fire({ + icon: "error", + title: res.statusText, + }); + throw new Error("Failed to upload profile picture: " + res.statusText); + } + return data; +}; + +export const requestPasswordReset = async (email: string) => { + ToastComponent.fire({ + icon: "info", + title: "Requesting password reset...", + }); + const response = await fetch( + `${NEXT_PUBLIC_IAM_USER_SERVICE}/request-password-reset`, + { + method: "POST", + headers: { + "Content-Type": "application/json", + }, + body: JSON.stringify({ email }), + } + ); + const data = await response.json(); + console.log(data); + + if (response.status !== 200) { + ToastComponent.fire({ + icon: "error", + title: data.message, + }); + return false; + } + + ToastComponent.fire({ + icon: "success", + title: "Password reset requested. Please check your email.", + }); + + return true; +}; + +export const checkPasswordResetCode = async (code: string) => { + const response = await fetch( + `${NEXT_PUBLIC_IAM_USER_SERVICE}/check-password-reset-code`, + { + method: "POST", + headers: { + "Content-Type": "application/json", + }, + body: JSON.stringify({ code }), + } + ); + const data = await response.json(); + + if (response.status !== 200) { + ToastComponent.fire({ + icon: "error", + title: data.message, + }); + return false; + } + + return { username: data.username }; +}; + +export const resetPasswordWithCode = async (code: string, password: string) => { + const response = await fetch( + `${NEXT_PUBLIC_IAM_USER_SERVICE}/password-reset`, + { + method: "POST", + headers: { + "Content-Type": "application/json", + }, + body: JSON.stringify({ code, password }), + } + ); + const data = await response.json(); + + if (response.status !== 200) { + ToastComponent.fire({ + icon: "error", + title: data.message, + }); + return false; + } + + return true; +}; diff --git a/frontend/src/app/(errors)/403/layout.tsx b/frontend/src/app/(errors)/403/layout.tsx new file mode 100644 index 0000000000..33ba319f6f --- /dev/null +++ b/frontend/src/app/(errors)/403/layout.tsx @@ -0,0 +1,3 @@ +import Layout from "../../common/Layout"; + +export default Layout; \ No newline at end of file diff --git a/frontend/src/app/(errors)/403/page.tsx b/frontend/src/app/(errors)/403/page.tsx new file mode 100644 index 0000000000..0f21de1cc9 --- /dev/null +++ b/frontend/src/app/(errors)/403/page.tsx @@ -0,0 +1,13 @@ +import Link from 'next/link' + +const Error403Page = () => { + return
+
+

Oops! 403 Forbidden!

+

You are not allowed to access this page.

+ Go back to Home +
+
+} + +export default Error403Page \ No newline at end of file diff --git a/frontend/src/app/(home)/about/components/Profile.tsx b/frontend/src/app/(home)/about/components/Profile.tsx new file mode 100644 index 0000000000..ec4364490f --- /dev/null +++ b/frontend/src/app/(home)/about/components/Profile.tsx @@ -0,0 +1,24 @@ +import Link from "next/link"; +import { FaLinkedin } from "react-icons/fa"; +import { FaGithub } from "react-icons/fa"; + +const ProfileItem = ({ name, img, linkedin, github }: { name: string, img: string, linkedin: string, github: string }) => { + return ( +
+

{name}

+ +
+
+ + + + + + +
+
+
+ ); +} + +export default ProfileItem; \ No newline at end of file diff --git a/frontend/src/app/(home)/about/layout.tsx b/frontend/src/app/(home)/about/layout.tsx new file mode 100644 index 0000000000..37412bb8ae --- /dev/null +++ b/frontend/src/app/(home)/about/layout.tsx @@ -0,0 +1,3 @@ +import Layout from "@/app/common/Layout"; + +export default Layout; \ No newline at end of file diff --git a/frontend/src/app/(home)/about/page.tsx b/frontend/src/app/(home)/about/page.tsx new file mode 100644 index 0000000000..3e070a6030 --- /dev/null +++ b/frontend/src/app/(home)/about/page.tsx @@ -0,0 +1,51 @@ +import ProfileItem from "./components/Profile"; + +const profiles = [ + { + name: "Mai Ting Kai", + img: "https://media.licdn.com/dms/image/v2/C5603AQFTOIBiZRDubQ/profile-displayphoto-shrink_200_200/profile-displayphoto-shrink_200_200/0/1659868517766?e=1736380800&v=beta&t=6uCl7A2pfEWbJvB5E8LspGKd9ndjjBeJBC8ZtmkW5Oo", + linkedin: "https://www.linkedin.com/in/mai-ting-kai/", + github: "https://github.com/tingkai-mai" + }, + { + name: "Soh Je Hou", + img: "https://media.licdn.com/dms/image/v2/D5603AQEyvoPMbsO4ZQ/profile-displayphoto-shrink_200_200/profile-displayphoto-shrink_200_200/0/1697231833209?e=1736380800&v=beta&t=hcXSW4YxkNhhPpt-58K_Ksw9QvJLQ80Mj-oStnsKRgk", + linkedin: "https://www.linkedin.com/in/jehousoh/", + github: "https://github.com/jehousoh" + }, + { + name: "Chrysline Lim Xing Hui", + img: "https://media.licdn.com/dms/image/v2/D5603AQFFhrXlN0rxPA/profile-displayphoto-shrink_200_200/profile-displayphoto-shrink_200_200/0/1679269861667?e=1736380800&v=beta&t=rVfJih_Z1j80KoCuRwPvF5fEJm0waFTIiOI-MyeYyqU", + linkedin: "https://www.linkedin.com/in/chrysline-lim-91320323a/", + github: "https://github.com/ChryslineLim" + }, + { + name: "Jamie Toh Hui Lin", + img: "https://media.licdn.com/dms/image/v2/C5603AQFqh_7ytNhdgg/profile-displayphoto-shrink_200_200/profile-displayphoto-shrink_200_200/0/1619188035985?e=1736380800&v=beta&t=_e92yUQXil7ImjZuuO0fNEzzutb_5CBfMxzxM6I0cWU", + linkedin: "https://www.linkedin.com/in/jamie-toh-892305186/", + github: "https://github.com/jamz903" + }, + { + name: "Izz Hafeez Bin Zek Hazley", + img: "https://media.licdn.com/dms/image/v2/C4D03AQGqEGA0k1xRaw/profile-displayphoto-shrink_200_200/profile-displayphoto-shrink_200_200/0/1590071844974?e=1736380800&v=beta&t=whOuHWXjV-vE9muz0KYiurnytAVoHpsiBIj-X9xDgTs", + linkedin: "https://www.linkedin.com/in/izzhafeez/", + github: "https://github.com/izzhafeez" + }, +] + +const AboutPage = () => { + return ( +
+
+

About Us

+
+ {profiles.map((profile, index) => ( + + ))} +
+
+
+ ); +} + +export default AboutPage; \ No newline at end of file diff --git a/frontend/src/app/(home)/components/code-snippet/CodeSnippetHighlight.tsx b/frontend/src/app/(home)/components/code-snippet/CodeSnippetHighlight.tsx new file mode 100644 index 0000000000..0fb3b58f21 --- /dev/null +++ b/frontend/src/app/(home)/components/code-snippet/CodeSnippetHighlight.tsx @@ -0,0 +1,63 @@ +"use client"; + +import { Prism as SyntaxHighlighter } from "react-syntax-highlighter"; +import { darcula } from "react-syntax-highlighter/dist/esm/styles/prism"; +import { useEffect, useState, useRef } from "react"; + +const CodeSnippetHighlight = () => { + const code = ` +class Solution: + def twoSum(self, nums: List[int], target: int) -> List[int]: + idxDict = {} + for i, num in enumerate(nums): + idxDict[num] = i + + for i, num in enumerate(nums): + diff = target - num + if diff in idxDict and i != idxDict[diff]: + return [i, idxDict[diff]] + + `; + + const [displayedText, setDisplayedText] = useState(""); // Store the currently displayed text + const currentCharIndexRef = useRef(0); // Track the current character index + const typingInterval = 30; // Milliseconds between each character + + useEffect(() => { + const intervalId = setInterval(() => { + if (currentCharIndexRef.current < code.length) { + // Append the next character if it exists + const nextChar = code[currentCharIndexRef.current]; + if (nextChar !== undefined) { + setDisplayedText((prevText) => prevText + nextChar); + currentCharIndexRef.current += 1; + } + } else { + // Stop the interval once all characters are displayed + clearInterval(intervalId); + } + }, typingInterval); + + return () => clearInterval(intervalId); // Cleanup on unmount + }, []); + + return ( + + {displayedText} + + + ); +}; + +export default CodeSnippetHighlight; diff --git a/frontend/src/app/(home)/components/icon/GoogleIcon.tsx b/frontend/src/app/(home)/components/icon/GoogleIcon.tsx new file mode 100644 index 0000000000..2b2508f363 --- /dev/null +++ b/frontend/src/app/(home)/components/icon/GoogleIcon.tsx @@ -0,0 +1,20 @@ +import Image from "next/image"; +import Link from "next/link"; + +const GoogleIcon = () => { + const iconSize = 24; + return ( +
+ + Google Icon + +
+ ); +}; + +export default GoogleIcon; diff --git a/frontend/src/app/(home)/components/landing-page/LandingPage.tsx b/frontend/src/app/(home)/components/landing-page/LandingPage.tsx new file mode 100644 index 0000000000..95095a5456 --- /dev/null +++ b/frontend/src/app/(home)/components/landing-page/LandingPage.tsx @@ -0,0 +1,61 @@ +import CodeSnippet from "@/app/(home)/components/code-snippet/CodeSnippetHighlight"; +import { Button } from "@/components/ui/button"; +import { useRouter } from "next/navigation"; +import Navbar from "@/app/common/Navbar"; +import { getAuthStatus } from "@/api/user"; +import { AuthStatus } from "@/types/user"; +import { useEffect, useState } from "react"; + +const LandingPage = () => { + const router = useRouter(); + const [authStatus, setAuthStatus] = useState( + AuthStatus.UNAUTHENTICATED + ); + + useEffect(() => { + setAuthStatus(getAuthStatus()); + }, []); + + const handleRedirect = () => { + if (authStatus === AuthStatus.UNAUTHENTICATED) { + router.push("/login"); + } else { + router.push("/dashboard"); + } + }; + + return ( +
+ +
+
+

+ Collaborative Coding,

Competitive Results. +

+

+ Join PeerPrep to sharpen your skills through real-time + problem-solving, and prepare to outshine in every interview. Created + for CS3219 Software Engineering Principles AY24/25 by Group 15. +

+
+ +
+
+
+ +
+
+
+ ); +}; + +export default LandingPage; diff --git a/frontend/src/app/(user)/dashboard/components/Dashboard.tsx b/frontend/src/app/(user)/dashboard/components/Dashboard.tsx new file mode 100644 index 0000000000..7a04c3a211 --- /dev/null +++ b/frontend/src/app/(user)/dashboard/components/Dashboard.tsx @@ -0,0 +1,61 @@ +/* eslint-disable react/no-unescaped-entities */ +"use client"; + +import { getUserHistoryData } from "@/api/dashboard"; +import { getUserId, getUsername } from "@/api/user"; +import Container from "@/components/ui/Container"; +import { TCombinedSession } from "@/types/dashboard"; +import { useEffect, useState } from "react"; +import DashboardCard from "@/app/(user)/dashboard/components/DashboardCard"; +import { DashboardDataTable } from "@/app/(user)/dashboard/components/DashboardDataTable"; + +const Dashboard = () => { + const [username, setUsername] = useState(null); + const [data, setData] = useState([]); + + useEffect(() => { + const username = getUsername(); + const userId = getUserId(); + if (!username) return; + if (!userId) return; + setUsername(username); + getUserHistoryData(userId).then((userHistory) => { + setData(userHistory); + }); + }, []); + + return ( + +
+ + {username}'s Dashboard + +
+ + Checkout your past interview sessions and questions attempted! + +
+
+
+ question.complexity == "Easy").length + }`, + `${ + data.filter((question) => question.complexity == "Medium").length + }`, + `${ + data.filter((question) => question.complexity == "Hard").length + }`, + ]} + cardFooterLabels={["Easy", "Medium", "Hard"]} + /> +
+ +
+ ); +}; + +export default Dashboard; diff --git a/frontend/src/app/(user)/dashboard/components/DashboardCard.tsx b/frontend/src/app/(user)/dashboard/components/DashboardCard.tsx new file mode 100644 index 0000000000..038526c953 --- /dev/null +++ b/frontend/src/app/(user)/dashboard/components/DashboardCard.tsx @@ -0,0 +1,40 @@ +import { + Card, + CardHeader, + CardTitle, +} from "@/components/ui/card"; + +import DashboardCardItem from './DashboardCardItem'; + +interface DashboardCardProps { + cardTitleLabel: string; + cardBodyLabels: string[]; + cardFooterLabels: string[]; +} + +const DashboardCard = ({ + cardTitleLabel, + cardBodyLabels, + cardFooterLabels, +}: DashboardCardProps) => { + return ( + + + + {cardTitleLabel} + + +
+ {cardBodyLabels.map((bodyLabel: string, index) => ( + + ))} +
+
+ ); +}; + +export default DashboardCard; diff --git a/frontend/src/app/(user)/dashboard/components/DashboardCardItem.tsx b/frontend/src/app/(user)/dashboard/components/DashboardCardItem.tsx new file mode 100644 index 0000000000..9e230f4042 --- /dev/null +++ b/frontend/src/app/(user)/dashboard/components/DashboardCardItem.tsx @@ -0,0 +1,22 @@ +import React from 'react'; +import { Card, CardContent, CardFooter } from "@/components/ui/card"; + +interface DashboardCardItemProps { + cardBodyLabel: string; + cardFooterLabel: string; +} + +const DashboardCardItem: React.FC = ({ cardBodyLabel, cardFooterLabel }) => { + return ( + + +

{cardBodyLabel}

+
+ + {cardFooterLabel} + +
+ ); +}; + +export default DashboardCardItem; \ No newline at end of file diff --git a/frontend/src/app/(user)/dashboard/components/DashboardDataTable.tsx b/frontend/src/app/(user)/dashboard/components/DashboardDataTable.tsx new file mode 100644 index 0000000000..dde49faeb9 --- /dev/null +++ b/frontend/src/app/(user)/dashboard/components/DashboardDataTable.tsx @@ -0,0 +1,247 @@ +"use client"; + +import * as React from "react"; +import { + ColumnDef, + flexRender, + getCoreRowModel, + getPaginationRowModel, + PaginationState, + useReactTable, +} from "@tanstack/react-table"; + +import { format } from "date-fns"; + +import { Button } from "@/components/ui/button"; +import { + Table, + TableBody, + TableCell, + TableHead, + TableHeader, + TableRow, +} from "@/components/ui/table"; +import { TCombinedSession } from "@/types/dashboard"; +import { cn } from "@/lib/utils"; +import { FaExternalLinkAlt } from "react-icons/fa"; +import Link from "next/link"; +import { getUser } from "@/api/user"; +import VerificationSymbol from "@/app/common/VerificationSymbol"; + +const Cell = ({ + className, + children, + tooltipText, +}: { + className?: string; + children: React.ReactNode; + tooltipText?: string; +}) => { + return ( +
+ {children} +
+ ); +}; + +export const columns: ColumnDef[] = [ + { + accessorKey: "peer", + header: () => Peer, + cell: async ({ row }) => { + const peer: string = row.getValue("peer"); + const peerData = await getUser(peer); + + return ( + + + {peerData.data.username as string} + + + + ); + }, + }, + { + accessorKey: "title", + header: () => Question Name, + cell: ({ row }) => { + const title: string = row.getValue("title"); + + return {title}; + }, + }, + { + accessorKey: "language", + header: () => Matched Language, + cell: ({ row }) => { + const language = row.getValue("language") as string; + const languageFormatted = + language.charAt(0).toUpperCase() + language.slice(1); + return {languageFormatted}; + }, + }, + { + accessorKey: "complexity", + header: () => Complexity, + cell: ({ row }) => { + const complexity: string = row.getValue("complexity"); + return {complexity}; + }, + }, + { + accessorKey: "category", + header: () => Category, + cell: ({ row }) => { + const categories: string[] = row.getValue("category"); + const combinedCategories: string = categories.join(", "); + return ( + + {categories.slice(0, 3).join(", ")} + {categories.length > 3 ? "..." : ""} + + ); + }, + }, + { + accessorKey: "createdAt", + header: () => Date, + cell: ({ row }) => { + const date: Date = row.getValue("createdAt"); + + return ( + + {format(date, "dd-MM-yyyy HH:mm:ss")} + + ); + }, + }, + { + accessorKey: "collabid", + header: () => Collab Space, + cell: ({ row }) => { + return ( + + + + + + ); + }, + }, +]; + +export function DashboardDataTable({ data }: { data: TCombinedSession[] }) { + const [pagination, setPagination] = React.useState({ + pageIndex: 0, + pageSize: 10, + }); + + const table = useReactTable({ + data, + columns, + getCoreRowModel: getCoreRowModel(), + getPaginationRowModel: getPaginationRowModel(), + state: { + pagination, + }, + onPaginationChange: setPagination, + }); + + return ( +
+
+ + + + + Past Collaborations + + + {table.getHeaderGroups().map((headerGroup) => ( + + {headerGroup.headers.map((header) => { + return ( + + {header.isPlaceholder + ? null + : flexRender( + header.column.columnDef.header, + header.getContext() + )} + + ); + })} + + ))} + + + {table.getRowModel().rows?.length ? ( + table.getRowModel().rows.map((row) => ( + + {row.getVisibleCells().map((cell) => ( + + {flexRender( + cell.column.columnDef.cell, + cell.getContext() + )} + + ))} + + )) + ) : ( + + + No results. + + + )} + +
+
+
+
+ +
+ Page{" "} + {table.getPageCount() == 0 + ? 0 + : table.getState().pagination.pageIndex + 1} + /{table.getPageCount()} +
+ +
+
+
+ ); +} diff --git a/frontend/src/app/(user)/dashboard/layout.tsx b/frontend/src/app/(user)/dashboard/layout.tsx new file mode 100644 index 0000000000..33ba319f6f --- /dev/null +++ b/frontend/src/app/(user)/dashboard/layout.tsx @@ -0,0 +1,3 @@ +import Layout from "../../common/Layout"; + +export default Layout; \ No newline at end of file diff --git a/frontend/src/app/(user)/dashboard/page.tsx b/frontend/src/app/(user)/dashboard/page.tsx new file mode 100644 index 0000000000..b6d4a7e6fb --- /dev/null +++ b/frontend/src/app/(user)/dashboard/page.tsx @@ -0,0 +1,7 @@ +import Dashboard from "@/app/(user)/dashboard/components/Dashboard" + +const DashboardPage = () => { + return ; +} + +export default DashboardPage; \ No newline at end of file diff --git a/frontend/src/app/(user)/forgot-password/components/ForgotPassword.tsx b/frontend/src/app/(user)/forgot-password/components/ForgotPassword.tsx new file mode 100644 index 0000000000..49332e87ae --- /dev/null +++ b/frontend/src/app/(user)/forgot-password/components/ForgotPassword.tsx @@ -0,0 +1,60 @@ +"use client"; + +import { requestPasswordReset } from "@/api/user"; +import { Button } from "@/components/ui/button"; +import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from "@/components/ui/form"; +import { Input } from "@/components/ui/input"; +import { zodResolver } from "@hookform/resolvers/zod"; +import { useForm } from "react-hook-form"; +import { z } from "zod"; +import Navbar from "@/app/common/Navbar"; + +const formSchema = z.object({ + email: z.string(), +}); + +const Login = () => { + const form = useForm>({ + resolver: zodResolver(formSchema), + defaultValues: { + email: "", + }, + }); + + const onSubmit = async (data: z.infer) => { + await requestPasswordReset(data.email); + }; + + return ( + <> + +
+

Forgot Your Password?

+

+ Enter your email address and we will send you a link to reset your password. +

+
+ + ( + + EMAIL + + + + {/* This is your public display name. */} + + + )} + /> + + + +
+ + ); +}; + +export default Login; \ No newline at end of file diff --git a/frontend/src/app/(user)/forgot-password/layout.tsx b/frontend/src/app/(user)/forgot-password/layout.tsx new file mode 100644 index 0000000000..33ba319f6f --- /dev/null +++ b/frontend/src/app/(user)/forgot-password/layout.tsx @@ -0,0 +1,3 @@ +import Layout from "../../common/Layout"; + +export default Layout; \ No newline at end of file diff --git a/frontend/src/app/(user)/forgot-password/page.tsx b/frontend/src/app/(user)/forgot-password/page.tsx new file mode 100644 index 0000000000..a6fa513fce --- /dev/null +++ b/frontend/src/app/(user)/forgot-password/page.tsx @@ -0,0 +1,9 @@ +import ForgotPassword from "./components/ForgotPassword"; + +const ForgotPasswordPage = () => { + return ( + + ); +} + +export default ForgotPasswordPage; \ No newline at end of file diff --git a/frontend/src/app/(user)/login/components/Login.tsx b/frontend/src/app/(user)/login/components/Login.tsx new file mode 100644 index 0000000000..320b094d91 --- /dev/null +++ b/frontend/src/app/(user)/login/components/Login.tsx @@ -0,0 +1,93 @@ +"use client"; + +import { login } from "@/api/user"; +import { Button } from "@/components/ui/button"; +import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from "@/components/ui/form"; +import { Input } from "@/components/ui/input"; +import { zodResolver } from "@hookform/resolvers/zod"; +import { useForm } from "react-hook-form"; +import { z } from "zod"; +import Navbar from "@/app/common/Navbar"; +import { useRouter, useSearchParams } from "next/navigation"; + +const formSchema = z.object({ + email: z.string(), + password: z.string(), +}); + +const Login = () => { + const router = useRouter(); + const searchParams = useSearchParams(); + const form = useForm>({ + resolver: zodResolver(formSchema), + defaultValues: { + email: "", + password: "", + }, + }); + + const onSubmit = async (data: z.infer) => { + const loginIsSuccessful = await login(data.email, data.password); + if (!loginIsSuccessful) { + return; + } + + if (!searchParams) return; + // route based on search params retrieved using router + const redirectUrl = searchParams.get("redirect") || "/dashboard"; + + // route the user to the redirect URL + router.push(redirectUrl as string); + }; + + return ( + <> + +
+

Login

+

+ Login to our platform to access its features! Don't have an account? Register here! +

+
+ + ( + + EMAIL + + + + {/* This is your public display name. */} + + + )} + /> + ( + + PASSWORD + + + + {/* This is your public display name. */} + + + )} + /> + + + + {/* forgot password? */} +

+ Forgot your password? Click here! +

+
+ + ); +}; + +export default Login; \ No newline at end of file diff --git a/frontend/src/app/(user)/login/layout.tsx b/frontend/src/app/(user)/login/layout.tsx new file mode 100644 index 0000000000..33ba319f6f --- /dev/null +++ b/frontend/src/app/(user)/login/layout.tsx @@ -0,0 +1,3 @@ +import Layout from "../../common/Layout"; + +export default Layout; \ No newline at end of file diff --git a/frontend/src/app/(user)/login/page.tsx b/frontend/src/app/(user)/login/page.tsx new file mode 100644 index 0000000000..1a6f463cfa --- /dev/null +++ b/frontend/src/app/(user)/login/page.tsx @@ -0,0 +1,10 @@ +import React from 'react'; +import Login from "@/app/(user)/login/components/Login"; + +const LoginPage = () => { + return ( + + ); +}; + +export default LoginPage; \ No newline at end of file diff --git a/frontend/src/app/(user)/register/components/Register.tsx b/frontend/src/app/(user)/register/components/Register.tsx new file mode 100644 index 0000000000..d22d521dd6 --- /dev/null +++ b/frontend/src/app/(user)/register/components/Register.tsx @@ -0,0 +1,170 @@ +"use client"; + +import { register } from "@/api/user"; +import { Button } from "@/components/ui/button"; +import { + Form, + FormControl, + FormField, + FormItem, + FormLabel, + FormMessage, +} from "@/components/ui/form"; +import { Input } from "@/components/ui/input"; +import { zodResolver } from "@hookform/resolvers/zod"; +import { useForm } from "react-hook-form"; +import { z } from "zod"; +import Navbar from "@/app/common/Navbar"; +import Swal from "sweetalert2"; +import { useRouter } from "next/navigation"; +import { useEffect, useState } from "react"; + +const formSchema = z.object({ + username: z + .string() + .min(5, "Username must be at least 5 characters") + .max(20, "Username must be at most 20 characters"), + email: z.string().email("Invalid email"), + password: z + .string() + .min(8, "Password must be at least 8 characters") + .max(100, "Password must be at most 100 characters") + .regex(/[a-z]/, "Password must contain at least one lowercase letter") + .regex(/[A-Z]/, "Password must contain at least one uppercase letter") + .regex(/\d/, "Password must contain at least one number") + .regex( + /[@$!%*?&]/, + "Password must contain at least one special character (@, $, !, %, *, ?, &)" + ), +}); + +const Register = () => { + const router = useRouter(); + const [mounted, setMounted] = useState(false); + + useEffect(() => { + setMounted(true); + }, []); + + const form = useForm>({ + resolver: zodResolver(formSchema), + defaultValues: { + username: "", + email: "", + password: "", + }, + }); + + const onSubmit = async (data: z.infer) => { + const registerIsSuccessful = await register( + data.email, + data.password, + data.username + ); + if (!registerIsSuccessful) return; + + // redirect to /login + Swal.fire({ + title: "Account created!", + text: "You can now login to your account.", + icon: "success", + confirmButtonText: "Login", + }).then(() => { + if (!mounted) return; + router.push("/login"); + }); + }; + + if (!mounted) return null; + + return ( + <> + +
+

Register

+

+ Register to our platform to access its features! Have an account?{" "} + + Login here! + +

+
+ + ( + + + USERNAME + + + + + {/* This is your public display name. */} + + + )} + /> + ( + + + EMAIL + + + + + {/* This is your public display name. */} + + + )} + /> + ( + + + PASSWORD + + + + + {/* This is your public display name. */} + + + )} + /> + + + +
+ + ); +}; + +export default Register; diff --git a/frontend/src/app/(user)/register/layout.tsx b/frontend/src/app/(user)/register/layout.tsx new file mode 100644 index 0000000000..33ba319f6f --- /dev/null +++ b/frontend/src/app/(user)/register/layout.tsx @@ -0,0 +1,3 @@ +import Layout from "../../common/Layout"; + +export default Layout; \ No newline at end of file diff --git a/frontend/src/app/(user)/register/page.tsx b/frontend/src/app/(user)/register/page.tsx new file mode 100644 index 0000000000..39f391d7f7 --- /dev/null +++ b/frontend/src/app/(user)/register/page.tsx @@ -0,0 +1,7 @@ +import Register from "@/app/(user)/register/components/Register"; + +const RegisterPage = () => { + return ; +}; + +export default RegisterPage; \ No newline at end of file diff --git a/frontend/src/app/(user)/reset-password/components/ResetPassword.tsx b/frontend/src/app/(user)/reset-password/components/ResetPassword.tsx new file mode 100644 index 0000000000..e5ec564c79 --- /dev/null +++ b/frontend/src/app/(user)/reset-password/components/ResetPassword.tsx @@ -0,0 +1,150 @@ +"use client"; + +import { checkPasswordResetCode, resetPasswordWithCode } from "@/api/user"; +import LoadingPage from "@/app/common/LoadingPage"; +import Navbar from "@/app/common/Navbar"; +import { Button } from "@/components/ui/button"; +import { + Form, + FormControl, + FormField, + FormItem, + FormLabel, + FormMessage, +} from "@/components/ui/form"; +import { Input } from "@/components/ui/input"; +import { zodResolver } from "@hookform/resolvers/zod"; +import { useSearchParams } from "next/navigation"; +import { useEffect, useState } from "react"; +import { useForm } from "react-hook-form"; +import { z } from "zod"; + +const formSchema = z.object({ + password: z + .string() + .min(8, "Password must be at least 8 characters") + .max(100, "Password must be at most 100 characters") + .regex(/[a-z]/, "Password must contain at least one lowercase letter") + .regex(/[A-Z]/, "Password must contain at least one uppercase letter") + .regex(/\d/, "Password must contain at least one number") + .regex( + /[@$!%*?&]/, + "Password must contain at least one special character (@, $, !, %, *, ?, &)" + ), +}); + +const ResetPassword = () => { + const form = useForm>({ + resolver: zodResolver(formSchema), + defaultValues: { + password: "", + }, + }); + + const searchParams = useSearchParams(); + const [isValidCode, setIsValidCode] = useState(false); + const [isInvalidCode, setIsInvalidCode] = useState(false); + const [username, setUsername] = useState(""); + const [changeIsSuccessful, setChangeIsSuccessful] = useState(false); + + useEffect(() => { + if (!searchParams) return; + const code = searchParams.get("code"); + if (!code) return; + // check if the code is valid + checkPasswordResetCode(code).then((data) => { + if (!data) { + setIsInvalidCode(true); + return; + } + setIsValidCode(true); + setUsername(data.username); + }); + }, [searchParams]); + + const onSubmit = async (data: z.infer) => { + if (!searchParams) return; + const code = searchParams.get("code"); + if (!code) return; + // reset the password + resetPasswordWithCode(code, data.password).then((data) => { + if (!data) return; + setChangeIsSuccessful(true); + }); + }; + + return ( + <> + + {!isValidCode && !isInvalidCode && } + {isValidCode && !changeIsSuccessful && ( +
+

Reset Password

+

+ Welcome, {username}! Please enter your new password. +

+
+ + ( + + + PASSWORD + + + + + {/* This is your public display name. */} + + + )} + /> + + + +
+ )} + {isInvalidCode && ( +
+

Invalid Code

+

+ The code you entered is invalid. Please check your email for the + correct code. +

+
+ )} + {changeIsSuccessful && ( +
+

+ Password Changed +

+

+ Your password has been changed successfully. You can now{" "} + + login + {" "} + with your new password. +

+
+ )} + + ); +}; + +export default ResetPassword; diff --git a/frontend/src/app/(user)/reset-password/layout.tsx b/frontend/src/app/(user)/reset-password/layout.tsx new file mode 100644 index 0000000000..33ba319f6f --- /dev/null +++ b/frontend/src/app/(user)/reset-password/layout.tsx @@ -0,0 +1,3 @@ +import Layout from "../../common/Layout"; + +export default Layout; \ No newline at end of file diff --git a/frontend/src/app/(user)/reset-password/page.tsx b/frontend/src/app/(user)/reset-password/page.tsx new file mode 100644 index 0000000000..4d58911e65 --- /dev/null +++ b/frontend/src/app/(user)/reset-password/page.tsx @@ -0,0 +1,9 @@ +import ResetPassword from "./components/ResetPassword"; + +const ResetPasswordPage = () => { + return ( + + ); +} + +export default ResetPasswordPage; \ No newline at end of file diff --git a/frontend/src/app/(user)/user/[id]/page.tsx b/frontend/src/app/(user)/user/[id]/page.tsx new file mode 100644 index 0000000000..6d1c0c6236 --- /dev/null +++ b/frontend/src/app/(user)/user/[id]/page.tsx @@ -0,0 +1,57 @@ +/* eslint-disable react/no-unescaped-entities */ +"use client"; + +import { getUser } from "@/api/user"; +import { useEffect, useState } from "react"; +import { User } from "@/types/user"; +import { useParams } from "next/navigation"; +import Link from "next/link"; +import VerificationSymbol from "@/app/common/VerificationSymbol"; + +// no need login +const ProfilePage = () => { + const params = useParams(); + const [user, setUser] = useState({}); + + useEffect(() => { + const { id } = params as { id: string }; + getUser(id as string).then((res) => { + setUser(res.data); + }); + }, [params]); + + const calculateAge = (createdAt: string | undefined) => { + if (!createdAt) return; + const birthDate = new Date(createdAt); + const ageDiff = new Date().getTime() - birthDate.getTime(); + const age = Math.floor(ageDiff / (1000 * 3600 * 24)); // Convert milliseconds to days + return age; + }; + + return ( +
+

{user?.username}'s Profile!

+
+

Profile Age

+ {calculateAge(user?.createdAt)} days + +

Email

+
+

{user?.email}

+ +
+ +

Bio

+ {user?.bio && {user?.bio}} + +

GitHub

+ {user?.github && {user?.github}} + +

LinkedIn

+ {user?.linkedin && {user?.linkedin}} +
+
+ ); +} + +export default ProfilePage; \ No newline at end of file diff --git a/frontend/src/app/(user)/user/layout.tsx b/frontend/src/app/(user)/user/layout.tsx new file mode 100644 index 0000000000..33ba319f6f --- /dev/null +++ b/frontend/src/app/(user)/user/layout.tsx @@ -0,0 +1,3 @@ +import Layout from "../../common/Layout"; + +export default Layout; \ No newline at end of file diff --git a/frontend/src/app/(user)/user/me/page.tsx b/frontend/src/app/(user)/user/me/page.tsx new file mode 100644 index 0000000000..223612e191 --- /dev/null +++ b/frontend/src/app/(user)/user/me/page.tsx @@ -0,0 +1,407 @@ +/* eslint-disable @typescript-eslint/no-unused-vars */ +"use client"; + +import { Button } from "@/components/ui/button"; +import { + Form, + FormControl, + FormField, + FormItem, + FormLabel, + FormMessage, +} from "@/components/ui/form"; +import { Input } from "@/components/ui/input"; +import { useForm } from "react-hook-form"; +import { + getToken, + getUser, + getUserId, + updateUser, + getFileUrl, + resetPasswordFromProfile, + setUsername, +} from "@/api/user"; +import { useEffect, useRef, useState } from "react"; +import { User } from "@/types/user"; +import { z } from "zod"; +import { zodResolver } from "@hookform/resolvers/zod"; +import { CgProfile } from "react-icons/cg"; +import MoonLoader from "react-spinners/MoonLoader"; +import { IoCloseCircle } from "react-icons/io5"; + +const profileFormSchema = z.object({ + username: z + .string() + .min(5, "Username must be at least 5 characters") + .max(20, "Username must be at most 20 characters") + .optional(), + profilePictureUrl: z + .string() + .optional() + .refine((value) => !value || z.string().url().safeParse(value).success, { + message: "Invalid URL", + }), + email: z.string().email("Invalid email").optional(), + bio: z.string().optional(), + linkedin: z + .string() + .refine((val) => val.length == 0 || val.includes("linkedin.com/in/"), { + message: "Invalid URL, is this a LinekdIn URL?", + }) + .optional(), + github: z + .string() + .refine((val) => val.length == 0 || val.includes("github.com/"), { + message: "Invalid URL, is this a GitHub URL?", + }) + .optional(), +}); + +const resetPasswordFormSchema = z + .object({ + password: z + .string() + .min(8, "Password must be at least 8 characters") + .max(100, "Password must be at most 100 characters") + .regex(/[a-z]/, "Password must contain at least one lowercase letter") + .regex(/[A-Z]/, "Password must contain at least one uppercase letter") + .regex(/\d/, "Password must contain at least one number") + .regex( + /[@$!%*?&]/, + "Password must contain at least one special character (@, $, !, %, *, ?, &)" + ), + confirmPassword: z + .string() + .min(8, "Password must be at least 8 characters"), + }) + .refine((data) => data.password === data.confirmPassword, { + message: "Passwords do not match", + path: ["confirmPassword"], // Error message will show up on confirmPassword + }); + +const ProfilePage = () => { + const [token, setToken] = useState(false); + const [user, setUser] = useState({}); + const fileInputRef = useRef(null); + const [isLoading, setIsLoading] = useState(false); + + const profileForm = useForm>({ + resolver: zodResolver(profileFormSchema), + defaultValues: { + username: "", + profilePictureUrl: "", + email: "", + bio: "", + linkedin: "", + github: "", + }, + }); + + const resetPasswordForm = useForm>({ + resolver: zodResolver(resetPasswordFormSchema), + defaultValues: { + password: "", + confirmPassword: "", + }, + }); + + useEffect(() => { + setToken((_) => !!getToken()); + }, []); + + useEffect(() => { + getUser().then((res) => { + setUser(res.data); + profileForm.reset(res.data); + }); + }, [profileForm]); + + const onUpdateProfileSubmit = async ( + data: z.infer + ) => { + await updateUser(data); + setUser(data); + if (data.username) setUsername(data.username); + }; + + const onResetPasswordSubmit = async ( + data: z.infer + ) => { + await resetPasswordFromProfile(data.password); + resetPasswordForm.reset(); + }; + + const triggerFileInput = () => { + if (fileInputRef.current && !isLoading) { + console.log("Click"); + fileInputRef.current.click(); + } + }; + + const handleProfilePictureUpload = async ( + e: React.ChangeEvent + ) => { + console.log("Uploading profile picture..."); + try { + if (e.target.files && e.target.files.length > 0) { + const imageFile = e.target.files[0]; + const formData = new FormData(); + formData.append("profilePicture", imageFile); + const userId = getUserId() ?? ""; + + setIsLoading(true); + const res = await getFileUrl(userId, formData); + + if (res.fileUrl) { + profileForm.setValue("profilePictureUrl", res.fileUrl); + setUser({ ...user, profilePictureUrl: res.fileUrl }); + } + } + } catch (error) { + console.log(error); + } finally { + setIsLoading(false); + } + }; + + return ( + !!token && ( +
+

+ Welcome, {user?.username}! +

+
+ + ( +
+ +
+ {field.value ? ( +
+ + {isLoading ? ( +
+ +
+ ) : ( +
+ + +
+ )} + { + e.stopPropagation(); + profileForm.setValue("profilePictureUrl", ""); + setUser({ ...user, profilePictureUrl: "" }); + }} + /> +
+ ) : ( +
+ {isLoading ? ( +
+ +
+ ) : ( + + )} +
+ )} + +
+
+ +
+ )} + /> + + ( + + + USERNAME + + + + + {/* This is your public display name. */} + + + )} + /> + ( + + + EMAIL + + + + + {/* This is your public display name. */} + + + )} + /> + + ( + + BIO + + + + {/* This is your public display name. */} + + + )} + /> + ( + + + LINKEDIN URL + + + + + {/* This is your public display name. */} + + + )} + /> + ( + + + GITHUB URL + + + + + {/* This is your public display name. */} + + + )} + /> + + + + +
+ + ( + + + NEW PASSWORD + + + + + + + )} + /> + ( + + + CONFIRM NEW PASSWORD + + + + + + + )} + /> + + + +
+ ) + ); +}; + +export default ProfilePage; diff --git a/frontend/src/app/(user)/verify/components/AlreadyVerified.tsx b/frontend/src/app/(user)/verify/components/AlreadyVerified.tsx new file mode 100644 index 0000000000..8b55184664 --- /dev/null +++ b/frontend/src/app/(user)/verify/components/AlreadyVerified.tsx @@ -0,0 +1,15 @@ +import Link from "next/link"; + +const AlreadyVerifiedPage = () => { + return ( +
+
+

Already Verified!

+

It seems you have already verified your email...

+ Go to Dashboard +
+
+ ); +}; + +export default AlreadyVerifiedPage; \ No newline at end of file diff --git a/frontend/src/app/(user)/verify/components/Error.tsx b/frontend/src/app/(user)/verify/components/Error.tsx new file mode 100644 index 0000000000..6ed8b1e0e7 --- /dev/null +++ b/frontend/src/app/(user)/verify/components/Error.tsx @@ -0,0 +1,15 @@ +import Link from "next/link"; + +const ErrorPage = () => { + return ( +
+
+

Error!

+

Oops... It seems something went wrong when verifying your email...

+ Go to Dashboard +
+
+ ); +}; + +export default ErrorPage; \ No newline at end of file diff --git a/frontend/src/app/(user)/verify/components/Verified.tsx b/frontend/src/app/(user)/verify/components/Verified.tsx new file mode 100644 index 0000000000..142052caa3 --- /dev/null +++ b/frontend/src/app/(user)/verify/components/Verified.tsx @@ -0,0 +1,15 @@ +import Link from "next/link"; + +const VerifiedPage = () => { + return ( +
+
+

Verified!

+

Thank you for verifying your email! Welcome to PeerPrep!

+ Go to Dashboard +
+
+ ); +}; + +export default VerifiedPage; \ No newline at end of file diff --git a/frontend/src/app/(user)/verify/components/Verifying.tsx b/frontend/src/app/(user)/verify/components/Verifying.tsx new file mode 100644 index 0000000000..02eebdf77e --- /dev/null +++ b/frontend/src/app/(user)/verify/components/Verifying.tsx @@ -0,0 +1,15 @@ +import { Spinner } from '@/components/ui/spinner'; + +const VerifyingPage = () => { + return ( +
+
+ +

Verifying...

+
+
+
+ ); +} + +export default VerifyingPage; \ No newline at end of file diff --git a/frontend/src/app/(user)/verify/layout.tsx b/frontend/src/app/(user)/verify/layout.tsx new file mode 100644 index 0000000000..33ba319f6f --- /dev/null +++ b/frontend/src/app/(user)/verify/layout.tsx @@ -0,0 +1,3 @@ +import Layout from "../../common/Layout"; + +export default Layout; \ No newline at end of file diff --git a/frontend/src/app/(user)/verify/page.tsx b/frontend/src/app/(user)/verify/page.tsx new file mode 100644 index 0000000000..0f2a566805 --- /dev/null +++ b/frontend/src/app/(user)/verify/page.tsx @@ -0,0 +1,48 @@ +"use client"; + +import { useSearchParams } from "next/navigation"; +import { useEffect, useState } from "react"; +import VerifyingPage from "./components/Verifying"; +import VerifiedPage from "./components/Verified"; +import ErrorPage from "./components/Error"; + +// handles the verification of the user's email address +const NEXT_PUBLIC_IAM_USER_SERVICE = process.env.NEXT_PUBLIC_IAM_USER_SERVICE; +const VerifyPage = () => { + const searchParams = useSearchParams(); + const code = searchParams.get("code") || ""; + const [verified, setVerified] = useState(false); + const [alreadyVerified, setAlreadyVerified] = useState(false); + const [error, setError] = useState(false); + + useEffect(() => { + const verify = async () => { + try { + const response = await fetch( + `${NEXT_PUBLIC_IAM_USER_SERVICE}/verify?code=${code}` + ); + if (response.status === 200) { + setVerified(true); + } else if (response.status === 400) { + setAlreadyVerified(true); + } else { + setError(true); + } + } catch (error) { + setError(true); + } + }; + verify(); + }, [code]); + + return ( +
+ {/* use Verifying Page as suspense, waiting for the rest to load */} + {!verified && !alreadyVerified && !error && } + {(verified || alreadyVerified) && } + {error && } +
+ ); +}; + +export default VerifyPage; diff --git a/frontend/src/app/[...not_found]/page.js b/frontend/src/app/[...not_found]/page.js new file mode 100644 index 0000000000..d29e156e2a --- /dev/null +++ b/frontend/src/app/[...not_found]/page.js @@ -0,0 +1,5 @@ +import {notFound} from "next/navigation" + +export default function NotFoundCatchAll() { + notFound() +} diff --git a/frontend/src/app/admin/components/AddQuestionDialog.tsx b/frontend/src/app/admin/components/AddQuestionDialog.tsx new file mode 100644 index 0000000000..d6b9671c2b --- /dev/null +++ b/frontend/src/app/admin/components/AddQuestionDialog.tsx @@ -0,0 +1,328 @@ +"use client"; + +import { Button } from "@/components/ui/button"; +import { + Form, + FormControl, + FormField, + FormItem, + FormLabel, + FormMessage, +} from "@/components/ui/form"; +import { Input } from "@/components/ui/input"; +import { MultiSelect } from "@/components/ui/multiselect"; +import { Textarea } from "@/components/ui/textarea"; +import { QuestionDifficulty } from "@/types/find-match"; +import { zodResolver } from "@hookform/resolvers/zod"; +import { useState } from "react"; +import { useForm, useFieldArray } from "react-hook-form"; +import Swal from "sweetalert2"; +import { z } from "zod"; +import MoonLoader from "react-spinners/MoonLoader"; +import { createSingleQuestion } from "@/api/question-dashboard"; +import { topicsList } from "@/utils/constants"; + +interface AddQuestionDialogProps { + handleClose: () => void; + setRefreshKey: React.Dispatch>; +} + +const AddQuestionDialog = ({ + handleClose, + setRefreshKey, +}: AddQuestionDialogProps) => { + const [isSubmitting, setIsSubmitting] = useState(false); + + const formSchema = z.object({ + questionTitle: z.string().min(2, { + message: "Title must be at least 2 characters.", + }), + questionDifficulty: z.string().nonempty({ + message: "Please select a difficulty.", + }), + questionTopics: z.array(z.string()).min(1, { + message: "Please select at least one topic.", + }), + questionDescription: z.string().min(10, { + message: "Description must be at least 10 characters.", + }), + examples: z.array( + z.object({ + expected_input: z.string().min(1, { message: "Input is required." }), + expected_output: z.string().min(1, { message: "Output is required." }), + explanation: z.string().optional(), + }) + ), + solution: z.string().optional(), + }); + + const form = useForm>({ + resolver: zodResolver(formSchema), + defaultValues: { + questionTitle: "", + questionDifficulty: "", + questionTopics: [], + questionDescription: "", + examples: [{ expected_input: "", expected_output: "", explanation: "" }], + solution: "", + }, + }); + + const { fields, append, remove } = useFieldArray({ + control: form.control, + name: "examples", + }); + + async function onSubmit(values: z.infer) { + setIsSubmitting(true); + + const examplesWithQuestionNumber = values.examples.map( + (example, index) => ({ example_num: index + 1, ...example }) + ); + + createSingleQuestion({ + title: values.questionTitle, + description: values.questionDescription, + category: values.questionTopics, + complexity: values.questionDifficulty, + examples: examplesWithQuestionNumber ?? [], + solution: values.solution ?? "", + }) + .then(() => { + Swal.fire({ + icon: "success", + title: "Question Added", + text: "Question has been added successfully.", + }); + }) + .catch(() => { + Swal.fire({ + icon: "error", + title: "Question Add Failed", + text: "Please try again later.", + }); + }) + .finally(() => { + setRefreshKey((prev) => prev + 1); + setIsSubmitting(false); + handleClose(); + }); + } + + return ( +
+
+ Add Question +
+
+ + {/* Question Title */} + ( + + + Question Title + + + + + + + )} + /> + + {/* Difficulty */} + ( + + Difficulty + + + + + + )} + /> + + {/* Topics */} + ( + + Topics + + + + + + )} + /> + + {/* Description */} + ( + + Description + +