From 67aa7f4247d02e697759b7dee108bb3cad480287 Mon Sep 17 00:00:00 2001 From: Faustze Date: Fri, 24 Jul 2026 13:38:28 +0300 Subject: [PATCH 1/2] chore/translate-new-notes --- content-ru/.translation-manifest.json | 131 ++++++++++-------- .../Array/11-container-with-most-water.md | 52 +++++++ .../Array/128-longest-consecutive-sequence.md | 69 +++++++++ ...ers-are-smaller-than-the-current-number.md | 40 +++--- ...ids-with-the-greatest-number-of-candies.md | 50 ++++--- ...41-build-an-array-with-stack-operations.md | 50 ++++--- .../leetcode/Array/1470-shuffle-the-array.md | 18 +-- ...rices-with-a-special-discount-in-a-shop.md | 48 ++++--- content-ru/leetcode/Array/15-3sum.md | 76 ++++++++++ .../150-evaluate-reverse-polish-notation.md | 57 +++++--- .../leetcode/Array/217-contains-duplicate.md | 45 +++--- .../Array/238-product-of-array-except-self.md | 54 ++++++++ .../leetcode/Array/268-missing-number.md | 57 ++++---- content-ru/leetcode/Array/283-move-zeroes.md | 43 +++--- .../Array/347-top-k-frequent-elements.md | 31 +++-- content-ru/leetcode/Array/36-valid-sudoku.md | 88 ++++++++++++ ...ind-all-numbers-disappeared-in-an-array.md | 16 +-- .../Array/485-max-consecutive-ones.md | 12 +- .../leetcode/Array/49-group-anagrams.md | 101 +++++++------- .../Array/496-next-greater-element-i.md | 60 ++++++++ .../leetcode/Array/605-can-place-flowers.md | 6 +- .../Array/636-exclusive-time-of-functions.md | 130 +++++++---------- .../Array/643-maximum-average-subarray-i.md | 29 ++-- content-ru/leetcode/Array/645-set-mismatch.md | 11 +- .../leetcode/Array/704-binary-search.md | 49 +++++++ .../leetcode/Array/735-asteroid-collision.md | 86 ++++++++++++ .../leetcode/Array/739-daily-temperatures.md | 46 ++++-- content-ru/leetcode/Array/853-car-fleet.md | 67 +++++++++ .../Array/977-squares-of-a-sorted-array.md | 50 ++++--- content-ru/leetcode/Array/index.md | 15 +- .../Hash Table/141-linked-list-cycle.md | 93 +++++++------ .../leetcode/Hash Table/242-valid-anagram.md | 47 ++++--- content-ru/leetcode/Hash Table/index.md | 8 +- .../Linked List/206-reverse-linked-list.md | 69 +++++---- .../876-middle-of-the-linked-list.md | 67 ++++----- content-ru/leetcode/Linked List/index.md | 8 +- ...1071-greatest-common-divisor-of-strings.md | 47 +++++++ content-ru/leetcode/Math/67-add-binary.md | 55 ++++++++ content-ru/leetcode/Math/index.md | 12 ++ content-ru/leetcode/Stack/155-min-stack.md | 65 +++++++++ content-ru/leetcode/Stack/index.md | 11 ++ .../leetcode/String/20-valid-parentheses.md | 52 +++++++ content-ru/leetcode/String/index.md | 6 +- .../Tree/104-maximum-depth-of-binary-tree.md | 53 +++++++ content-ru/leetcode/Tree/index.md | 11 ++ .../Two Pointers/125-valid-palindrome.md | 33 +++-- .../151-reverse-words-in-a-string.md | 27 ++-- .../1768-merge-strings-alternately.md | 50 +++---- .../345-reverse-vowels-of-a-string.md | 34 ++--- .../Two Pointers/392-is-subsequence.md | 22 +-- .../844-backspace-string-compare.md | 88 ++++++------ content-ru/leetcode/Two Pointers/index.md | 16 +-- .../Untagged/125-valid-palindrome-neetcode.md | 49 +++++++ content-ru/leetcode/Untagged/2620-counter.md | 5 +- .../Untagged/2622-cache-with-time-limit.md | 81 ++++++----- content-ru/leetcode/Untagged/2623-memoize.md | 14 +- .../2626-array-reduce-transformation.md | 46 +++--- content-ru/leetcode/Untagged/2627-debounce.md | 29 ++-- .../Untagged/2629-function-composition.md | 27 +--- content-ru/leetcode/Untagged/2631-group-by.md | 29 ++-- .../Untagged/2637-promise-time-limit.md | 25 +--- content-ru/leetcode/Untagged/2665-counter2.md | 16 ++- .../Untagged/2666-allow-one-fn-call.md | 16 +-- .../leetcode/Untagged/2677-chunk-array.md | 17 ++- .../2693-call-function-with-custom-context.md | 27 +++- .../2703-return-length-of-arguments-passed.md | 29 ++-- .../Untagged/271-string-encode-and-decode.md | 64 +++++++++ .../Untagged/2715-timeout-cancellation.md | 47 +++---- ...cute-asynchronous-functions-in-parallel.md | 80 +++++------ .../Untagged/2723-add-two-promises.md | 51 ++++--- content-ru/leetcode/Untagged/2724-sort-by.md | 52 +++---- .../Untagged/2725-interval-cancellation.md | 17 ++- .../2726-calculator-with-method-chaining.md | 36 +++-- content-ru/leetcode/Untagged/index.md | 6 +- content-ru/leetcode/index.md | 5 +- 75 files changed, 2182 insertions(+), 1047 deletions(-) create mode 100644 content-ru/leetcode/Array/11-container-with-most-water.md create mode 100644 content-ru/leetcode/Array/128-longest-consecutive-sequence.md create mode 100644 content-ru/leetcode/Array/15-3sum.md create mode 100644 content-ru/leetcode/Array/238-product-of-array-except-self.md create mode 100644 content-ru/leetcode/Array/36-valid-sudoku.md create mode 100644 content-ru/leetcode/Array/496-next-greater-element-i.md create mode 100644 content-ru/leetcode/Array/704-binary-search.md create mode 100644 content-ru/leetcode/Array/735-asteroid-collision.md create mode 100644 content-ru/leetcode/Array/853-car-fleet.md create mode 100644 content-ru/leetcode/Math/1071-greatest-common-divisor-of-strings.md create mode 100644 content-ru/leetcode/Math/67-add-binary.md create mode 100644 content-ru/leetcode/Math/index.md create mode 100644 content-ru/leetcode/Stack/155-min-stack.md create mode 100644 content-ru/leetcode/Stack/index.md create mode 100644 content-ru/leetcode/String/20-valid-parentheses.md create mode 100644 content-ru/leetcode/Tree/104-maximum-depth-of-binary-tree.md create mode 100644 content-ru/leetcode/Tree/index.md create mode 100644 content-ru/leetcode/Untagged/125-valid-palindrome-neetcode.md create mode 100644 content-ru/leetcode/Untagged/271-string-encode-and-decode.md diff --git a/content-ru/.translation-manifest.json b/content-ru/.translation-manifest.json index 9476062b99ccc..f7149b61378df 100644 --- a/content-ru/.translation-manifest.json +++ b/content-ru/.translation-manifest.json @@ -2,73 +2,92 @@ "headhunter/JavaScript-easy-level.md": "07d772fee0195708ac9b6bdf41e1f0fcd2efcf15861cc34947dbce0975d26277", "headhunter/JavaScript-middle-level.md": "46ae57febadc70bebdc4f8116a7cf2db901c525e2b573bcfa34377be7af45ac0", "headhunter/index.md": "d9888f62e5b1a3e71f67b05616d51e15e1eccb67be651c33da850f48f438afd2", + "leetcode/Array/11-container-with-most-water.md": "8a735550d14dee7e853dee42c6ba6fd04b8671a31b76958370e192972cb39d5a", "index.md": "9da5f03310750282a9d78c77d9f3d8bd547ca447608377e930b344b05465465a", - "leetcode/Array/1431-kids-with-the-greatest-number-of-candies.md": "63fdcc01a7a44dca9301fe6f9b46a221ce36b4ac4c7a82d004451a63151e9e35", - "leetcode/Array/1365-how-many-numbers-are-smaller-than-the-current-number.md": "1aabb7af878dc57059138773a80f3b5a829dd00f55e5090008c6405664aaf866", - "leetcode/Array/1441-build-an-array-with-stack-operations.md": "f83b6cc4f1f9c526925ffc84ae60d6ed8ebed87d47c277d6adc35aae1a8f9b4c", - "leetcode/Array/1470-shuffle-the-array.md": "d689cc8a9113e0a9caf1d06e3056d9dbf29ec6e2e2fbbdc2f2829500eae98015", - "leetcode/Array/1475-final-prices-with-a-special-discount-in-a-shop.md": "37d8d67a2e299cd5df218d853827ba7d8d838a43aae5871f4485ab0ee1a51f87", - "leetcode/Array/150-evaluate-reverse-polish-notation.md": "39af4b5a73bcaa6cd1ca63877e3d4f6d294257d2e565bf8e2aa56938b1191fec", - "leetcode/Array/217-contains-duplicate.md": "d7c07c031f8a89148456171805e5e0cc1c734c1d0f39655407800a0b12daa05a", - "leetcode/Array/268-missing-number.md": "d980141d5e2799b0d5b8a6885f0ec1f28349b757adf5840e59a511a942d60ed8", - "leetcode/Array/283-move-zeroes.md": "ecd64c153895b45966a424a3eca18924845c3f10cba6b941d3bc8c7f388c6ce8", - "leetcode/Array/347-top-k-frequent-elements.md": "acede1659e36a24a6677c97c97b79ecb1ac3e04194d91a59bc7e1cf5aa3aac26", - "leetcode/Array/448-find-all-numbers-disappeared-in-an-array.md": "d2ed121ca6ec1835ef5d86896aa19524cf4914f87086c47949971c3d945ea2b3", - "leetcode/Array/485-max-consecutive-ones.md": "46c3435899b62a0530a1fd80be5c41bb5e980d0ca8df4cbfec837a15e927155b", - "leetcode/Array/49-group-anagrams.md": "29d3d6ebc88c673cb91100874a3d99a7936e7b1063211105fc9a8bfca4b8378d", - "leetcode/Array/605-can-place-flowers.md": "11bc3914c5e1131e5c5377779f275a156b8ec959cd24cfd31169e233d3b3670a", - "leetcode/Array/636-exclusive-time-of-functions.md": "a8b8ab9d43c61445e57d86dddbca66684b1d57dc4fe44a11a1922f0199e015a9", - "leetcode/Array/643-maximum-average-subarray-i.md": "456fa20ed3b0e3406f29374ca845a82f23011f25ef8a8e4849dd8f6bd2c6724b", - "leetcode/Array/739-daily-temperatures.md": "e8ee50281cb0aad8abc9aac86d042986a6426e4d848ed139387bec565c627cef", - "leetcode/Array/645-set-mismatch.md": "9c191de49444ce493d69e290bb94a2505671e3d5d9578c77dc90ae1d22cbc1dc", - "leetcode/Array/977-squares-of-a-sorted-array.md": "ac2d931d781a3882411a2503a2c5b278db48c5f8fb2c208148fb894ccbe152cd", - "leetcode/Array/index.md": "be617ed5dddd1de586b918f9db40ffe287c764276984c5376d34840016c77044", + "leetcode/Array/128-longest-consecutive-sequence.md": "bb86cb5975db819d2c34752f0a1ca02abb9b65eda3f7313aac2ad95c88bb480e", + "leetcode/Array/1365-how-many-numbers-are-smaller-than-the-current-number.md": "f816494f32fef0b84d820be9cd1f803d78f614d9c75ec73ef64cf58775767dee", + "leetcode/Array/1431-kids-with-the-greatest-number-of-candies.md": "b1fbb71ca3551f90b3d25f529c47e17d6a73383e1c36bfa04862229f749c51d0", + "leetcode/Array/1441-build-an-array-with-stack-operations.md": "a00f1e6e0be8fb3a96fdec7af7acec5df08729d792d6a2700c13d3dc497d77dd", + "leetcode/Array/1470-shuffle-the-array.md": "6e8126ee811ef642491ebba9cb092e5b23d6f8679804ed2697212e8a5ec572b9", + "leetcode/Array/1475-final-prices-with-a-special-discount-in-a-shop.md": "3c21935ee9ecee1743de2943e83d1d2188c861d3b2ed9969e7647c230bf028cc", + "leetcode/Array/15-3sum.md": "eda5986825dc0a56a685c6aea8c4ed5fa04875072f0051c419eeae224326e0d3", + "leetcode/Array/150-evaluate-reverse-polish-notation.md": "ee1d723504f059a55bc5a80846458ea922297914ed9ee43d5661a6bdf90caa63", + "leetcode/Array/217-contains-duplicate.md": "77bc0fb031ea58f908fc8ccfc7bcba17e7a8f42e6566dacb285127ad79d33c67", + "leetcode/Array/238-product-of-array-except-self.md": "3f1fea69de59d7061cdd14a9a3fbf6bf4b1291fd372110be97c37a4cc21a40a5", + "leetcode/Array/268-missing-number.md": "3577d85e78ddb8969652d2858a4aa598a0f32a2afc3fa8782d28bfeff58dd665", + "leetcode/Array/283-move-zeroes.md": "f20009dffaa4fb97d7ba05ec35cce58b7bce71de96eb76053d3fde7e8827645f", + "leetcode/Array/347-top-k-frequent-elements.md": "fca4f6ade48cc15b704b25245ef037a0ea55c403c3457eb6c371e5e73ad53c63", + "leetcode/Array/36-valid-sudoku.md": "11273da1e89a5ec091515c106849a37da00d5bb903a9d7952e7a46937de262f5", + "leetcode/Array/448-find-all-numbers-disappeared-in-an-array.md": "e8c6856074bccaa8cf4f1f3c28ddc53dab93df186bb794da94ea06d27900a837", + "leetcode/Array/485-max-consecutive-ones.md": "cecd3f4d56c8e2c2f4cff8965f0b6c1aa5f217614aaeb1bd32024c9455d6fa26", + "leetcode/Array/49-group-anagrams.md": "ebfbe37f7e965962e52c86c1dd11210b54d76e5b775bd0f500f6bef1d01093ec", + "leetcode/Array/496-next-greater-element-i.md": "569216419f565e9f4cb5b60f5faed22e4d40f15474fdb8ebb425046a0495bcb5", + "leetcode/Array/605-can-place-flowers.md": "5a267f76d903e85cd258a90ec85b10040f4c00a90f2937868b7cc5d7046d0dec", + "leetcode/Array/636-exclusive-time-of-functions.md": "c2284d1cf444318e39128ae13f81d0ec7e9637fb0c0025d904824e1612fc6963", + "leetcode/Array/643-maximum-average-subarray-i.md": "c62b46e6311fa75e55a6b639be2cf3bc34225242e635645afb23f8eb6d102acd", + "leetcode/Array/645-set-mismatch.md": "acc20ca19753e4973ef37b965c41266860c88e0de46a3403029bfa9faf79a5a7", + "leetcode/Array/704-binary-search.md": "38b6a0a46fd8780fd3967bc1c1faed23b0ae853c956c03cdbd4c2d6614be4731", + "leetcode/Array/735-asteroid-collision.md": "c30fabdb1a4f851c56655b15bd9f7291a2da09ff3386b2ec3b2aedf039357422", + "leetcode/Array/739-daily-temperatures.md": "0bfddf3b8279c46885dd3e9af83a5cc89c3eeaf590503dce4a63993c6de6cba9", + "leetcode/Array/853-car-fleet.md": "d358af8120e5bea872cf1bf7e2df7bfd7c71061f27ab73f4ca2e68779f77c36c", + "leetcode/Array/977-squares-of-a-sorted-array.md": "86bd6cb5aca5d6b093247b86829f5812eb925665e69938e93dce671dde7bd64d", + "leetcode/Array/index.md": "41312c1aa22a2bc48942ab7db09a841e791bcf67b807d817ec2de0e21c2295cf", "leetcode/Binary Tree/104-maximum-depth-of-binary-tree.md": "7b7cf86f3dd19dab12c5bb5a80d6dc889d05c8311f736e29a7910290c383487c", "leetcode/Binary Tree/index.md": "bb041a66e32d22d4aa02c786575954937f2de9fe580c34c4c8c934ab07558992", - "leetcode/Bit Manipulation/67-add-binary.md": "2a126e7e39ea2ee7a1572acbcddfbe458ee82e78255ca453eaf927b828d1ae31", "leetcode/Bit Manipulation/index.md": "0b0adb3378454a911b3002ebcbb86a25d0079a9f156c4241a839a25f8f356f38", - "leetcode/Hash Table/141-linked-list-cycle.md": "e4e7ef198e57b817eb42caabb12594f31e4e1f02b39c5b0a286736e28464416e", - "leetcode/Hash Table/242-valid-anagram.md": "dc018ef171c8ffa3fd947f6faeceacc6212e04bd6f7145a158087d6f490b8394", - "leetcode/Hash Table/index.md": "4586b29e6b77b35df8c55c9255c11a1f1537c254fd925e590fc7c4697fa23124", - "leetcode/Linked List/206-reverse-linked-list.md": "98579775c8a13b74052a094cb9592dc323696d917771367fabc15ef8b13c4b4a", - "leetcode/Linked List/876-middle-of-the-linked-list.md": "f314fd73b8b84c1c9db3b19c72ec19f78b6081a1f0e1441338dfdca02cfb95cb", - "leetcode/Linked List/index.md": "1f66408decafad77eaa46becef2b990afd980ee4de07433e4de733101e0cd9a7", + "leetcode/Bit Manipulation/67-add-binary.md": "2a126e7e39ea2ee7a1572acbcddfbe458ee82e78255ca453eaf927b828d1ae31", + "leetcode/Hash Table/141-linked-list-cycle.md": "d7538035f0f319e0fe14792ef58e044728747a3360020d7668647aba2d5e49c0", + "leetcode/Hash Table/242-valid-anagram.md": "918da654051dfe91aa4604aa3c2014818f648abc856f2559596215418275c14c", + "leetcode/Hash Table/index.md": "f3ba5f85339d830df3c1e5cad598e5bc9194bef16fab3896671aed4b6911fc06", + "leetcode/Linked List/206-reverse-linked-list.md": "b36b3ec86054908593234ebb96be81bb5d246a8af9e0f17690a4fb5be4275bc1", + "leetcode/Linked List/876-middle-of-the-linked-list.md": "b40410ae2327c5e5ba6a06e000ff7482e425186832e587a08e4e93a353797562", + "leetcode/Linked List/index.md": "1ed2a4773566072292b91d4db16b415e458a76c2ef0e9a9348e82e8a16197c37", + "leetcode/Math/1071-greatest-common-divisor-of-strings.md": "f99a51799e789e2f7cc7a6d0b7fb1e560a166e31562a85662c5d65f586dc5963", + "leetcode/Math/67-add-binary.md": "2149fb9dcaf8554953051be4ad6c423275a517c30f098d37c767ba0167493e67", + "leetcode/Math/index.md": "830b5d1cc54f08c4fe04b528873eb98c0ee2135565bafa58ba1987ccc71e204e", "leetcode/Patterns/index.md": "91b98e2e91ebf0120b3f11af329e7612ff72e2115abff43328d24b6392f1df06", "leetcode/RegExp/easy/125-Valid-Palindrome.md": "b49a4bec7a9441a3416417604cd0fa434662d60b70b5da829da0e18d0981b164", "leetcode/RegExp/easy/index.md": "db9c117825e03c6dfb1d49204728f47e164303c960c31b98c06e2cc2edf97acc", "leetcode/RegExp/hard/index.md": "f5a7ee32c54d0aa4e2a8e70c436c9c5d2d026fc74199cf20c6c386e42072fc15", "leetcode/RegExp/index.md": "e7bf3a1f297442c1a7f5ee9aacabe9fdde9f2324ffc6a780bcb010a0004a5588", "leetcode/RegExp/medium/index.md": "ab62ebc8a5e5519835b27ed24b5771e7b3a1b9bcf655eb33baf023b6b2a194c2", + "leetcode/Stack/155-min-stack.md": "25a7eccf2f43411ac98bcc103412154c85a147ba2b0760e3ab12e22120873163", + "leetcode/Stack/index.md": "586159d36c4e8c6f765e6658a515d14a87903a5f356149298340e0109fb9c1a9", + "leetcode/String/20-valid-parentheses.md": "1c25f418d9dd3a4eaf6998878a8ad3109e3674c0f79a170386103f7d6dfc0ebd", "leetcode/String/1071-greatest-common-divisor-of-strings.md": "9161f7f16739eb7e040db86053a57a58e8f211743ab24ecaf7aa0bc79ba97273", - "leetcode/String/index.md": "a6490229f6719276c18c51c49ddddd52107f950342d16ded5dbfac29ae90ac26", - "leetcode/Two Pointers/125-valid-palindrome.md": "ad201e9ae78e993ea451e4483f3c4d17f44c8cc013ef5023fc90d1ee0c31c434", - "leetcode/Two Pointers/151-reverse-words-in-a-string.md": "0d148a946592729b1843c380b43a6a92aeb13e265143fd1a11acd805288636c8", - "leetcode/Two Pointers/1768-merge-strings-alternately.md": "7890b6e5a4b017c7efc055a88eebc49abb253b02f77c14853856758ca0fa0b23", - "leetcode/Two Pointers/345-reverse-vowels-of-a-string.md": "5cc6d4f62e3990b05ed0641d7b3456d39007b97a14887c6f007ed147919fbde5", - "leetcode/Two Pointers/392-is-subsequence.md": "eb6745d6df4fb8fd1da6af33385f516fe03175cdc7ba09df952b5cb846134b72", - "leetcode/Two Pointers/844-backspace-string-compare.md": "8d02a3d39ff4052fcc52c880c560b32520162912c4d0ed6247255f9258b4f6e2", - "leetcode/Two Pointers/index.md": "db55f33fb207601386f8666ef5600087920a073f36fb47820cdf110c65a0da4b", - "leetcode/Untagged/2620-counter.md": "a3e6625fd5aa8a3f7b35ab0168f3d38b04f74c1076c28e5c00c3aeb3844eb4bf", - "leetcode/Untagged/2622-cache-with-time-limit.md": "72e6c8c7a7110c84ab4b28dad74f13f8711ac604f95ec00253b29f19a9277a81", - "leetcode/Untagged/2623-memoize.md": "52a806585ea1cd354f3b007c904b2db0c44fc0e049381e58d514470701a608c7", - "leetcode/Untagged/2626-array-reduce-transformation.md": "3c89b98946c784e1cd1e62d51a15fbca02e634003a392fdf14d46bdcda0e5e10", - "leetcode/Untagged/2627-debounce.md": "4fff0107520aa7004bd7c664f4d109900b58209c83b9392787a19cdf0767313e", - "leetcode/Untagged/2629-function-composition.md": "5b09575241a91ac444553b4a97a008dddce51c85edcba07d87b7ed587c4a84d7", - "leetcode/Untagged/2631-group-by.md": "c72ed4fb2d17552fad8222d1a17895fadd1ac45bf51ceeed8bc9b40fe14c1cbf", - "leetcode/Untagged/2637-promise-time-limit.md": "06bbc0cc00eaa9c27b145296574ec31f75e13c56f5b4ea6ce844b74341622846", - "leetcode/Untagged/2665-counter2.md": "6e7c0a6203778be439a7cd3e54097692b160de4c6bdb8e0399c911bfdde1f670", - "leetcode/Untagged/2666-allow-one-fn-call.md": "4a6484179fd5e58c462c7db13afefe3f18ee517bed2aa69f5de4c54307c7235e", - "leetcode/Untagged/2677-chunk-array.md": "ad5617e0b22bec3b0b9f90ad16da4f0465cb1c98eade68c32d93bef8dd654385", - "leetcode/Untagged/2693-call-function-with-custom-context.md": "7a4878299c85a59e5660e56559e8dc0f0aea4824a1910c1cc6f376ff45f1e789", - "leetcode/Untagged/2703-return-length-of-arguments-passed.md": "16bf6a0299eb23e609df9f18f9158bf85179ba476f822cd97abdfe81bd645734", - "leetcode/Untagged/2715-timeout-cancellation.md": "91117be20095f35a544d710fdac1df5e21a6aff2048bc3a3be9f877f942d6532", - "leetcode/Untagged/2721-execute-asynchronous-functions-in-parallel.md": "65d78b32ccf48ce7afdd17e082ef858fc572d91d0adf35bda901eb204d2dd3e2", - "leetcode/Untagged/2723-add-two-promises.md": "2b756d3e9803baf14ba2bd466e23dbf5ecf810f24aac046cda041254f79cc2f7", - "leetcode/Untagged/2724-sort-by.md": "1f8bb9b6510e9d3192e477a2887e2cc09b29be4b4ae77720e8538a76b9279a1d", - "leetcode/Untagged/2725-interval-cancellation.md": "1f32d998285b01c787b59d99100e5c06038e4aef9bbe6a0934cb813cf1409c96", - "leetcode/Untagged/2726-calculator-with-method-chaining.md": "fe686080f35137aed7f31f54a5cd65280f21c25d2be3d88885317405f057c6ff", - "leetcode/Untagged/index.md": "91922cc90086069531bbda1975efc7e6901a2473d9009cb891a1c385b29d5752", - "leetcode/index.md": "ce693bb7f4204990aa1bd336bfd3ee070f90465d172e1d6fab725b93c783f334", + "leetcode/String/index.md": "a204d9fa53134117067547db045dbada54118559e84e339c3be8ab72684ee954", + "leetcode/Tree/104-maximum-depth-of-binary-tree.md": "00268c53d961183aa465e7551190cbb69009cf7f5a03747a450679904e8ef3a2", + "leetcode/Tree/index.md": "132df40193bfba429b2405b2ac7923e051bb229e2df90bf3d4f2d8daf29bee2b", + "leetcode/Two Pointers/125-valid-palindrome.md": "32334fb9a29277144f4c71b45e9d70b176c4b7edf6888e44500f1a0bf82e7252", + "leetcode/Two Pointers/151-reverse-words-in-a-string.md": "c5bd272bb7e57d388a35bf43574798af024f5cc5a1c7e7dd75f8fa2b9fd0ef08", + "leetcode/Two Pointers/1768-merge-strings-alternately.md": "a0c79bd9c720798dd77352cfc6f758d0e6eeef693446a794ff45611b3597791f", + "leetcode/Two Pointers/345-reverse-vowels-of-a-string.md": "dcc3d9613673f579ddd1b8f2b40eba4d87f051c68f8a8382d2bf24e0195702d5", + "leetcode/Two Pointers/392-is-subsequence.md": "65e5a9cd64607ff194617eb88e762f2b1cf4de321a82ea7cd4264702858c0874", + "leetcode/Two Pointers/844-backspace-string-compare.md": "e4c477301f43f894faf38ce9c909e413f1c08331c31ed91a51851545e5e9434b", + "leetcode/Two Pointers/index.md": "4cb491ee0ec59a9ae7949e737e7c8c4415300a1ce6c956f57adab859a3ceac09", + "leetcode/Untagged/125-valid-palindrome-neetcode.md": "2affd3379a11f899152bde7972f1aed6db65771ba5cf014bc4ed627b753fa006", + "leetcode/Untagged/2620-counter.md": "b30b1257075676f58acc3b6a949e32f4ba389c428ead8610dc6bcfd6d75a713c", + "leetcode/Untagged/2622-cache-with-time-limit.md": "15e7c72d825cc9bdaf8301d51c232f07964a9e856106e6a0c19a800b77b73de5", + "leetcode/Untagged/2623-memoize.md": "fc142f067fea89ae13912f34905a17bab7417e0b754cd13b22f09a65b70b302f", + "leetcode/Untagged/2626-array-reduce-transformation.md": "bf182b5b65f9f0b743031c4a7e86ecbcb16ae9d91afd8f34f26177de5887aa85", + "leetcode/Untagged/2627-debounce.md": "3667258cd6475223129647759586737e6fafbd6ee046f24c869db501b0a0295e", + "leetcode/Untagged/2629-function-composition.md": "b50a8db22ebf9d3d606cc5cc6f5c49c8cf6a1510634e6463b0e3a24e51addd68", + "leetcode/Untagged/2631-group-by.md": "b5d3b7da7fb4833fb327fcd04b08a8a46b0dab651fb14fc2335903eec9b9cb7a", + "leetcode/Untagged/2637-promise-time-limit.md": "54473bfbe24bf3c17685e9f8576a2624cdac1ca009cd363723ee9604bf31258a", + "leetcode/Untagged/2665-counter2.md": "94e481888bed24b9298c38db03373ec1cbf1d6b672e8fc606736bcef25c90a2a", + "leetcode/Untagged/2666-allow-one-fn-call.md": "6346763cf0bbb1bb524d002cbae4a1a39385114e13da2cef565ce98ee13d7930", + "leetcode/Untagged/2677-chunk-array.md": "3d2b4bdb37ec5961567244d24933579e1e2ffd0075d36fbac3dda2a689a1ffca", + "leetcode/Untagged/2693-call-function-with-custom-context.md": "54bff68e852adb9af666e2b81ccd17b0f2ec2e030b404eaa7de49bc8a0a9e1e3", + "leetcode/Untagged/2703-return-length-of-arguments-passed.md": "b2669367406b49cfa4904a7643b07cb608c3631274126eb9f8490b5d6a874193", + "leetcode/Untagged/271-string-encode-and-decode.md": "f4f01a023c843c15a56b8c1f6bac420a362064096e9b657a4643eacc2857db75", + "leetcode/Untagged/2715-timeout-cancellation.md": "170a0dca15023327a42ec820beddce08fade08e4267ca13a554c370babe52b8f", + "leetcode/Untagged/2723-add-two-promises.md": "411a4daef6100ecece7bccd87525cb725541de931b6dcba40ab2614aae029248", + "leetcode/Untagged/2721-execute-asynchronous-functions-in-parallel.md": "70387ecd0e5134a6c989bfafc41daac9df31147d6469e87d0b46538f4375a648", + "leetcode/Untagged/2724-sort-by.md": "1feb454ea55531d52e47950aa416cc23702f76d6560319c37f80dbc1118f687c", + "leetcode/Untagged/2725-interval-cancellation.md": "d245e0d1ec13403fa51b8349d2524332507c9b0cb3ff7c71ac99becbb8ff0eb9", + "leetcode/Untagged/index.md": "988a5773fd5f501cd92b5b3223500966941b19d5f2d21448da391cdc4895f064", + "leetcode/Untagged/2726-calculator-with-method-chaining.md": "249ec94bdb2fa52ded25c266daf411ed4e208d966f0041939aabe4d647d99c7f", + "leetcode/index.md": "88c151c7c5564227dea91e47d96076632d854dd7fc1eddfa45440093be401dc3", "vue/Internals/Compiler.md": "c46b3dd12912b11bc4f0a34b2abba574baff9626f42df410eab279ae77b99e90", "vue/Internals/Reactivity.md": "9b502f513195b4512f4d8188f1ac30746030e1c5a52a6a626d51c80c15752d24", "vue/Internals/index.md": "0637645f58c346554c1687702236afa74ed3b25e795a4c0ad5038369ed0479fb", diff --git a/content-ru/leetcode/Array/11-container-with-most-water.md b/content-ru/leetcode/Array/11-container-with-most-water.md new file mode 100644 index 0000000000000..f62c837715ec1 --- /dev/null +++ b/content-ru/leetcode/Array/11-container-with-most-water.md @@ -0,0 +1,52 @@ +# 11. Контейнер с наибольшим количеством воды (Medium) () + +> Дан целочисленный массив height длины n. +> Проведены n вертикальных линий, такие что конечные точки i-й линии — это (i, 0) и (i, height[i]). +> Найдите две линии, которые вместе с осью x образуют контейнер, содержащий максимальное количество воды. +> Верните максимальное количество воды, которое может удержать контейнер. +> Обратите внимание, что наклонять контейнер нельзя. +> Ограничения: - n == height.length - 2 <= n <= 10^5 - 0 <= height[i] <= 10^4 + +```ts +function maxArea(height: number[]): number { + let left = 0, + right = height.length - 1; + let area = 0; + + while (left < right) { + const leftValue = height[left], + rightValue = height[right]; + area = Math.max(area, Math.min(leftValue, rightValue) * (right - left)); + + if (leftValue < rightValue) { + left++; + } else { + right--; + } + } + + return area; +} + +// Локальная проверка: +console.log(maxArea([1, 8, 6, 2, 5, 4, 8, 3, 7])); // 49 +console.log(maxArea([1, 7, 2, 5, 4, 7, 3, 6])); // 36 +console.log(maxArea([1, 1])); // 1 +console.log(maxArea([2, 2, 2])); // 4 +``` + +```md +Пример 1: + + Ввод: height = [1,8,6,2,5,4,8,3,7] + Вывод: 49 + Объяснение: Вышеуказанные вертикальные линии представлены массивом [1,8,6,2,5,4,8,3,7]. + В этом случае максимальная площадь воды (синяя область), которую может удержать контейнер, равна 49. + + Пример 2: + + Ввод: height = [1,1] + Вывод: 1 +``` + +#leetcode diff --git a/content-ru/leetcode/Array/128-longest-consecutive-sequence.md b/content-ru/leetcode/Array/128-longest-consecutive-sequence.md new file mode 100644 index 0000000000000..ae6b4be019517 --- /dev/null +++ b/content-ru/leetcode/Array/128-longest-consecutive-sequence.md @@ -0,0 +1,69 @@ +# 128. Longest Consecutive Sequence (?) () + +> 128. +> Longest Consecutive Sequence (https://leetcode.com/problems/longest-consecutive-sequence/) Дан неотсортированный массив целых чисел nums, верните длину самой длинной последовательности идущих подряд элементов. +> Необходимо написать алгоритм, работающий за O(n). + +```ts +function longestConsecutive(nums: number[]): number { + let maxCnt = 0, cnt = 1 + const st = new Set(nums) + + for (let i = 0; i < nums.length; i++) { + if (st.has(nums[i] - 1)) continue + for (let j = 1; j < nums.length + 1; j++) { + // является ли число началом последовательности? + if (st.has(nums[i] + j)) { + cnt += 1 + } else { + break + } + } + maxCnt = cnt > maxCnt ? cnt : maxCnt + cnt = 1 + } + return maxCnt +}; + +// O(n^2) brute force +// function longestConsecutive(nums: number[]): number { +// let maxCnt = 0, +// cnt = 1 +// for (let i = 0; i < nums.length; i++) { +// for (let j = 1; j < nums.length - 1; j++) { +// if (nums.includes(nums[i] + j)) { +// cnt += 1 +// } else { +// break +// } +// } +// maxCnt = cnt > maxCnt ? cnt : maxCnt +// cnt = 1 +// } +// return maxCnt +// }; + +// Local check: +console.log(longestConsecutive([100, 4, 200, 1, 3, 2])) // 4 +console.log(longestConsecutive([0, 3, 7, 2, 5, 8, 4, 6, 0, 1])) // 9 +console.log(longestConsecutive([1, 0, 1, 2])) // 3 +``` + +```md +Example 1: + + Input: nums = [100,4,200,1,3,2] + Output: 4 + Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4. + + Example 2: + + Input: nums = [0,3,7,2,5,8,4,6,0,1] + Output: 9 + + Example 3: + Input: nums = [1,0,1,2] + Output: 3 +``` + +#leetcode diff --git a/content-ru/leetcode/Array/1365-how-many-numbers-are-smaller-than-the-current-number.md b/content-ru/leetcode/Array/1365-how-many-numbers-are-smaller-than-the-current-number.md index 8a59e1796659f..38c723eefda81 100644 --- a/content-ru/leetcode/Array/1365-how-many-numbers-are-smaller-than-the-current-number.md +++ b/content-ru/leetcode/Array/1365-how-many-numbers-are-smaller-than-the-current-number.md @@ -1,7 +1,7 @@ -# 1365. How Many Numbers Are Smaller Than the Current Number (Easy) () +# 1365. Сколько чисел меньше текущего числа (Easy) () -> Дан массив nums; для каждого nums[i] нужно найти, сколько чисел в массиве меньше него. -> То есть для каждого nums[i] нужно посчитать количество валидных j, таких что j != i и nums[j] < nums[i]. +> Дан массив nums, для каждого nums[i] найдите, сколько чисел в массиве меньше него. +> То есть для каждого nums[i] нужно посчитать количество допустимых j, таких что j != i и nums[j] < nums[i]. > Верните ответ в виде массива. > Ограничения: - 2 <= nums.length <= 500 - 0 <= nums[i] <= 100 @@ -16,36 +16,36 @@ function smallerNumbersThanCurrent(nums: number[]): number[] { } } - return nums.map((n) => firstIndex.get(n)!) + return nums.map(n => firstIndex.get(n)!) } -// Local check: +// Локальная проверка: console.log(smallerNumbersThanCurrent([8, 1, 2, 2, 3])) console.log(smallerNumbersThanCurrent([6, 5, 4, 8])) console.log(smallerNumbersThanCurrent([7, 7, 7, 7])) ``` ```md -Example 1: +Пример 1: - Input: nums = [8,1,2,2,3] - Output: [4,0,1,1,3] - Explanation: - For nums[0]=8 there exist four smaller numbers than it (1, 2, 2 and 3). - For nums[1]=1 does not exist any smaller number than it. - For nums[2]=2 there exist one smaller number than it (1). - For nums[3]=2 there exist one smaller number than it (1). - For nums[4]=3 there exist three smaller numbers than it (1, 2 and 2). + Вход: nums = [8,1,2,2,3] + Выход: [4,0,1,1,3] + Пояснение: + Для nums[0]=8 существует четыре числа меньше него (1, 2, 2 и 3). + Для nums[1]=1 не существует ни одного числа меньше него. + Для nums[2]=2 существует одно число меньше него (1). + Для nums[3]=2 существует одно число меньше него (1). + Для nums[4]=3 существует три числа меньше него (1, 2 и 2). -Example 2: + Пример 2: - Input: nums = [6,5,4,8] - Output: [2,1,0,3] + Вход: nums = [6,5,4,8] + Выход: [2,1,0,3] -Example 3: + Пример 3: - Input: nums = [7,7,7,7] - Output: [0,0,0,0] + Вход: nums = [7,7,7,7] + Выход: [0,0,0,0] ``` [[leetcode/Array/1431-kids-with-the-greatest-number-of-candies]] diff --git a/content-ru/leetcode/Array/1431-kids-with-the-greatest-number-of-candies.md b/content-ru/leetcode/Array/1431-kids-with-the-greatest-number-of-candies.md index fba172ec5c74f..d33e3885b52a0 100644 --- a/content-ru/leetcode/Array/1431-kids-with-the-greatest-number-of-candies.md +++ b/content-ru/leetcode/Array/1431-kids-with-the-greatest-number-of-candies.md @@ -1,16 +1,16 @@ # 1431. Kids With the Greatest Number of Candies (Easy) () > Есть n детей с конфетами. -> Дан целочисленный массив candies, где candies[i] — количество конфет у i-го ребёнка, и целое число extraCandies — количество дополнительных конфет, которые есть у вас. -> Верните булев массив result длины n, где result[i] равно true, если после того как i-й ребёнок получит все extraCandies, у него будет наибольшее количество конфет среди всех детей, иначе — false. -> Учтите, что наибольшее количество конфет может быть у нескольких детей одновременно. +> Вам дан целочисленный массив candies, где candies[i] обозначает количество конфет у i-го ребёнка, и целое число extraCandies, обозначающее количество дополнительных конфет, которые у вас есть. +> Верните булев массив result длины n, где result[i] равно true, если после того, как i-му ребёнку отдадут все extraCandies, у него будет наибольшее количество конфет среди всех детей, или false в противном случае. +> Обратите внимание, что несколько детей могут иметь наибольшее количество конфет. > Ограничения: n == candies.length 2 <= n <= 100 1 <= candies[i] <= 100 1 <= extraCandies <= 50 ```ts function kidsWithCandies(candies: number[], extraCandies: number): boolean[] { const max = Math.max(...candies) - return candies.map((candy) => candy + extraCandies >= max) -} + return candies.map(candy => candy + extraCandies >= max) +}; // function kidsWithCandies(candies: number[], extraCandies: number): boolean[] { // const sortedCandies = [...candies].sort((a, b) => a - b) @@ -27,7 +27,7 @@ function kidsWithCandies(candies: number[], extraCandies: number): boolean[] { // return result // } -// Local check: +// Локальная проверка: console.log(kidsWithCandies([2, 3, 5, 1, 3], 3)) console.log(kidsWithCandies([4, 2, 1, 1, 2], 1)) console.log(kidsWithCandies([12, 1, 12], 10)) @@ -35,32 +35,30 @@ console.log(kidsWithCandies([1, 10, 10, 3], 1)) ``` ```md -Example 1: +Пример 1: - Input: candies = [2,3,5,1,3], extraCandies = 3 - Output: [true,true,true,false,true] - Explanation: If you give all extraCandies to: - Kid 1, they will have 2 + 3 = 5 candies, which is the greatest among the kids. - Kid 2, they will have 3 + 3 = 6 candies, which is the greatest among the kids. - Kid 3, they will have 5 + 3 = 8 candies, which is the greatest among the kids. - Kid 4, they will have 1 + 3 = 4 candies, which is not the greatest among the kids. - Kid 5, they will have 3 + 3 = 6 candies, which is the greatest among the kids. + Вход: candies = [2,3,5,1,3], extraCandies = 3 + Выход: [true,true,true,false,true] + Объяснение: Если отдать все extraCandies: + Ребёнку 1, у него будет 2 + 3 = 5 конфет, что является наибольшим числом среди детей. + Ребёнку 2, у него будет 3 + 3 = 6 конфет, что является наибольшим числом среди детей. + Ребёнку 3, у него будет 5 + 3 = 8 конфет, что является наибольшим числом среди детей. + Ребёнку 4, у него будет 1 + 3 = 4 конфеты, что не является наибольшим числом среди детей. + Ребёнку 5, у него будет 3 + 3 = 6 конфет, что является наибольшим числом среди детей. -Example 2: - - Input: candies = [4,2,1,1,2], extraCandies = 1 - Output: [true,false,false,false,false] + Пример 2: + Вход: candies = [4,2,1,1,2], extraCandies = 1 + Выход: [true,false,false,false,false] + Объяснение: Есть только 1 дополнительная конфета. + У ребёнка 1 всегда будет наибольшее количество конфет, даже если + дополнительную конфету отдать другому ребёнку. - Explanation: There is only 1 extra candy. - Kid 1 will always have the greatest number of candies, even if a different - kid is given the extra candy. - -Example 3: + Пример 3: - Input: candies = [12,1,12], extraCandies = 10 - Output: [true,false,true] + Вход: candies = [12,1,12], extraCandies = 10 + Выход: [true,false,true] ``` [[leetcode/Array/1365-how-many-numbers-are-smaller-than-the-current-number]] diff --git a/content-ru/leetcode/Array/1441-build-an-array-with-stack-operations.md b/content-ru/leetcode/Array/1441-build-an-array-with-stack-operations.md index 4de9e23af8da2..971103399c885 100644 --- a/content-ru/leetcode/Array/1441-build-an-array-with-stack-operations.md +++ b/content-ru/leetcode/Array/1441-build-an-array-with-stack-operations.md @@ -1,42 +1,41 @@ -# 1441. Build an Array With Stack Operations (Medium) () +# 1441. Построение массива с помощью операций со стеком (Средний уровень) () -> Дан целочисленный массив target и целое число n. -> У вас есть пустой стек с двумя операциями: - "Push": добавляет число на вершину стека. -> -> - "Pop": удаляет число с вершины стека. -> Также у вас есть поток чисел из диапазона [1, n]. -> Используйте эти две операции стека, чтобы числа в стеке (снизу вверх) стали равны target. -> Следуйте правилам: - Если поток чисел не пуст, возьмите следующее число из потока и положите его на вершину стека. -> - Если стек не пуст, удалите число с вершины стека. -> - Если в любой момент элементы в стеке (снизу вверх) равны target, прекратите чтение чисел из потока и операции со стеком. -> Верните операции со стеком, необходимые для построения target по указанным правилам. -> Если существует несколько верных ответов, верните любой из них. -> Ограничения: - 1 <= target.length <= 100 - 1 <= n <= 100 - 1 <= target[i] <= n - target строго возрастает. +> Вам дан целочисленный массив target и целое число n. +> У вас есть пустой стек с двумя следующими операциями: - "Push": добавляет целое число на вершину стека. +> - "Pop": удаляет целое число с вершины стека. +> Также у вас есть поток целых чисел в диапазоне [1, n]. +> Используйте эти две операции со стеком, чтобы числа в стеке (от дна до вершины) стали равны target. +> Вы должны следовать следующим правилам: - Если поток целых чисел не пуст, возьмите следующее целое число из потока и добавьте его на вершину стека. +> - Если стек не пуст, удалите целое число с вершины стека. +> - Если в любой момент элементы в стеке (от дна до вершины) равны target, прекратите чтение новых чисел из потока и не выполняйте больше операций со стеком. +> Верните операции со стеком, необходимые для построения target по указанным правилам. +> Если существует несколько допустимых ответов, верните любой из них. +> Ограничения: - 1 <= target.length <= 100 - 1 <= n <= 100 - 1 <= target[i] <= n - target строго возрастающий. ```ts function buildArray(target: number[], n: number): string[] { - const operations: string[] = [] + const operations: string[] = []; const stack = { items: [] as number[], push(value: number) { - operations.push("Push") - this.items.push(value) + operations.push("Push") + this.items.push(value); }, pop(): number | undefined { operations.push("Pop") - return this.items.pop() - }, + return this.items.pop(); + } } - let currentTargetIndex = 0 + let currentTargetIndex = 0; for (let i = 0; i < n; i++) { if (currentTargetIndex === target.length) { - break + break; } stack.push(i + 1) if (target[currentTargetIndex] !== stack.items[currentTargetIndex]) { - stack.pop() + stack.pop(); } else { currentTargetIndex += 1 } @@ -45,15 +44,14 @@ function buildArray(target: number[], n: number): string[] { return operations } -// Local check: +// Локальная проверка: console.log(buildArray([1, 3], 3)) console.log(buildArray([1, 2, 3], 3)) console.log(buildArray([1, 2], 4)) -console.log(buildArray([1, 2, 3], 3)) +console.log(buildArray([1,2,3], 3)) ``` - ```md Example 1: @@ -65,7 +63,7 @@ Example 1: Pop the integer on the top of the stack. s = [1]. Read 3 from the stream and push it to the stack. s = [1,3]. -Example 2: + Example 2: Input: target = [1,2,3], n = 3 Output: ["Push","Push","Push"] @@ -74,7 +72,7 @@ Example 2: Read 2 from the stream and push it to the stack. s = [1,2]. Read 3 from the stream and push it to the stack. s = [1,2,3]. -Example 3: + Example 3: Input: target = [1,2], n = 4 Output: ["Push","Push"] diff --git a/content-ru/leetcode/Array/1470-shuffle-the-array.md b/content-ru/leetcode/Array/1470-shuffle-the-array.md index 33a9cf8cdd6d3..67c217ae13d8a 100644 --- a/content-ru/leetcode/Array/1470-shuffle-the-array.md +++ b/content-ru/leetcode/Array/1470-shuffle-the-array.md @@ -1,17 +1,17 @@ -# 1470. Shuffle the Array (Easy) () +# 1470. Перемешать массив (Easy) () -> Дан массив nums из 2n элементов в форме [x1,x2,...,xn,y1,y2,...,yn]. -> Верните массив в форме [x1,y1,x2,y2,...,xn,yn]. +> Дан массив nums, состоящий из 2n элементов в виде [x1,x2,...,xn,y1,y2,...,yn]. +> Верните массив в виде [x1,y1,x2,y2,...,xn,yn]. > Ограничения: 1 <= n <= 500 nums.length == 2 * n 1 <= nums[i] <= 10^3 ```ts function shuffle(nums: number[], n: number): number[] { - const result = new Array(n * 2) + const result = new Array(n * 2); for (let i = 0; i < n; i++) { - result[i * 2] = nums[i] - result[i * 2 + 1] = nums[i + n] + result[i * 2] = nums[i]; + result[i * 2 + 1] = nums[i + n]; } - return result + return result; } // Local check: @@ -27,12 +27,12 @@ Example 1: 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 2: + Example 2: Input: nums = [1,2,3,4,4,3,2,1], n = 4 Output: [1,4,2,3,3,2,4,1] -Example 3: + Example 3: Input: nums = [1,1,2,2], n = 2 Output: [1,2,1,2] diff --git a/content-ru/leetcode/Array/1475-final-prices-with-a-special-discount-in-a-shop.md b/content-ru/leetcode/Array/1475-final-prices-with-a-special-discount-in-a-shop.md index 5809d1cdc67ec..a44ac11f01ec0 100644 --- a/content-ru/leetcode/Array/1475-final-prices-with-a-special-discount-in-a-shop.md +++ b/content-ru/leetcode/Array/1475-final-prices-with-a-special-discount-in-a-shop.md @@ -1,10 +1,10 @@ -# 1475. Final Prices With a Special Discount in a Shop (Easy) () +# 1475. Итоговые цены с особой скидкой в магазине (Easy) () > Дан целочисленный массив prices, где prices[i] — цена i-го товара в магазине. -> В магазине действует специальная скидка на товары. +> В магазине действует особая скидка на товары. > Если вы покупаете i-й товар, вы получите скидку, равную prices[j], где j — минимальный индекс такой, что j > i и prices[j] <= prices[i]. -> В противном случае скидки не будет вовсе. -> Верните целочисленный массив answer, где answer[i] — итоговая цена, которую вы заплатите за i-й товар с учётом специальной скидки. +> В противном случае вы не получите никакой скидки. +> Верните целочисленный массив answer, где answer[i] — итоговая цена, которую вы заплатите за i-й товар магазина с учётом особой скидки. > Ограничения: 1 <= prices.length <= 500 1 <= prices[i] <= 1000 ```ts @@ -14,6 +14,7 @@ function finalPrices(prices: number[]): number[] { for (let i = 0; i < prices.length; i++) { discounted[i] = prices[i]; + // i является скидкой для тех в стеке, чья цена >= prices[i] while (stack.length > 0 && prices[stack.at(-1)!] >= prices[i]) { const topIdx = stack.pop()!; @@ -27,6 +28,7 @@ function finalPrices(prices: number[]): number[] { /* v2 */ function finalPrices2(prices: number[]): number[] { const answer: number[] = []; + for (let i = 0; i < prices.length; i++) { for (let j = i + 1; j < prices.length; j++) { if (j > i && prices[j] <= prices[i]) { @@ -41,31 +43,37 @@ function finalPrices2(prices: number[]): number[] { return answer; } -// Local check: +// Локальная проверка: console.log(finalPrices([8, 4, 6, 2, 3])); console.log(finalPrices([1, 2, 3, 4, 5])); console.log(finalPrices([10, 1, 1, 6])); - ``` ```md Example 1: -Input: prices = [8,4,6,2,3] -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. -For 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. -For 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. -For items 3 and 4 you will not receive any discount at all. -Example 2: -Input: prices = [1,2,3,4,5] -Output: [1,2,3,4,5] -Explanation: In this case, for all items, you will not receive any discount at all. -Example 3: -Input: prices = [10,1,1,6] -Output: [9,0,1,6] + Input: prices = [8,4,6,2,3] + 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. + For 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. + For 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. + For items 3 and 4 you will not receive any discount at all. + + Example 2: + + Input: prices = [1,2,3,4,5] + Output: [1,2,3,4,5] + Explanation: In this case, for all items, you will not receive any discount at all. + + Example 3: + + Input: prices = [10,1,1,6] + Output: [9,0,1,6] ``` [[leetcode/Array/1470-shuffle-the-array]] diff --git a/content-ru/leetcode/Array/15-3sum.md b/content-ru/leetcode/Array/15-3sum.md new file mode 100644 index 0000000000000..ade85d48f7c28 --- /dev/null +++ b/content-ru/leetcode/Array/15-3sum.md @@ -0,0 +1,76 @@ +# 15. 3Sum (Medium) () + +> Дан массив целых чисел nums, верните все триплеты [nums[i], nums[j], nums[k]] такие, что i != j, i != k, и j != k, и nums[i] + nums[j] + nums[k] == 0. +> Набор решений не должен содержать дублирующихся триплетов. +> Вы можете вернуть результат в любом порядке. +> Ограничения: 3 <= nums.length <= 3000 -10^5 <= nums[i] <= 10^5 + +```ts +function threeSum(nums: number[]): number[][] { + const triplets: number[][] = [] + nums.sort((a, b) => a - b); + + for (let i = 0; i < nums.length; i++) { + let leftIdx = i + 1, rightIdx = nums.length - 1; + if (i > 0 && nums[i] === nums[i - 1]) continue + + while (leftIdx < rightIdx) { + const sm = nums[i] + nums[leftIdx] + nums[rightIdx] + + if (sm === 0) { + triplets.push([nums[i], nums[leftIdx], nums[rightIdx]]) + + leftIdx++ + rightIdx-- + + // пропускаем одинаковые left значения + while ( + leftIdx < rightIdx && + nums[leftIdx] === nums[leftIdx - 1] + ) { + leftIdx++ + } + + // пропускаем одинаковые right значения + while ( + leftIdx < rightIdx && + nums[rightIdx] === nums[rightIdx + 1] + ) { + rightIdx-- + } + + } else if (sm > 0) { + rightIdx-- + } else { + leftIdx++ + } + } + } + + return triplets +} + +// Local check: +console.log(threeSum([-1, 0, 1, 2, -1, -4])) +console.log(threeSum([0, 1, 1])) +console.log(threeSum([0, 0, 0])) +``` + +```md +Пример 1: + + Вход: nums = [-1,0,1,2,-1,-4] + Выход: [[-1,-1,2],[-1,0,1]] + + Пример 2: + + Вход: nums = [0,1,1] + Выход: [] + + Пример 3: + + Вход: nums = [0,0,0] + Выход: [[0,0,0]] +``` + +#leetcode diff --git a/content-ru/leetcode/Array/150-evaluate-reverse-polish-notation.md b/content-ru/leetcode/Array/150-evaluate-reverse-polish-notation.md index 76af45eb5c646..a22419b7aae03 100644 --- a/content-ru/leetcode/Array/150-evaluate-reverse-polish-notation.md +++ b/content-ru/leetcode/Array/150-evaluate-reverse-polish-notation.md @@ -1,14 +1,14 @@ -# 150. Evaluate Reverse Polish Notation (Medium) () +# 150. Вычисление выражения в обратной польской записи (Medium) () -> Дан массив строк tokens, представляющий арифметическое выражение в обратной польской записи. -> Вычислите выражение. -> Верните целое число — значение выражения. -> Учтите, что: • Допустимые операторы: '+', '-', '*' и '/'. -> • Каждый операнд может быть числом или другим выражением. -> • Деление двух целых чисел всегда округляется в сторону нуля. +> Вам дан массив строк tokens, представляющий арифметическое выражение в обратной польской записи. +> Вычислите значение выражения. +> Верните целое число, представляющее результат вычисления. +> Обратите внимание: • Допустимые операторы: '+', '-', '*' и '/'. +> • Каждый операнд может быть целым числом или другим выражением. +> • Деление между двумя целыми числами всегда усекается в сторону нуля. > • Деления на ноль не будет. > • Входные данные представляют собой корректное арифметическое выражение в обратной польской записи. -> • Ответ и все промежуточные вычисления можно представить 32-битным целым числом. +> • Ответ и все промежуточные вычисления могут быть представлены 32-битным целым числом. ```ts const ops: Record number> = { @@ -16,27 +16,44 @@ const ops: Record number> = { "-": (a, b) => a - b, "*": (a, b) => a * b, "/": (a, b) => Math.trunc(a / b), -} +}; function evalRPN(tokens: string[]): number { - const stack: number[] = [] + const stack: number[] = []; for (const token of tokens) { if (token in ops) { - const right = stack.pop()! - const left = stack.pop()! - stack.push(ops[token](left, right)) + const right = stack.pop()!; + const left = stack.pop()!; + stack.push(ops[token](left, right)); } else { - stack.push(Number(token)) + stack.push(Number(token)); } } - return stack[0] + return stack[0]; } // Local check: -console.log(evalRPN(["2", "1", "+", "3", "*"])) // 9 -console.log(evalRPN(["4", "13", "5", "/", "+"])) // 6 -console.log(evalRPN(["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"])) // 22 +console.log(evalRPN(["1", "2", "+", "3", "*", "4", "-"])); // 5 +console.log(evalRPN(["2", "1", "+", "3", "*"])); // 9 +console.log(evalRPN(["4", "13", "5", "/", "+"])); // 6 +console.log( + evalRPN([ + "10", + "6", + "9", + "3", + "+", + "-11", + "*", + "/", + "*", + "17", + "+", + "5", + "+", + ]), +); // 22 ``` ```md @@ -46,13 +63,13 @@ Example 1: Output: 9 Explanation: ((2 + 1) * 3) = 9 -Example 2: + Example 2: Input: tokens = ["4","13","5","/","+"] Output: 6 Explanation: (4 + (13 / 5)) = 6 -Example 3: + Example 3: Input: tokens = ["10","6","9","3","+","-11","*","/","*","17","+","5","+"] Output: 22 diff --git a/content-ru/leetcode/Array/217-contains-duplicate.md b/content-ru/leetcode/Array/217-contains-duplicate.md index 44d8688acde46..85742f446c22c 100644 --- a/content-ru/leetcode/Array/217-contains-duplicate.md +++ b/content-ru/leetcode/Array/217-contains-duplicate.md @@ -1,21 +1,21 @@ # 217. Contains Duplicate (Easy) () -> Дан целочисленный массив nums, верните true, если какое-либо значение встречается в массиве хотя бы дважды, и false, если все элементы различны. +> Дан массив целых чисел nums, верните true, если какое-либо значение встречается в массиве хотя бы дважды, и false, если все элементы различны. > Ограничения: 1 <= nums.length <= 10^5 -10^9 <= nums[i] <= 10^9 ```ts function containsDuplicate(nums: number[]): boolean { - const st = new Set() - for (const num of nums) { - if (st.has(num)) { - return true + const st = new Set() + for (const num of nums) { + if (st.has(num)) { + return true + } + st.add(num) } - st.add(num) - } - return false + return false } -// Local check: +// Локальная проверка: console.log(containsDuplicate([1, 2, 3, 1])) // true console.log(containsDuplicate([1, 2, 3, 4])) // false console.log(containsDuplicate([1, 1, 1, 3, 3, 4, 3, 2, 4, 2])) // true @@ -23,18 +23,21 @@ console.log(containsDuplicate([1, 1, 1, 3, 3, 4, 3, 2, 4, 2])) // true ```md Example 1: -Input: nums = [1,2,3,1] -Output: true -Explanation: The element 1 occurs at the indices 0 and 3. - -Example 2: -Input: nums = [1,2,3,4] -Output: false -Explanation: All elements are distinct. - -Example 3: -Input: nums = [1,1,1,3,3,4,3,2,4,2] -Output: true + + Input: nums = [1,2,3,1] + Output: true + Explanation: The element 1 occurs at the indices 0 and 3. + + Example 2: + + Input: nums = [1,2,3,4] + Output: false + Explanation: All elements are distinct. + + Example 3: + + Input: nums = [1,1,1,3,3,4,3,2,4,2] + Output: true ``` [[leetcode/Array/index|array]] diff --git a/content-ru/leetcode/Array/238-product-of-array-except-self.md b/content-ru/leetcode/Array/238-product-of-array-except-self.md new file mode 100644 index 0000000000000..10ac1f83e6a62 --- /dev/null +++ b/content-ru/leetcode/Array/238-product-of-array-except-self.md @@ -0,0 +1,54 @@ +# 238. Произведение массива, кроме самого себя (Medium) () + +> Дан целочисленный массив nums, верните массив answer такой, что answer[i] равен произведению всех элементов nums, кроме nums[i]. +> Гарантируется, что произведение любого префикса или суффикса nums помещается в 32-битное целое число. +> Вы должны написать алгоритм, работающий за O(n) и без использования операции деления. +> Ограничения: - 2 <= nums.length <= 10^5 - -30 <= nums[i] <= 30 - Входные данные сгенерированы так, что answer[i] гарантированно помещается в 32-битное целое число. +> Дополнительно: Сможете ли вы решить задачу с O(1) дополнительной памяти? (Выходной массив не учитывается при анализе сложности по памяти.) + +```ts +function productExceptSelf(nums: number[]): number[] { + let leftProduct = 1, + rightProduct = 1; + const answer: number[] = []; + + for (let i = 0; i < nums.length; i++) { + answer.push(leftProduct); + leftProduct *= nums[i]; + } + + for (let i = nums.length - 1; i > -1; i--) { + answer[i] *= rightProduct; + rightProduct *= nums[i]; + } + + return answer; +} + +// Local check: +console.log(productExceptSelf([1, 2, 3, 4])); // [24, 12, 8, 6] +console.log(productExceptSelf([-1, 1, 0, -3, 3])); // [0, 0, 9, 0, 0] +``` + +```md +Example 1: + Input: nums = [1,2,3,4] + Output: [24,12,8,6] + Explanation: + - answer[0] = 2 * 3 * 4 = 24 + - answer[1] = 1 * 3 * 4 = 12 + - answer[2] = 1 * 2 * 4 = 8 + - answer[3] = 1 * 2 * 3 = 6 + + Example 2: + Input: nums = [-1,1,0,-3,3] + Output: [0,0,9,0,0] + Explanation: + - answer[0] = 1 * 0 * -3 * 3 = 0 + - answer[1] = -1 * 0 * -3 * 3 = 0 + - answer[2] = -1 * 1 * -3 * 3 = 9 + - answer[3] = -1 * 1 * 0 * 3 = 0 + - answer[4] = -1 * 1 * 0 * -3 = 0 +``` + +#leetcode diff --git a/content-ru/leetcode/Array/268-missing-number.md b/content-ru/leetcode/Array/268-missing-number.md index 9b1c3c309ca45..052d395e796e2 100644 --- a/content-ru/leetcode/Array/268-missing-number.md +++ b/content-ru/leetcode/Array/268-missing-number.md @@ -1,43 +1,44 @@ -# 268. Missing Number (Easy) () - -> Дан массив nums, содержащий n различных чисел из диапазона [0, n], верните единственное число из диапазона, отсутствующее в массиве. +# 268. Отсутствующее число (Easy) () +> Дан массив nums, содержащий n различных чисел в диапазоне [0, n], верните единственное число из этого диапазона, которое отсутствует в массиве. > Ограничения: n == nums.length 1 <= n <= 10^4 0 <= nums[i] <= n Все числа в nums уникальны. - -> Дополнительно: сможете ли вы реализовать решение с O(1) дополнительной памяти и O(n) временем выполнения? +> Дополнительно: сможете ли вы реализовать решение, используя только O(1) дополнительной памяти и O(n) времени выполнения? ```ts function missingNumber(nums: number[]): number { - const n = nums.length - const expectedSum = (n * (n + 1)) / 2 - const actualSum = nums.reduce((acc, num) => acc + num, 0) - return expectedSum - actualSum + const n = nums.length; + const expectedSum = (n * (n + 1)) / 2; + const actualSum = nums.reduce((acc, num) => acc + num, 0); + return expectedSum - actualSum; } // Local check: -console.log(missingNumber([3, 0, 1])) -console.log(missingNumber([0, 1])) -console.log(missingNumber([9, 6, 4, 2, 3, 5, 7, 0, 1])) +console.log(missingNumber([3, 0, 1])); +console.log(missingNumber([0, 1])); +console.log(missingNumber([9, 6, 4, 2, 3, 5, 7, 0, 1])); ``` ```md Example 1: -Input: nums = [3,0,1] -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 2: -Input: nums = [0,1] -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 3: -Input: nums = [9,6,4,2,3,5,7,0,1] -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. + + Input: nums = [3,0,1] + 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 2: + + Input: nums = [0,1] + 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 3: + + Input: nums = [9,6,4,2,3,5,7,0,1] + 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. ``` [[leetcode/Array/150-evaluate-reverse-polish-notation]] diff --git a/content-ru/leetcode/Array/283-move-zeroes.md b/content-ru/leetcode/Array/283-move-zeroes.md index ef0b9c9a6ccb6..271b1724039dd 100644 --- a/content-ru/leetcode/Array/283-move-zeroes.md +++ b/content-ru/leetcode/Array/283-move-zeroes.md @@ -1,43 +1,44 @@ -#lcpatterns/slow-fast-pointer - # 283. Move Zeroes (Easy) () -> Дан целочисленный массив nums, переместите все нули в конец массива, сохраняя относительный порядок ненулевых элементов. -> Учтите, что делать это нужно на месте, без создания копии массива. -> Ограничения: 1 <= nums.length <= 10^4 -2^31 <= nums[i] <= 2^31 - 1 Дополнительно: сможете ли вы минимизировать количество операций? +> Дан целочисленный массив nums, переместите все 0 в его конец, сохраняя относительный порядок ненулевых элементов. +> Обратите внимание, что вы должны сделать это на месте, не создавая копию массива. +> Ограничения: 1 <= nums.length <= 10^4 -2^31 <= nums[i] <= 2^31 - 1 Дополнительное задание: Сможете ли вы минимизировать общее количество операций? ```ts function moveZeroes(nums: number[]): void { - let left = 0 - let right = left + let left = 0; + let right = left; while (right !== nums.length) { if (nums[right] !== 0) { if (right !== left) { - const temp = nums[left] - nums[left] = nums[right] - nums[right] = temp + const temp = nums[left]; + nums[left] = nums[right]; + nums[right] = temp; } - right++ - left++ + right++; + left++; } else { - right++ + right++; } } } // Local check: -console.log(moveZeroes([0, 1, 0, 3, 12])) -console.log(moveZeroes([0])) -console.log(moveZeroes([0, 1, 2, 3, 0])) +console.log(moveZeroes([0, 1, 0, 3, 12])); +console.log(moveZeroes([0])); +console.log(moveZeroes([0, 1, 2, 3, 0])); ``` ```md Example 1: -Input: nums = [0,1,0,3,12] -Output: [1,3,12,0,0] -Example 2: -Input: nums = [0] -Output: [0] + + Input: nums = [0,1,0,3,12] + Output: [1,3,12,0,0] + + Example 2: + + Input: nums = [0] + Output: [0] ``` [[leetcode/Array/268-missing-number]] diff --git a/content-ru/leetcode/Array/347-top-k-frequent-elements.md b/content-ru/leetcode/Array/347-top-k-frequent-elements.md index 2f3618010d2c5..303ea6716d9ea 100644 --- a/content-ru/leetcode/Array/347-top-k-frequent-elements.md +++ b/content-ru/leetcode/Array/347-top-k-frequent-elements.md @@ -1,7 +1,7 @@ # 347. Top K Frequent Elements (Medium) () -> Дан целочисленный массив nums и целое число k, верните k самых частых элементов. -> Порядок ответа может быть любым. +> Дан массив целых чисел nums и целое число k, верните k наиболее часто встречающихся элементов. +> Ответ можно вернуть в любом порядке. > Ограничения: - 1 <= nums.length <= 10^5 - -10^4 <= nums[i] <= 10^4 - k находится в диапазоне [1, количество уникальных элементов в массиве] - гарантируется, что ответ единственный ```ts @@ -11,6 +11,7 @@ function topKFrequent(nums: number[], k: number): number[] { for (const num of nums) { freq.set(num, (freq.get(num) ?? 0) + 1) } + return Array.from(freq.entries()) .sort((a, b) => b[1] - a[1]) // сортируем по частоте .slice(0, k) @@ -18,24 +19,28 @@ function topKFrequent(nums: number[], k: number): number[] { } // Local check: -console.log(topKFrequent([1, 1, 1, 2, 2, 3], 2)) +console.log(topKFrequent([1,1,1,2,2,3], 2)) +console.log(topKFrequent([7,7], 1)) console.log(topKFrequent([1], 1)) -console.log(topKFrequent([1, 2, 1, 2, 1, 2, 3, 1, 3, 2], 2)) +console.log(topKFrequent([1,2,1,2,1,2,3,1,3,2], 2)) ``` ```md Example 1: -Input: nums = [1,1,1,2,2,3], k = 2 -Output: [1,2] -Explanation: The values 1 and 2 appear most frequently. -Example 2: -Input: nums = [1], k = 1 -Output: [1] + Input: nums = [1,1,1,2,2,3], k = 2 + Output: [1,2] + Explanation: The values 1 and 2 appear most frequently. + + Example 2: + + Input: nums = [1], k = 1 + Output: [1] + + Example 3: -Example 3: -Input: nums = [1,2,1,2,1,2,3,1,3,2], k = 2 -Output: [1,2] + Input: nums = [1,2,1,2,1,2,3,1,3,2], k = 2 + Output: [1,2] ``` [[leetcode/Array/index|array]] diff --git a/content-ru/leetcode/Array/36-valid-sudoku.md b/content-ru/leetcode/Array/36-valid-sudoku.md new file mode 100644 index 0000000000000..4da6f8dd46e5c --- /dev/null +++ b/content-ru/leetcode/Array/36-valid-sudoku.md @@ -0,0 +1,88 @@ +# 36. Valid Sudoku (Medium) () + +> Определите, является ли доска 9 x 9 для судоку допустимой. +> Проверять нужно только заполненные ячейки согласно следующим правилам: 1. +> Каждая строка должна содержать цифры 1-9 без повторений. +> 2. +> Каждый столбец должен содержать цифры 1-9 без повторений. +> 3. +> Каждый из девяти квадратов 3 x 3 сетки должен содержать цифры 1-9 без повторений. +> Примечание: - Доска судоку (частично заполненная) может быть допустимой, но не обязательно разрешимой. +> - Проверять по указанным правилам нужно только заполненные ячейки. +> Ограничения: - board.length == 9 - board[i].length == 9 - board[i][j] это цифра 1-9 или '.'. + +```ts +function isValidSudoku(board: string[][]): boolean { + const rowSet = new Set(); + const colSets: Set[] = Array.from( + { length: 9 }, + () => new Set(), + ); + const squareSets: Set[] = Array.from( + { length: 9 }, + () => new Set(), + ); + + for (let i = 0; i < board.length; i++) { + for (let j = 0; j < board[i].length; j++) { + if (board[i][j] === ".") continue; + // column + if (colSets[j].has(board[i][j])) return false; + colSets[j].add(board[i][j]); + // row + if (rowSet.has(board[i][j])) return false; + rowSet.add(board[i][j]); + // square + const squareIndex = Math.floor(i / 3) * 3 + Math.floor(j / 3); + if (squareSets[squareIndex].has(board[i][j])) return false; + squareSets[squareIndex].add(board[i][j]); + } + rowSet.clear(); + } + return true; +} + +// Локальная проверка: +console.log( + isValidSudoku([ + ["5", "3", ".", ".", "7", ".", ".", ".", "."], + ["6", ".", ".", "1", "9", "5", ".", ".", "."], + [".", "9", "8", ".", ".", ".", ".", "6", "."], + ["8", ".", ".", ".", "6", ".", ".", ".", "3"], + ["4", ".", ".", "8", ".", "3", ".", ".", "1"], + ["7", ".", ".", ".", "2", ".", ".", ".", "6"], + [".", "6", ".", ".", ".", ".", "2", "8", "."], + [".", ".", ".", "4", "1", "9", ".", ".", "5"], + [".", ".", ".", ".", "8", ".", ".", "7", "9"], + ]), +); // true + +console.log( + isValidSudoku([ + ["8", "3", ".", ".", "7", ".", ".", ".", "."], + ["6", ".", ".", "1", "9", "5", ".", ".", "."], + [".", "9", "8", ".", ".", ".", ".", "6", "."], + ["8", ".", ".", ".", "6", ".", ".", ".", "3"], + ["4", ".", ".", "8", ".", "3", ".", ".", "1"], + ["7", ".", ".", ".", "2", ".", ".", ".", "6"], + [".", "6", ".", ".", ".", ".", "2", "8", "."], + [".", ".", ".", "4", "1", "9", ".", ".", "5"], + [".", ".", ".", ".", "8", ".", ".", "7", "9"], + ]), +); // false +``` + +```md +Пример 1: + + Ввод: board = [["5","3",".",".","7",".",".",".","."],["6",".",".","1","9","5",".",".","."],[".","9","8",".",".",".",".","6","."],["8",".",".",".","6",".",".",".","3"],["4",".",".","8",".","3",".",".","1"],["7",".",".",".","2",".",".",".","6"],[".","6",".",".",".",".","2","8","."],[".",".",".","4","1","9",".",".","5"],[".",".",".",".","8",".",".","7","9"]] + Вывод: true + + Пример 2: + + Ввод: board = [["8","3",".",".","7",".",".",".","."],["6",".",".","1","9","5",".",".","."],[".","9","8",".",".",".",".","6","."],["8",".",".",".","6",".",".",".","3"],["4",".",".","8",".","3",".",".","1"],["7",".",".",".","2",".",".",".","6"],[".","6",".",".",".",".","2","8","."],[".",".",".","4","1","9",".",".","5"],[".",".",".",".","8",".",".","7","9"]] + Вывод: false + Объяснение: То же, что и в примере 1, за исключением того, что 5 в левом верхнем углу изменена на 8. Поскольку в левом верхнем квадрате 3x3 есть две восьмёрки, доска недопустима. +``` + +#leetcode diff --git a/content-ru/leetcode/Array/448-find-all-numbers-disappeared-in-an-array.md b/content-ru/leetcode/Array/448-find-all-numbers-disappeared-in-an-array.md index 58b2df1c5136a..44f48952160dd 100644 --- a/content-ru/leetcode/Array/448-find-all-numbers-disappeared-in-an-array.md +++ b/content-ru/leetcode/Array/448-find-all-numbers-disappeared-in-an-array.md @@ -1,7 +1,7 @@ # 448. Find All Numbers Disappeared in an Array (Easy) () -> Дан массив nums из n целых чисел, где nums[i] находится в диапазоне [1, n], верните массив всех чисел из диапазона [1, n], которые не встречаются в nums. -> Ограничения: - n == nums.length - 1 <= n <= 10^5 - 1 <= nums[i] <= n Дополнительно: сможете ли вы сделать это без дополнительной памяти за O(n)? Считайте, что возвращаемый список не считается дополнительной памятью. +> Дан массив nums из n целых чисел, где nums[i] находится в диапазоне [1, n]. Верните массив всех целых чисел из диапазона [1, n], которые не встречаются в nums. +> Ограничения: - n == nums.length - 1 <= n <= 10^5 - 1 <= nums[i] <= n Дополнительно: сможете ли вы решить задачу без дополнительной памяти и за O(n) времени выполнения? Считайте, что возвращаемый список не учитывается как дополнительная память. ```ts function findDisappearedNumbers(nums: number[]): number[] { @@ -31,15 +31,15 @@ console.log(findDisappearedNumbers([1, 1])) ``` ```md -Example 1: +Пример 1: - Input: nums = [4,3,2,7,8,2,3,1] - Output: [5,6] + Ввод: nums = [4,3,2,7,8,2,3,1] + Вывод: [5,6] -Example 2: + Пример 2: - Input: nums = [1,1] - Output: [2] + Ввод: nums = [1,1] + Вывод: [2] ``` [[leetcode/Array/283-move-zeroes]] diff --git a/content-ru/leetcode/Array/485-max-consecutive-ones.md b/content-ru/leetcode/Array/485-max-consecutive-ones.md index 4a8b677756aff..23cf55f0906f1 100644 --- a/content-ru/leetcode/Array/485-max-consecutive-ones.md +++ b/content-ru/leetcode/Array/485-max-consecutive-ones.md @@ -1,7 +1,7 @@ # 485. Max Consecutive Ones (Easy) () -> Дан бинарный массив nums, верните максимальное количество подряд идущих единиц в массиве. -> Ограничения: 1 <= nums.length <= 10^5 nums[i] равно 0 или 1. +> Дан бинарный массив nums, верните максимальное количество последовательных единиц в массиве. +> Ограничения: 1 <= nums.length <= 10^5 nums[i] равен либо 0, либо 1. ```ts function findMaxConsecutiveOnes(nums: number[]): number { @@ -10,8 +10,10 @@ function findMaxConsecutiveOnes(nums: number[]): number { for (const n of nums) { if (n === 1) { cnt += 1 - if (cnt > maxCnt) maxCnt = cnt - } else { + if (cnt > maxCnt) + maxCnt = cnt + } + else { cnt = 0 } } @@ -31,7 +33,7 @@ Example 1: Explanation: The first two digits or the last three digits are consecutive 1s. The maximum number of consecutive 1s is 3. -Example 2: + Example 2: Input: nums = [1,0,1,1,0,1] Output: 2 diff --git a/content-ru/leetcode/Array/49-group-anagrams.md b/content-ru/leetcode/Array/49-group-anagrams.md index 71da718cf09ee..b529531949f6b 100644 --- a/content-ru/leetcode/Array/49-group-anagrams.md +++ b/content-ru/leetcode/Array/49-group-anagrams.md @@ -1,72 +1,73 @@ -# 49. Group Anagrams (Medium) () +# 49. Группировка анаграмм (Medium) () -> Example 1: Input: `['eat','tea','tan','ate','nat','bat']` Output: `[['bat'],['nat','tan'],['eat','tea','ate']]` Explanation: ... -> Example 2: Input: `['']` Output: `[['']]` Explanation: ... -> Example 3: Input: `['a']` Output: `[['a']]` Explanation: ... +> Пример 1: Ввод: ['eat','tea','tan','ate','nat','bat'] Вывод: [['bat'],['nat','tan'],['eat','tea','ate']] Объяснение: ... +> Пример 2: Ввод: [''] Вывод: [['']] Объяснение: ... +> Пример 3: Ввод: ['a'] Вывод: [['a']] Объяснение: ... ```ts function groupAnagrams(strs: string[]): string[][] { - if (strs.length === 1) return [strs] - const group = new Map() + if (strs.length === 1) return [strs] - for (const ch of strs) { - const curr = ch.split("").sort().join("") - const currVal: string[] | undefined = group.get(curr) + const group = new Map() - if (currVal === undefined) { - group.set(curr, [ch]) - } else { - currVal.push(ch) - group.set(curr, currVal) + for (const ch of strs) { + const curr = ch.split('').sort().join('') + const currVal: string[] | undefined = group.get(curr) + if (currVal === undefined) { + group.set(curr, [ch]) + } else { + currVal.push(ch) + group.set(curr, currVal) + } } - } - return Array.from(group.values()) + return Array.from(group.values()) } // by charCode [O(n)] -function groupAnagrams2(strs: string[]): string[][] { - if (strs.length === 1) return [strs] - const mp = new Map() +// function groupAnagrams(strs: string[]): string[][] { +// if (strs.length === 1) return [strs] - for (const ch of strs) { - const count = new Array(26).fill(0) +// const mp = new Map() - for (const c of ch) { - count[c.charCodeAt(0) - 97]++ - } - - const countStr = count.join("#") - const currVal = mp.get(countStr) +// for (const ch of strs) { +// const count = new Array(26).fill(0) +// for (const c of ch) { +// count[c.charCodeAt(0) - 97]++ +// } +// const countStr = count.join('#') +// const currVal = mp.get(countStr) +// if (currVal === undefined) { +// mp.set(countStr, [ch]) +// } else { +// currVal.push(ch) +// mp.set(countStr, currVal) +// } +// } - if (currVal === undefined) { - mp.set(countStr, [ch]) - } else { - currVal.push(ch) - mp.set(countStr, currVal) - } - } - return Array.from(mp.values()) -} +// return Array.from(mp.values()) +// } // Local check: -console.log(groupAnagrams(["eat", "tea", "tan", "ate", "nat", "bat"])) -console.log(groupAnagrams([""])) -console.log(groupAnagrams(["a"])) +console.log(groupAnagrams(['eat','tea','tan','ate','nat','bat'])); +console.log(groupAnagrams([''])); +console.log(groupAnagrams(['a'])); ``` ```md Example 1: - Input: ['eat','tea','tan','ate','nat','bat'] - Output: [['bat'],['nat','tan'],['eat','tea','ate']] - Explanation: ... -Example 2: - Input: [''] - Output: [['']] - Explanation: ... -Example 3: - Input: ['a'] - Output: [['a']] - Explanation: ... + Input: ['eat','tea','tan','ate','nat','bat'] + Output: [['bat'],['nat','tan'],['eat','tea','ate']] + Explanation: ... + + Example 2: + Input: [''] + Output: [['']] + Explanation: ... + + Example 3: + Input: ['a'] + Output: [['a']] + Explanation: ... ``` [[leetcode/Array/index|array]] diff --git a/content-ru/leetcode/Array/496-next-greater-element-i.md b/content-ru/leetcode/Array/496-next-greater-element-i.md new file mode 100644 index 0000000000000..e9798b51cc716 --- /dev/null +++ b/content-ru/leetcode/Array/496-next-greater-element-i.md @@ -0,0 +1,60 @@ +# 496. Next Greater Element I (Easy) () + +> Следующий больший элемент для некоторого элемента x в массиве — это первый больший элемент, находящийся справа от x в том же массиве. +> Даны два различных 0-индексированных целочисленных массива nums1 и nums2, где nums1 является подмножеством nums2. +> Для каждого 0 <= i < nums1.length найдите индекс j такой, что nums1[i] == nums2[j], и определите следующий больший элемент для nums2[j] в nums2. +> Если следующего большего элемента нет, ответом для этого запроса будет -1. +> Верните массив длины nums1.length такой, что ans[i] — это следующий больший элемент, как описано выше. +> Ограничения: - 1 <= nums1.length <= nums2.length <= 1000 - 0 <= nums1[i], nums2[i] <= 10^4 - Все целые числа в nums1 и nums2 уникальны. +> - Все целые числа из nums1 также присутствуют в nums2. +> Дополнительный вопрос: Сможете ли вы найти решение с O(nums1.length + nums2.length)? + +```ts +function nextGreaterElement(nums1: number[], nums2: number[]): number[] { + const stack: number[] = []; // LIFO; хранит числа, ещё не нашедшие next greater + const nextGreaters: Record = {}; // где ключ — число из nums2, значение — его next greater element + + for (let i = 0; i < nums2.length; i++) { + const curr = nums2[i]; + + // При новом числе — пока оно больше вершины стека, выталкивай вершину и записывай в map map[вершина] = новое_число + while (curr > stack[stack.length - 1] && stack.length > 0) { + nextGreaters[stack.pop()!] = curr; + } + + stack.push(curr); + } + + const result = []; + for (let i = 0; i < nums1.length; i++) { + result.push(nextGreaters[nums1[i]] ?? -1); + } + + return result; +} + +// Local check: +console.log(nextGreaterElement([4, 1, 2], [1, 3, 4, 2])); // [-1,3,-1] +console.log(nextGreaterElement([2, 4], [1, 2, 3, 4])); // [3,-1] +``` + +```md +Example 1: + + Input: nums1 = [4,1,2], nums2 = [1,3,4,2] + Output: [-1,3,-1] + Explanation: + 4 is in nums2 = [1,3,4,2]. There is no next greater element, so the answer is -1. + 1 is in nums2 = [1,3,4,2]. The next greater element is 3. + 2 is in nums2 = [1,3,4,2]. There is no next greater element, so the answer is -1. + + Example 2: + + Input: nums1 = [2,4], nums2 = [1,2,3,4] + Output: [3,-1] + Explanation: + 2 is in nums2 = [1,2,3,4]. The next greater element is 3. + 4 is in nums2 = [1,2,3,4]. There is no next greater element, so the answer is -1. +``` + +#leetcode diff --git a/content-ru/leetcode/Array/605-can-place-flowers.md b/content-ru/leetcode/Array/605-can-place-flowers.md index 4dd1aaf89ccb4..b785a44d46c90 100644 --- a/content-ru/leetcode/Array/605-can-place-flowers.md +++ b/content-ru/leetcode/Array/605-can-place-flowers.md @@ -1,8 +1,8 @@ # 605. Can Place Flowers (Easy) () -> У вас есть длинная клумба, часть участков которой засажена, а часть — нет. +> У вас есть длинная клумба, на которой некоторые участки засажены, а некоторые — нет. > Однако цветы нельзя сажать на соседних участках. -> Дан целочисленный массив flowerbed из 0 и 1, где 0 означает пустой участок, а 1 — занятый, и целое число n; верните true, если можно посадить n новых цветов на клумбе, не нарушая правило "без соседних цветов", и false в противном случае. +> Дан целочисленный массив flowerbed, содержащий 0 и 1, где 0 означает пустой участок, а 1 — занятый, и целое число n. Верните true, если можно посадить n новых цветов на клумбе, не нарушая правило отсутствия соседних цветов, и false в противном случае. > Ограничения: 1 <= flowerbed.length <= 2 * 10^4 flowerbed[i] равно 0 или 1. > В flowerbed нет двух соседних цветов. > 0 <= n <= flowerbed.length @@ -38,7 +38,7 @@ Example 1: Input: flowerbed = [1,0,0,0,1], n = 1 Output: true -Example 2: + Example 2: Input: flowerbed = [1,0,0,0,1], n = 2 Output: false diff --git a/content-ru/leetcode/Array/636-exclusive-time-of-functions.md b/content-ru/leetcode/Array/636-exclusive-time-of-functions.md index cbe672b03b7cd..984e296516505 100644 --- a/content-ru/leetcode/Array/636-exclusive-time-of-functions.md +++ b/content-ru/leetcode/Array/636-exclusive-time-of-functions.md @@ -1,47 +1,21 @@ # 636. Exclusive Time of Functions (Medium) () -> На однопоточном CPU выполняется программа, содержащая n функций. -> У каждой функции уникальный ID от 0 до n - 1. -> Вызовы функций хранятся в стеке вызовов: когда вызов функции начинается, её ID кладётся на стек, а когда вызов завершается, её ID снимается со стека. -> Функция, чей ID находится на вершине стека — это текущая выполняющаяся функция. -> Каждый раз, когда функция начинается или заканчивается, записывается лог с её ID, тем, началась она или закончилась, и временной меткой. -> Дан список logs, где logs[i] представляет i-е сообщение лога в формате строки "{function_id}:{"start" | "end"}:{timestamp}". -> Например, "0:start:3" означает, что вызов функции с ID 0 начался в начале момента времени 3, а "1:end:2" означает, что вызов функции с ID 1 закончился в конце момента времени 2. -> Учтите, что функция может вызываться несколько раз, в том числе рекурсивно. -> Эксклюзивное время функции — это сумма времени выполнения всех вызовов этой функции в программе. -> Например, если функция вызывается дважды: один вызов выполняется 2 единицы времени, а другой — 1 единицу, эксклюзивное время равно 2 + 1 = 3. +> На однопоточном процессоре мы выполняем программу, содержащую n функций. +> Каждая функция имеет уникальный ID от 0 до n - 1. +> Вызовы функций хранятся в стеке вызовов: когда вызов функции начинается, её ID кладётся на стек, а когда вызов завершается, ID снимается со стека. +> Функция, чей ID находится на вершине стека, — это функция, выполняемая в данный момент. +> Каждый раз, когда функция начинается или завершается, записывается лог с ID, признаком начала/завершения и меткой времени. +> Дан список logs, где logs[i] представляет i-й лог в формате строки "{function_id}:{"start" | "end"}:{timestamp}". +> Например, "0:start:3" означает, что вызов функции с ID 0 начался в начале момента времени 3, а "1:end:2" означает, что вызов функции с ID 1 завершился в конце момента времени 2. +> Обратите внимание, что функция может вызываться несколько раз, в том числе рекурсивно. +> Эксклюзивное время функции — это сумма времени выполнения по всем вызовам этой функции в программе. +> Например, если функция вызвана дважды, и один вызов выполнялся 2 единицы времени, а другой — 1 единицу, то эксклюзивное время равно 2 + 1 = 3. > Верните эксклюзивное время каждой функции в виде массива, где значение по индексу i представляет эксклюзивное время функции с ID i. -> Ограничения: - 1 <= n <= 100 - 2 <= logs.length <= 500 - 0 <= function_id < n - 0 <= timestamp <= 10^9 - Никакие два события start не произойдут в один и тот же момент времени. -> -> - Никакие два события end не произойдут в один и тот же момент времени. -> - У каждой функции есть лог "end" для каждого лога "start". +> Ограничения: - 1 <= n <= 100 - 2 <= logs.length <= 500 - 0 <= function_id < n - 0 <= timestamp <= 10^9 - Никакие два события "start" не происходят в один и тот же момент времени. +> - Никакие два события "end" не происходят в один и тот же момент времени. +> - Для каждого "start" лога есть соответствующий "end" лог. ```ts -function starts or ends, we write a log with the ID, whether it started or ended, and the timestamp. - - You are given a list logs, where logs[i] represents the ith log message formatted as a string - "{function_id}:{"start" | "end"}:{timestamp}". For example, "0:start:3" means a function call - with function ID 0 started at the beginning of timestamp 3, and "1:end:2" means a function call - with function ID 1 ended at the end of timestamp 2. Note that a function can be called multiple - times, possibly recursively. - - A function's exclusive time is the sum of execution times for all function calls in the program. - For example, if a function is called twice, one call executing for 2 time units and another call - executing for 1 time unit, the exclusive time is 2 + 1 = 3. - - Return the exclusive time of each function in an array, where the value at the ith index - represents the exclusive time for the function with ID i. - - Constraints: - - 1 <= n <= 100 - - 2 <= logs.length <= 500 - - 0 <= function_id < n - - 0 <= timestamp <= 10^9 - - No two start events will happen at the same timestamp. - - No two end events will happen at the same timestamp. - - Each function has an "end" log for each "start" log. -*/ - function exclusiveTime(n: number, logs: string[]): number[] { // Стек хранит ID функций, которые сейчас "в работе" (ещё не завершились). // Вершина стека — текущая выполняемая функция. @@ -156,45 +130,45 @@ console.log(exclusiveTime2(2, ['0:start:0', '0:start:2', '0:end:5', '1:start:6', ``` ```md -Example 1: - - Input: n = 2, logs = ["0:start:0","1:start:2","1:end:5","0:end:6"] - Output: [3,4] - Explanation: - Function 0 starts at the beginning of time 0, then it executes 2 units of time - and reaches the end of time 1. - Function 1 starts at the beginning of time 2, executes for 4 units of time, - and ends at the end of time 5. - Function 0 resumes execution at the beginning of time 6 and executes for 1 unit of time. - So function 0 spends 2 + 1 = 3 units of total time executing, and function 1 spends - 4 units of total time executing. - -Example 2: - - Input: n = 1, logs = ["0:start:0","0:start:2","0:end:5","0:start:6","0:end:6","0:end:7"] - Output: [8] - Explanation: - Function 0 starts at the beginning of time 0, executes for 2 units of time, and - recursively calls itself. - Function 0 (recursive call) starts at the beginning of time 2 and executes for 4 units of time. - Function 0 (initial call) resumes execution then immediately calls itself again. - Function 0 (2nd recursive call) starts at the beginning of time 6 and executes for 1 unit of time. - Function 0 (initial call) resumes execution at the beginning of time 7 and executes for 1 unit of time. - So function 0 spends 2 + 4 + 1 + 1 = 8 units of total time executing. - -Example 3: - - Input: n = 2, logs = ["0:start:0","0:start:2","0:end:5","1:start:6","1:end:6","0:end:7"] - Output: [7,1] - Explanation: - Function 0 starts at the beginning of time 0, executes for 2 units of time, and - recursively calls itself. - Function 0 (recursive call) starts at the beginning of time 2 and executes for 4 units of time. - Function 0 (initial call) resumes execution then immediately calls function 1. - Function 1 starts at the beginning of time 6, executes 1 unit of time, and ends at the end of time 6. - Function 0 resumes execution at the beginning of time 7 and executes for 1 unit of time. - So function 0 spends 2 + 4 + 1 = 7 units of total time executing, and function 1 spends - 1 unit of total time executing. +Пример 1: + + Вход: n = 2, logs = ["0:start:0","1:start:2","1:end:5","0:end:6"] + Выход: [3,4] + Объяснение: + Функция 0 начинается в начале времени 0, затем выполняется 2 единицы времени + и достигает конца времени 1. + Функция 1 начинается в начале времени 2, выполняется 4 единицы времени, + и заканчивается в конце времени 5. + Функция 0 возобновляет выполнение в начале времени 6 и выполняется 1 единицу времени. + Таким образом, функция 0 суммарно тратит на выполнение 2 + 1 = 3 единицы времени, а функция 1 — + 4 единицы времени. + + Пример 2: + + Вход: n = 1, logs = ["0:start:0","0:start:2","0:end:5","0:start:6","0:end:6","0:end:7"] + Выход: [8] + Объяснение: + Функция 0 начинается в начале времени 0, выполняется 2 единицы времени и + рекурсивно вызывает саму себя. + Функция 0 (рекурсивный вызов) начинается в начале времени 2 и выполняется 4 единицы времени. + Функция 0 (исходный вызов) возобновляет выполнение и сразу же снова вызывает саму себя. + Функция 0 (второй рекурсивный вызов) начинается в начале времени 6 и выполняется 1 единицу времени. + Функция 0 (исходный вызов) возобновляет выполнение в начале времени 7 и выполняется 1 единицу времени. + Таким образом, функция 0 суммарно тратит на выполнение 2 + 4 + 1 + 1 = 8 единиц времени. + + Пример 3: + + Вход: n = 2, logs = ["0:start:0","0:start:2","0:end:5","1:start:6","1:end:6","0:end:7"] + Выход: [7,1] + Объяснение: + Функция 0 начинается в начале времени 0, выполняется 2 единицы времени и + рекурсивно вызывает саму себя. + Функция 0 (рекурсивный вызов) начинается в начале времени 2 и выполняется 4 единицы времени. + Функция 0 (исходный вызов) возобновляет выполнение и сразу же вызывает функцию 1. + Функция 1 начинается в начале времени 6, выполняется 1 единицу времени и заканчивается в конце времени 6. + Функция 0 возобновляет выполнение в начале времени 7 и выполняется 1 единицу времени. + Таким образом, функция 0 суммарно тратит на выполнение 2 + 4 + 1 = 7 единиц времени, а функция 1 — + 1 единицу времени. ``` [[leetcode/Array/605-can-place-flowers]] diff --git a/content-ru/leetcode/Array/643-maximum-average-subarray-i.md b/content-ru/leetcode/Array/643-maximum-average-subarray-i.md index 2ee811408a49c..0de957418fad1 100644 --- a/content-ru/leetcode/Array/643-maximum-average-subarray-i.md +++ b/content-ru/leetcode/Array/643-maximum-average-subarray-i.md @@ -1,35 +1,36 @@ # 643. Maximum Average Subarray I (Easy) () -> Дан целочисленный массив nums из n элементов и целое число k. -> Найдите непрерывный подмассив длины k с максимальным средним значением и верните это значение. +> Дан массив целых чисел nums, состоящий из n элементов, и целое число k. +> Найдите непрерывный подмассив длиной, равной k, у которого максимальное среднее значение, и верните это значение. > Любой ответ с погрешностью вычисления менее 10^-5 будет принят. > Ограничения: - n == nums.length - 1 <= k <= n <= 10^5 - -10^4 <= nums[i] <= 10^4 ```ts function findMaxAverage(nums: number[], k: number): number { - let maxSum = nums.slice(0, k).reduce((acc, cur) => acc + cur, 0) - let curSum = maxSum + let maxSum = nums.slice(0, k).reduce((acc, cur) => acc + cur, 0); + let curSum = maxSum; for (let i = 0; i < nums.length - k; i++) { curSum = curSum - nums[i] + nums[i + k] maxSum = curSum > maxSum ? curSum : maxSum } - return maxSum / k + return maxSum / k; } -console.log(findMaxAverage([1, 12, -5, -6, 50, 3], 4)) // 12.75 -console.log(findMaxAverage([5], 1)) // 5.0 +console.log(findMaxAverage([1, 12, -5, -6, 50, 3], 4)); // 12.75 +console.log(findMaxAverage([5], 1)); // 5.0 ``` ```md -Example 1: -Input: nums = [1,12,-5,-6,50,3], k = 4 -Output: 12.75 -Explanation: Maximum average is (12 - 5 - 6 + 50) / 4 = 51 / 4 = 12.75 -Example 2: -Input: nums = [5], k = 1 -Output: 5.00000 +Пример 1: + Ввод: nums = [1,12,-5,-6,50,3], k = 4 + Вывод: 12.75 + Объяснение: Максимальное среднее равно (12 - 5 - 6 + 50) / 4 = 51 / 4 = 12.75 + + Пример 2: + Ввод: nums = [5], k = 1 + Вывод: 5.00000 ``` [[leetcode/Array/index|array]] diff --git a/content-ru/leetcode/Array/645-set-mismatch.md b/content-ru/leetcode/Array/645-set-mismatch.md index 097e4f2eb150a..4c86fdadc67d5 100644 --- a/content-ru/leetcode/Array/645-set-mismatch.md +++ b/content-ru/leetcode/Array/645-set-mismatch.md @@ -1,8 +1,8 @@ # 645. Set Mismatch (Easy) () -> У вас есть набор целых чисел `s`, изначально содержащий все числа от `1` до `n`. -> К сожалению, из-за ошибки одно из чисел в `s` продублировалось вместо другого числа набора, из-за чего одно число повторилось, а другое было потеряно. -> Дан целочисленный массив nums, представляющий состояние данных этого набора после ошибки. +> У вас есть множество целых чисел `s`, которое изначально содержит все числа от `1` до `n`. +> К сожалению, из-за некоторой ошибки одно из чисел в `s` продублировалось вместо другого числа множества, что привело к повторению одного числа и потере другого. +> Вам дан массив целых чисел nums, представляющий состояние данных этого множества после ошибки. > Найдите число, которое встречается дважды, и число, которое отсутствует, и верните их в виде массива. > Ограничения: - 2 <= nums.length <= 10^4 - 1 <= nums[i] <= 10^4 @@ -15,7 +15,8 @@ function findErrorNums(nums: number[]): number[] { const seen = new Set() for (const n of nums) { - if (seen.has(n)) dupSum = n + if (seen.has(n)) + dupSum = n seen.add(n) actualSum += n } @@ -36,7 +37,7 @@ Example 1: Output: [2,3] Explanation: The number 2 appears twice and the number 3 is missing. -Example 2: + Example 2: Input: nums = [1,1] Output: [1,2] diff --git a/content-ru/leetcode/Array/704-binary-search.md b/content-ru/leetcode/Array/704-binary-search.md new file mode 100644 index 0000000000000..845f2eeee818e --- /dev/null +++ b/content-ru/leetcode/Array/704-binary-search.md @@ -0,0 +1,49 @@ +# 704. Двоичный поиск (Лёгкий уровень) () + +> Дан отсортированный по возрастанию массив целых чисел nums и целое число target, напишите функцию для поиска target в nums. +> Если target существует, верните его индекс. +> В противном случае верните -1. +> Вы должны написать алгоритм со сложностью выполнения O(log n). +> Ограничения: - 1 <= nums.length <= 10^4 - -10^4 < nums[i], target < 10^4 - Все целые числа в nums уникальны. +> - nums отсортирован по возрастанию. + +```ts +function search(nums: number[], target: number): number { + let left = 0, + right = nums.length - 1; + let middle = Math.floor((left + right) / 2); + + while (right >= left) { + if (target > nums[middle]) { + left = middle + 1; + } else if (target < nums[middle]) { + right = middle - 1; + } else { + return middle; + } + middle = Math.floor((left + right) / 2); + } + + return -1; +} + +// Локальная проверка: +console.log(search([-1, 0, 3, 5, 9, 12], 9)); // 4 +console.log(search([-1, 0, 3, 5, 9, 12], 2)); // -1 +console.log(search([-1, 0, 3, 5, 9, 12], 12)); // 5 +``` + +```md +Пример 1: + + Ввод: nums = [-1,0,3,5,9,12], target = 9 + Вывод: 4 + Объяснение: 9 существует в nums и его индекс равен 4 + + Пример 2: + + Ввод: nums = [-1,0,3,5,9,12], target = 2 + Вывод: -1 + Объяснение: 2 не существует в nums, поэтому возвращаем -1 +``` +#leetcode diff --git a/content-ru/leetcode/Array/735-asteroid-collision.md b/content-ru/leetcode/Array/735-asteroid-collision.md new file mode 100644 index 0000000000000..2351ecf336cc7 --- /dev/null +++ b/content-ru/leetcode/Array/735-asteroid-collision.md @@ -0,0 +1,86 @@ +# 735. Столкновение астероидов (Medium) () + +> Нам дан массив astероids, содержащий целые числа, представляющие астероиды в ряд. +> Индексы астероида в массиве представляют их относительное положение в пространстве. +> Для каждого астероида абсолютное значение представляет его размер, а знак — направление (положительное означает вправо, отрицательное — влево). +> Все астероиды двигаются с одинаковой скоростью. +> Определите состояние астероидов после всех столкновений. +> Если два астероида встречаются, меньший взрывается. +> Если оба одинакового размера, взрываются оба. +> Два астероида, движущихся в одном направлении, никогда не встретятся. +> Ограничения: - 2 <= asteroids.length <= 10^4 - -1000 <= asteroids[i] <= 1000 - asteroids[i] != 0 + +```ts +function asteroidCollision(asteroids: number[]): number[] { + const stack: number[] = []; + + for (let i = 0; i < asteroids.length; i++) { + const curr = asteroids[i]; + if (stack.length === 0 || (stack.at(-1)! > 0 && curr > 0)) { + stack.push(curr); + continue; + } + + if (stack.at(-1)! < 0 && curr > 0) { + stack.push(curr); + continue; + } + + let currAlive = true; + while (stack.at(-1)! > 0 && curr < 0) { + if (Math.abs(curr) > Math.abs(stack.at(-1)!)) { + stack.pop(); + } else if (Math.abs(curr) < Math.abs(stack.at(-1)!)) { + currAlive = false; + break; + } else { + currAlive = false; + stack.pop(); + break; + } + } + + if (currAlive) { + stack.push(curr); + } + } + + return stack; +} + +// Локальная проверка: +console.log(asteroidCollision([10, -2])); +console.log(asteroidCollision([5, 10, -5])); +console.log(asteroidCollision([8, -8])); +console.log(asteroidCollision([10, 2, -5])); +console.log(asteroidCollision([3, 5, -6, 2, -1, 4])); +``` + +```md +Пример 1: + + Вход: asteroids = [5,10,-5] + Выход: [5,10] + Объяснение: 10 и -5 сталкиваются, в результате остаётся 10. 5 и 10 никогда не сталкиваются. + + Пример 2: + + Вход: asteroids = [8,-8] + Выход: [] + Объяснение: 8 и -8 сталкиваются, взрывая друг друга. + + Пример 3: + + Вход: asteroids = [10,2,-5] + Выход: [10] + Объяснение: 2 и -5 сталкиваются, в результате остаётся -5. 10 и -5 сталкиваются, в результате остаётся 10. + + Пример 4: + + Вход: asteroids = [3,5,-6,2,-1,4] + Выход: [-6,2,4] + Объяснение: астероид -6 взрывает астероиды 3 и 5, а затем продолжает лететь влево. + С другой стороны, астероид 2 уничтожает -1. Поскольку 2 и 4 оба движутся вправо, они никогда не сталкиваются. +``` + +#leetcode diff --git a/content-ru/leetcode/Array/739-daily-temperatures.md b/content-ru/leetcode/Array/739-daily-temperatures.md index e17f7025fe783..17c2a67634501 100644 --- a/content-ru/leetcode/Array/739-daily-temperatures.md +++ b/content-ru/leetcode/Array/739-daily-temperatures.md @@ -1,31 +1,49 @@ # 739. Daily Temperatures (Medium) () -> Дан массив целых чисел temperatures, представляющий дневные температуры; верните массив answer такой, что answer[i] — количество дней, которые нужно подождать после i-го дня, чтобы получить более тёплую температуру. +> Дан массив целых чисел temperatures, представляющий дневные температуры. Верните массив answer такой, что answer[i] — это количество дней, которые нужно подождать после i-го дня, чтобы получить более тёплую температуру. > Если такого будущего дня не существует, оставьте answer[i] == 0. -> git@github.com:Faustze/frontend-study-lab.git Ограничения: - 1 <= temperatures.length <= 10^5 - 30 <= temperatures[i] <= 100 +> Ограничения: - 1 <= temperatures.length <= 10^5 - 30 <= temperatures[i] <= 100 ```ts function dailyTemperatures(temperatures: number[]): number[] { - const n = temperatures.length - const answer: number[] = new Array(n).fill(0) // по умолчанию 0 - const stack: number[] = [] // храним ИНДЕКСЫ + const n = temperatures.length; + const answer: number[] = new Array(n).fill(0); // по умолчанию 0 + const stack: number[] = []; // храним ИНДЕКСЫ for (let i = 0; i < n; i++) { // Пока стек не пуст И текущая температура ВЫШЕ температуры на верхушке while (stack.length > 0 && temperatures[i] > temperatures[stack.at(-1)!]) { - const topIdx = stack.pop()! - answer[topIdx] = i - topIdx // расстояние между индексами + const topIdx = stack.pop()!; + answer[topIdx] = i - topIdx; // расстояние между индексами } - stack.push(i) + stack.push(i); } - return answer + return answer; } // Local check: -console.log(dailyTemperatures([73, 74, 75, 71, 69, 72, 76, 73])) // [1,1,4,2,1,1,0,0] -console.log(dailyTemperatures([30, 40, 50, 60])) // [1,1,1,0] -console.log(dailyTemperatures([30, 60, 90])) // [1,1,0] +console.log(dailyTemperatures([73, 74, 75, 71, 69, 72, 76, 73])); // [1,1,4,2,1,1,0,0] +console.log(dailyTemperatures([30, 40, 50, 60])); // [1,1,1,0] +console.log(dailyTemperatures([30, 60, 90])); // [1,1,0] + +// function dailyTemperatures(temperatures: number[]): number[] { +// const answer: number[] = []; + +// for (let i = 0; i < temperatures.length; i++) { +// let j = i + 1; +// let cnt = 1; + +// while (j < temperatures.length && temperatures[i] >= temperatures[j]) { +// cnt++; +// j++; +// } + +// answer.push(j < temperatures.length ? cnt : 0); +// } + +// return answer; +// } ``` ```md @@ -43,12 +61,12 @@ Example 1: Day 6 (76): no warmer day -> 0 Day 7 (73): no warmer day -> 0 -Example 2: + Example 2: Input: temperatures = [30,40,50,60] Output: [1,1,1,0] -Example 3: + Example 3: Input: temperatures = [30,60,90] Output: [1,1,0] diff --git a/content-ru/leetcode/Array/853-car-fleet.md b/content-ru/leetcode/Array/853-car-fleet.md new file mode 100644 index 0000000000000..ed1ef1fcb41c6 --- /dev/null +++ b/content-ru/leetcode/Array/853-car-fleet.md @@ -0,0 +1,67 @@ +# 853. Автопарк (Средний уровень) () + +> Есть n машин, находящихся на заданном расстоянии от начальной отметки 0 мили, движущихся к отметке target. +> Вам даны два целочисленных массива position и speed, оба длиной n, где position[i] — начальная миля i-й машины, а speed[i] — скорость i-й машины в милях в час. +> Машина не может обогнать другую машину, но может её догнать и затем ехать рядом с ней со скоростью более медленной машины. +> Автопарк — это одна машина или группа машин, едущих рядом друг с другом. +> Скорость автопарка — это минимальная скорость среди всех машин в этом автопарке. +> Если машина догоняет автопарк ровно на отметке target, она всё равно считается частью этого автопарка. +> Верните количество автопарков, которые прибудут к месту назначения. +> Ограничения: - n == position.length == speed.length - 1 <= n <= 10^5 - 0 < target <= 10^6 - 0 <= position[i] < target - Все значения position уникальны. +> - 0 < speed[i] <= 10^6 + +```ts +function carFleet(target: number, position: number[], speed: number[]): number { + let time = 0; + let fleets = 0; + const cars = position.map((p, i) => [p, speed[i]]); + cars.sort((a, b) => b[0] - a[0]); + for (let i = 0; i < cars.length; i++) { + const currentTime = (target - cars[i][0]) / cars[i][1]; + if (currentTime > time) { + fleets += 1; + time = currentTime; + } + } + return fleets; +} + +// Local check: +console.log(carFleet(12, [10, 8, 0, 5, 3], [2, 4, 1, 1, 3])); // 3 +console.log(carFleet(10, [3], [3])); // 1 +console.log(carFleet(100, [0, 2, 4], [4, 2, 1])); // 1 +``` + +```md +Пример 1: + + Ввод: target = 12, position = [10,8,0,5,3], speed = [2,4,1,1,3] + Вывод: 3 + Объяснение: + Машины, начавшие движение с 10 (скорость 2) и 8 (скорость 4), образуют автопарк, + встречаясь друг с другом на отметке 12. Автопарк формируется на target. + Машина, начавшая движение с 0 (скорость 1), не догоняет ни одну другую машину, поэтому + она является автопарком сама по себе. + Машины, начавшие движение с 5 (скорость 1) и 3 (скорость 3), образуют автопарк, + встречаясь друг с другом на отметке 6. Автопарк движется со скоростью 1, пока не достигнет + target. + + Пример 2: + + Ввод: target = 10, position = [3], speed = [3] + Вывод: 1 + Объяснение: Есть только одна машина, следовательно, есть только один автопарк. + + Пример 3: + + Ввод: target = 100, position = [0,2,4], speed = [4,2,1] + Вывод: 1 + Объяснение: + Машины, начавшие движение с 0 (скорость 4) и 2 (скорость 2), образуют автопарк, + встречаясь друг с другом на отметке 4. Машина, начавшая движение с 4 (скорость 1), доезжает до 5. + Затем автопарк на отметке 4 (скорость 2) и машина на отметке 5 (скорость 1) + объединяются в один автопарк, встречаясь друг с другом на отметке 6. Автопарк движется со скоростью 1 + до достижения target. +``` + +#leetcode diff --git a/content-ru/leetcode/Array/977-squares-of-a-sorted-array.md b/content-ru/leetcode/Array/977-squares-of-a-sorted-array.md index bd3afbc365211..e003729b192a4 100644 --- a/content-ru/leetcode/Array/977-squares-of-a-sorted-array.md +++ b/content-ru/leetcode/Array/977-squares-of-a-sorted-array.md @@ -1,45 +1,49 @@ # 977. Squares of a Sorted Array (Easy) () -> Дан целочисленный массив nums, отсортированный по неубыванию, верните массив квадратов каждого числа, отсортированный по неубыванию. +> Дан массив целых чисел nums, отсортированный по неубыванию. Верните массив квадратов каждого числа, отсортированный по неубыванию. > Ограничения: - 1 <= nums.length <= 10^4 - -10^4 <= nums[i] <= 10^4 - nums отсортирован по неубыванию. -> Дополнительно: возвести каждый элемент в квадрат и отсортировать новый массив — тривиально, сможете ли вы найти решение за O(n) другим способом? +> Дополнительное задание: возвести каждый элемент в квадрат и отсортировать новый массив — тривиальное решение, сможете ли вы найти решение за O(n), используя другой подход? ```ts function sortedSquares(nums: number[]): number[] { - const result: number[] = new Array(nums.length) - let left = 0 - let right = nums.length - 1 - let idx = nums.length - 1 + const result: number[] = new Array(nums.length); + let left = 0; + let right = nums.length - 1; + let idx = nums.length - 1; while (left <= right) { - const squaredLeft = nums[left] * nums[left] - const squaredRight = nums[right] * nums[right] + const squaredLeft = nums[left] * nums[left]; + const squaredRight = nums[right] * nums[right]; if (squaredLeft > squaredRight) { - result[idx] = squaredLeft - left++ + result[idx] = squaredLeft; + left++; } else { - result[idx] = squaredRight - right-- + result[idx] = squaredRight; + right--; } - idx-- + idx--; } - return result + + return result; } // Local check: -console.log(sortedSquares([-4, -1, 0, 3, 10])) -console.log(sortedSquares([-7, -3, 2, 3, 11])) +console.log(sortedSquares([-4, -1, 0, 3, 10])); +console.log(sortedSquares([-7, -3, 2, 3, 11])); ``` ```md Example 1: -Input: nums = [-4,-1,0,3,10] -Output: [0,1,9,16,100] -Explanation: After squaring, the array becomes [16,1,0,9,100]. -After sorting, it becomes [0,1,9,16,100]. -Example 2: -Input: nums = [-7,-3,2,3,11] -Output: [4,9,9,49,121] + + Input: nums = [-4,-1,0,3,10] + Output: [0,1,9,16,100] + Explanation: After squaring, the array becomes [16,1,0,9,100]. + After sorting, it becomes [0,1,9,16,100]. + + Example 2: + + Input: nums = [-7,-3,2,3,11] + Output: [4,9,9,49,121] ``` #leetcode diff --git a/content-ru/leetcode/Array/index.md b/content-ru/leetcode/Array/index.md index 2c0fd6b2609aa..63ec0ae733421 100644 --- a/content-ru/leetcode/Array/index.md +++ b/content-ru/leetcode/Array/index.md @@ -6,24 +6,33 @@ title: array [[leetcode/index|← LeetCode]] +- [[Array/11-container-with-most-water]] +- [[Array/128-longest-consecutive-sequence]] - [[Array/1365-how-many-numbers-are-smaller-than-the-current-number]] - [[Array/1431-kids-with-the-greatest-number-of-candies]] - [[Array/1441-build-an-array-with-stack-operations]] - [[Array/1470-shuffle-the-array]] - [[Array/1475-final-prices-with-a-special-discount-in-a-shop]] +- [[Array/15-3sum]] - [[Array/150-evaluate-reverse-polish-notation]] +- [[Array/217-contains-duplicate]] +- [[Array/238-product-of-array-except-self]] - [[Array/268-missing-number]] - [[Array/283-move-zeroes]] +- [[Array/347-top-k-frequent-elements]] +- [[Array/36-valid-sudoku]] - [[Array/448-find-all-numbers-disappeared-in-an-array]] - [[Array/485-max-consecutive-ones]] +- [[Array/49-group-anagrams]] +- [[Array/496-next-greater-element-i]] - [[Array/605-can-place-flowers]] - [[Array/636-exclusive-time-of-functions]] - [[Array/643-maximum-average-subarray-i]] - [[Array/645-set-mismatch]] +- [[Array/704-binary-search]] +- [[Array/735-asteroid-collision]] - [[Array/739-daily-temperatures]] +- [[Array/853-car-fleet]] - [[Array/977-squares-of-a-sorted-array]] -- [[Array/217-contains-duplicate]] -- [[Array/347-top-k-frequent-elements]] -- [[Array/49-group-anagrams]] #leetcode diff --git a/content-ru/leetcode/Hash Table/141-linked-list-cycle.md b/content-ru/leetcode/Hash Table/141-linked-list-cycle.md index e468e6b2bc808..e7d2624c25b1d 100644 --- a/content-ru/leetcode/Hash Table/141-linked-list-cycle.md +++ b/content-ru/leetcode/Hash Table/141-linked-list-cycle.md @@ -1,76 +1,79 @@ # 141. Linked List Cycle (Easy) () -> Дан head — голова связного списка, определите, есть ли в списке цикл. -> Цикл в связном списке есть, если существует узел, до которого можно снова дойти, постоянно следуя по указателю next. -> Внутренне pos используется для обозначения индекса узла, к которому подключён указатель next хвоста. -> Учтите, что pos не передаётся как параметр. +> Дан head — голова связного списка. Определите, содержит ли связный список цикл. +> В связном списке есть цикл, если существует узел, к которому можно снова прийти, непрерывно следуя по указателю next. +> Внутренне используется pos для обозначения индекса узла, к которому подключён указатель next хвостового узла. +> Обратите внимание, что pos не передаётся как параметр. > Верните true, если в связном списке есть цикл. -> Иначе верните false. -> Ограничения: - количество узлов в списке находится в диапазоне [0, 10^4]. -> -> - -10^5 <= Node.val <= 10^5 - pos равно -1 или является валидным индексом в связном списке. -> Дополнительно: сможете ли вы решить это за O(1) (то есть -> константную) память? +> В противном случае верните false. +> Ограничения: - Количество узлов в списке находится в диапазоне [0, 10^4]. +> - -10^5 <= Node.val <= 10^5 - pos равен -1 или является допустимым индексом в связном списке. +> Дополнительное задание: Сможете ли вы решить эту задачу, используя O(1) (то есть +> константную) память? ```ts class ListNode { - val: number - next: ListNode | null + val: number; + next: ListNode | null; constructor(val?: number, next?: ListNode | null) { - this.val = val === undefined ? 0 : val - this.next = next === undefined ? null : next + this.val = val === undefined ? 0 : val; + this.next = next === undefined ? null : next; } } function hasCycle(head: ListNode | null): boolean { // Floyd's Cycle Detection - let slow: ListNode | null = head - let fast: ListNode | null = head + let slow: ListNode | null = head; + let fast: ListNode | null = head; while (fast !== null && fast.next !== null) { - slow = slow!.next - fast = fast.next.next - if (fast === slow) return true + slow = slow!.next; + fast = fast.next.next; + if (fast === slow) return true; } - return false + return false; } function toList(arr: number[], pos: number): ListNode | null { - if (arr.length === 0) return null - const nodes = arr.map((v) => new ListNode(v)) - + if (arr.length === 0) return null; + const nodes = arr.map((v) => new ListNode(v)); for (let i = 0; i < nodes.length - 1; i++) { - nodes[i].next = nodes[i + 1] + nodes[i].next = nodes[i + 1]; } if (pos >= 0 && pos < nodes.length) { - nodes[nodes.length - 1].next = nodes[pos] + nodes[nodes.length - 1].next = nodes[pos]; } - return nodes[0] + return nodes[0]; } -// Local check: -console.log(hasCycle(toList([3, 2, 0, -4], 1))) // true -console.log(hasCycle(toList([1, 2], 0))) // true -console.log(hasCycle(toList([1], -1))) // false -console.log(hasCycle(toList([], -1))) // false -console.log(hasCycle(toList([1, 2, 3, 4, 5], -1))) // false -console.log(hasCycle(toList([1, 2, 3, 4, 5], 4))) // true (tail → last node itself) +// Локальная проверка: +console.log(hasCycle(toList([3, 2, 0, -4], 1))); // true +console.log(hasCycle(toList([1, 2], 0))); // true +console.log(hasCycle(toList([1], -1))); // false +console.log(hasCycle(toList([], -1))); // false +console.log(hasCycle(toList([1, 2, 3, 4, 5], -1))); // false +console.log(hasCycle(toList([1, 2, 3, 4, 5], 4))); // true (tail → last node itself) ``` ```md -Example 1: -Input: head = [3,2,0,-4], pos = 1 -Output: true -Explanation: There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed). -Example 2: -Input: head = [1,2], pos = 0 -Output: true -Explanation: There is a cycle in the linked list, where the tail connects to the 0th node. -Example 3: -Input: head = [1], pos = -1 -Output: false -Explanation: There is no cycle in the linked list. +Пример 1: + + Вход: head = [3,2,0,-4], pos = 1 + Выход: true + Объяснение: В связном списке есть цикл, где хвост соединяется с 1-м узлом (индексация с 0). + + Пример 2: + + Вход: head = [1,2], pos = 0 + Выход: true + Объяснение: В связном списке есть цикл, где хвост соединяется с 0-м узлом. + + Пример 3: + + Вход: head = [1], pos = -1 + Выход: false + Объяснение: В связном списке нет цикла. ``` [[leetcode/Hash Table/index|hash-table]] diff --git a/content-ru/leetcode/Hash Table/242-valid-anagram.md b/content-ru/leetcode/Hash Table/242-valid-anagram.md index 576b274317c40..38bb83d04e9d1 100644 --- a/content-ru/leetcode/Hash Table/242-valid-anagram.md +++ b/content-ru/leetcode/Hash Table/242-valid-anagram.md @@ -1,26 +1,27 @@ # 242. Valid Anagram (Easy) () > Даны две строки s и t, верните true, если t является анаграммой s, и false в противном случае. -> Ограничения: 1 <= s.length, t.length <= 5 * 10^4 s и t состоят из строчных латинских букв. -> Дополнительно: что если во входных данных встречаются символы Unicode? Как адаптировать решение под этот случай? +> Ограничения: 1 <= s.length, t.length <= 5 * 10^4 s и t состоят из строчных английских букв. +> Дополнительный вопрос: что если входные данные содержат Unicode-символы? Как адаптировать решение под такой случай? ```ts function isAnagram(s: string, t: string): boolean { - if (s.length !== t.length) return false - const mp: Map = new Map() + if (s.length !== t.length) return false - for (const ch of s) { - mp.set(ch, (mp.get(ch) || 0) + 1) - } + const mp: Map = new Map(); - for (const ch of t) { - const curr = mp.get(ch) - if (!curr) return false - if (curr === 1) mp.delete(ch) - else mp.set(ch, curr - 1) - } + for (const ch of s) { + mp.set(ch, (mp.get(ch) || 0) + 1) + } - return true + for (const ch of t) { + const curr = mp.get(ch) + if (!curr) return false + if (curr === 1) mp.delete(ch) + else mp.set(ch, curr - 1) + } + + return true } // Local check: @@ -30,14 +31,16 @@ console.log(isAnagram("rat", "car")) // false ```md Example 1: -Input: s = "anagram", t = "nagaram" -Output: true -Explanation: "nagaram" is an anagram of "anagram". - -Example 2: -Input: s = "rat", t = "car" -Output: false -Explanation: "car" is not an anagram of "rat". + + Input: s = "anagram", t = "nagaram" + Output: true + Explanation: "nagaram" is an anagram of "anagram". + + Example 2: + + Input: s = "rat", t = "car" + Output: false + Explanation: "car" is not an anagram of "rat". ``` [[leetcode/Hash Table/index|hash-table]] diff --git a/content-ru/leetcode/Hash Table/index.md b/content-ru/leetcode/Hash Table/index.md index 441435c6f66e0..c3173f924edc6 100644 --- a/content-ru/leetcode/Hash Table/index.md +++ b/content-ru/leetcode/Hash Table/index.md @@ -1,12 +1,12 @@ --- -title: hash-table +title: хеш-таблица --- -# Hash Table +# Хеш-таблица [[leetcode/index|← LeetCode]] -- [[Hash-Table/141-linked-list-cycle]] -- [[Hash-Table/242-valid-anagram]] +- [[Hash Table/141-linked-list-cycle]] +- [[Hash Table/242-valid-anagram]] #leetcode diff --git a/content-ru/leetcode/Linked List/206-reverse-linked-list.md b/content-ru/leetcode/Linked List/206-reverse-linked-list.md index 52d7731090909..169f150ccaef5 100644 --- a/content-ru/leetcode/Linked List/206-reverse-linked-list.md +++ b/content-ru/leetcode/Linked List/206-reverse-linked-list.md @@ -1,55 +1,64 @@ # 206. Reverse Linked List (Easy) () -> Дана голова head односвязного списка, разверните список и верните развёрнутый список. -> Ограничения: - количество узлов в списке находится в диапазоне [0, 5000]. -> -> - -5000 <= Node.val <= 5000 Дополнительно: связный список можно развернуть итеративно или рекурсивно. -> Сможете ли вы реализовать оба варианта? +> Given the head of a singly linked list, reverse the list, and return the reversed list. +> Constraints: - The number of nodes in the list is in the range [0, 5000]. +> - -5000 <= Node.val <= 5000 Follow up: A linked list can be reversed either iteratively or recursively. +> Could you implement both? ```ts class ListNode { - val: number - next: ListNode | null + val: number; + next: ListNode | null; constructor(val?: number, next?: ListNode | null) { - this.val = val === undefined ? 0 : val - this.next = next === undefined ? null : next + this.val = val === undefined ? 0 : val; + this.next = next === undefined ? null : next; } } function reverseList(head: ListNode | null): ListNode | null { - if (head === null) return null - let prev: ListNode | null = null - let current = head + if (head === null) return null; + + let prev: ListNode | null = null; + let current: ListNode | null = head; while (current !== null) { - const next = current.next // запоминаем следующий узел - current.next = prev // разворачиваем ссылку - prev = current // двигаем prev - current = next // переходим дальше + const next: ListNode | null = current.next; // запоминаем следующий узел + current.next = prev; // разворачиваем ссылку + prev = current; // двигаем prev + current = next; // переходим дальше } - return prev + + return prev; } // Local check: -const list1 = new ListNode(1, new ListNode(2, new ListNode(3, new ListNode(4, new ListNode(5))))) -console.log(reverseList(list1)) // [5,4,3,2,1] +const list1 = new ListNode( + 1, + new ListNode(2, new ListNode(3, new ListNode(4, new ListNode(5)))), +); +console.log(reverseList(list1)); // [5,4,3,2,1] -const list2 = new ListNode(1, new ListNode(2)) -console.log(reverseList(list2)) // [2,1] +const list2 = new ListNode(1, new ListNode(2)); +console.log(reverseList(list2)); // [2,1] -console.log(reverseList(null)) // [] +console.log(reverseList(null)); // [] ``` ```md Example 1: -Input: head = [1,2,3,4,5] -Output: [5,4,3,2,1] -Example 2: -Input: head = [1,2] -Output: [2,1] -Example 3: -Input: head = [] -Output: [] + + Input: head = [1,2,3,4,5] + Output: [5,4,3,2,1] + + Example 2: + + Input: head = [1,2] + Output: [2,1] + + Example 3: + + Input: head = [] + Output: [] ``` [[leetcode/Linked List/index|linked-list]] diff --git a/content-ru/leetcode/Linked List/876-middle-of-the-linked-list.md b/content-ru/leetcode/Linked List/876-middle-of-the-linked-list.md index 9d4741fbbd0f4..ecefccf48fc4d 100644 --- a/content-ru/leetcode/Linked List/876-middle-of-the-linked-list.md +++ b/content-ru/leetcode/Linked List/876-middle-of-the-linked-list.md @@ -1,63 +1,68 @@ -# 876. Middle of the Linked List (Easy) () +# 876. Середина связного списка (Easy) () -> Дана голова head односвязного списка, верните средний узел связного списка. -> Если средних узлов два, верните второй из них. +> Дана голова односвязного списка, нужно вернуть средний узел связного списка. +> Если есть два средних узла, вернуть второй из них. ```ts class ListNode { - val: number - next: ListNode | null + val: number; + next: ListNode | null; constructor(val?: number, next?: ListNode | null) { - this.val = val === undefined ? 0 : val - this.next = next === undefined ? null : next + this.val = val === undefined ? 0 : val; + this.next = next === undefined ? null : next; } } function middleNode(head: ListNode | null): ListNode | null { - let slow = head - let fast = head + // Floyd's slow/fast pointers + let slow = head; + let fast = head; while (fast !== null && fast.next !== null) { - slow = slow!.next - fast = fast.next.next + slow = slow!.next; + fast = fast.next.next; } - return slow + + return slow; } // Local check: function toList(arr: number[]): ListNode | null { - if (arr.length === 0) return null - const head = new ListNode(arr[0]) - let cur = head + if (arr.length === 0) return null; + const head = new ListNode(arr[0]); + let cur = head; for (let i = 1; i < arr.length; i++) { - cur.next = new ListNode(arr[i]) - cur = cur.next + cur.next = new ListNode(arr[i]); + cur = cur.next; } - return head + return head; } function toArray(node: ListNode | null): number[] { - const out: number[] = [] + const out: number[] = []; while (node !== null) { - out.push(node.val) - node = node.next + out.push(node.val); + node = node.next; } - return out + return out; } -console.log(toArray(middleNode(toList([1, 2, 3, 4, 5])))) -console.log(toArray(middleNode(toList([1, 2, 3, 4, 5, 6])))) +console.log(toArray(middleNode(toList([1, 2, 3, 4, 5])))); +console.log(toArray(middleNode(toList([1, 2, 3, 4, 5, 6])))); ``` ```md Example 1: -Input: head = [1,2,3,4,5] -Output: [3,4,5] -Explanation: The middle node of the list is node 3. -Example 2: -Input: head = [1,2,3,4,5,6] -Output: [4,5,6] -Explanation: Since the list has two middle nodes with values 3 and 4, we return the second one. + + Input: head = [1,2,3,4,5] + Output: [3,4,5] + Explanation: The middle node of the list is node 3. + + Example 2: + + Input: head = [1,2,3,4,5,6] + Output: [4,5,6] + Explanation: Since the list has two middle nodes with values 3 and 4, we return the second one. ``` [[leetcode/Linked List/index|linked-list]] diff --git a/content-ru/leetcode/Linked List/index.md b/content-ru/leetcode/Linked List/index.md index 4142d051f14a4..67d69ad8d3fd6 100644 --- a/content-ru/leetcode/Linked List/index.md +++ b/content-ru/leetcode/Linked List/index.md @@ -1,12 +1,12 @@ --- -title: linked-list +title: связный список --- -# Linked List +# Связный список [[leetcode/index|← LeetCode]] -- [[Linked-List/206-reverse-linked-list]] -- [[Linked-List/876-middle-of-the-linked-list]] +- [[Linked List/206-reverse-linked-list]] +- [[Linked List/876-middle-of-the-linked-list]] #leetcode diff --git a/content-ru/leetcode/Math/1071-greatest-common-divisor-of-strings.md b/content-ru/leetcode/Math/1071-greatest-common-divisor-of-strings.md new file mode 100644 index 0000000000000..d276ddbbc9a46 --- /dev/null +++ b/content-ru/leetcode/Math/1071-greatest-common-divisor-of-strings.md @@ -0,0 +1,47 @@ +# 1071. Наибольший общий делитель строк (Easy) () + +> Для двух строк s и t говорят, что "t делит s" тогда и только тогда, когда s = t + t + ... +> + t (то есть t конкатенируется сама с собой один или более раз). +> Даны две строки str1 и str2, верните наибольшую строку x такую, что x делит и str1, и str2. +> Ограничения: 1 <= str1.length, str2.length <= 1000 str1 и str2 состоят из заглавных букв английского алфавита. + +```ts +function gcdOfStrings(str1: string, str2: string): string { + if (str1 + str2 !== str2 + str1) + return '' + return str1.slice(0, gcd(str1.length, str2.length)) +} + +// Алгоритм Евклида +function gcd(a: number, b: number) { + if (b === 0) { + return a + } + return gcd(b, a % b) +} + +// Local check: +console.log(gcdOfStrings('ABCABC', 'ABC')) +console.log(gcdOfStrings('ABABAB', 'ABAB')) +console.log(gcdOfStrings('LEET', 'CODE')) +``` + +```md +Example 1: + + Input: str1 = "ABCABC", str2 = "ABC" + Output: "ABC" + + Example 2: + + Input: str1 = "ABABAB", str2 = "ABAB" + Output: "AB" + + Example 3: + + Input: str1 = "LEET", str2 = "CODE" + Output: "" +``` + +[[leetcode/String/index|string]] +#leetcode diff --git a/content-ru/leetcode/Math/67-add-binary.md b/content-ru/leetcode/Math/67-add-binary.md new file mode 100644 index 0000000000000..cd2d8ce203bc8 --- /dev/null +++ b/content-ru/leetcode/Math/67-add-binary.md @@ -0,0 +1,55 @@ +# 67. Сложение двоичных чисел (Easy) () + +> Даны две двоичные строки a и b, нужно вернуть их сумму в виде двоичной строки. +> Ограничения: - 1 <= a.length, b.length <= 10^4 - a и b состоят только из символов '0' или '1'. +> - Каждая строка не содержит ведущих нулей, кроме самого нуля. + +```ts +function addBinary(a: string, b: string): string { + const sum = BigInt("0b" + a) + BigInt("0b" + b); + return sum.toString(2); +} + +// Local check: +console.log(addBinary("11", "1")); // "100" +console.log(addBinary("1010", "1011")); // "10101" + +// function addBinary(a: string, b: string): string { +// let i = a.length - 1; +// let j = b.length - 1; +// let carry = 0; +// let result = ""; + +// while (i >= 0 || j >= 0 || carry) { +// const x = i >= 0 ? Number(a[i]) : 0; +// const y = j >= 0 ? Number(b[j]) : 0; + +// const sum = x + y + carry; + +// result = (sum % 2) + result; +// carry = Math.floor(sum / 2); + +// i--; +// j--; +// } + +// return result; +// } +``` + +```md +Example 1: + + Input: a = "11", b = "1" + Output: "100" + Explanation: 11 (binary) = 3, 1 (binary) = 1, 3 + 1 = 4 = 100 (binary) + + Example 2: + + Input: a = "1010", b = "1011" + Output: "10101" + Explanation: 1010 (binary) = 10, 1011 (binary) = 11, 10 + 11 = 21 = 10101 (binary) +``` + +[[leetcode/Bit Manipulation/index|bit-manipulation]] +#leetcode diff --git a/content-ru/leetcode/Math/index.md b/content-ru/leetcode/Math/index.md new file mode 100644 index 0000000000000..0698e47e4076a --- /dev/null +++ b/content-ru/leetcode/Math/index.md @@ -0,0 +1,12 @@ +--- +title: Математика +--- + +# Математика + +[[leetcode/index|← LeetCode]] + +- [[Math/1071-greatest-common-divisor-of-strings]] +- [[Math/67-add-binary]] + +#leetcode diff --git a/content-ru/leetcode/Stack/155-min-stack.md b/content-ru/leetcode/Stack/155-min-stack.md new file mode 100644 index 0000000000000..057227fbeeda8 --- /dev/null +++ b/content-ru/leetcode/Stack/155-min-stack.md @@ -0,0 +1,65 @@ +# 155. Min Stack (Medium) () + +> Спроектируйте стек, который поддерживает push, pop, top и получение минимального элемента за константное время. +> Реализуйте класс MinStack: - MinStack() инициализирует объект стека. +> - void push(int value) добавляет элемент value на вершину стека. +> - void pop() удаляет элемент с вершины стека. +> - int top() возвращает элемент на вершине стека. +> - int getMin() возвращает минимальный элемент в стеке. +> Ограничения: - -2^31 <= val <= 2^31 - 1 - Операции pop, top и getMin всегда будут вызываться на непустых стеках. +> - Будет сделано не более 3 * 10^4 вызовов push, pop, top и getMin. +> Вы должны реализовать решение с временной сложностью O(1) для каждой функции. + +```ts +class MinStack { + private stack: number[] = []; + private minStack: number[] = []; + + constructor() {} + + push(val: number): void { + this.stack.push(val); + const currentMin = + this.minStack.length === 0 ? Infinity : this.minStack.at(-1)!; + this.minStack.push(Math.min(val, currentMin)); + } + + pop(): void { + this.stack.pop(); + this.minStack.pop(); + } + + top(): number { + return this.stack.at(-1); + } + + getMin(): number { + return this.minStack.at(-1); + } +} + + +// Локальная проверка: +const minStack = new MinStack(); +minStack.push(1); +minStack.push(2); +minStack.push(0); +console.log(minStack.getMin()); +minStack.pop(); +console.log(minStack.top()); +console.log(minStack.getMin()); +``` + +```md +Пример 1: + + Ввод + ["MinStack", "push", 1, "push", 2, "push", 0, "getMin", "pop", "top", "getMin"] + + Вывод + [null,null,null,null,0,null,2,1] + + Объяснение +``` + +#leetcode diff --git a/content-ru/leetcode/Stack/index.md b/content-ru/leetcode/Stack/index.md new file mode 100644 index 0000000000000..65a70494de42a --- /dev/null +++ b/content-ru/leetcode/Stack/index.md @@ -0,0 +1,11 @@ +--- +title: стек +--- + +# Стек + +[[leetcode/index|← LeetCode]] + +- [[Stack/155-min-stack]] + +#leetcode diff --git a/content-ru/leetcode/String/20-valid-parentheses.md b/content-ru/leetcode/String/20-valid-parentheses.md new file mode 100644 index 0000000000000..d1814d0e27d7a --- /dev/null +++ b/content-ru/leetcode/String/20-valid-parentheses.md @@ -0,0 +1,52 @@ +# 20. Valid Parentheses (Easy) () + +> Дана строка s, содержащая только символы '(', ')', '{', '}', '[' и ']', определите, является ли входная строка допустимой. +> Входная строка допустима, если: 1. +> Открывающие скобки должны закрываться скобками того же типа. +> 2. +> Открывающие скобки должны закрываться в правильном порядке. +> 3. +> Каждой закрывающей скобке соответствует открывающая скобка того же типа. +> Ограничения: - 1 <= s.length <= 10^4 - s состоит только из скобок '()[]{}'. + +```ts +function isValid(s: string): boolean { + +} + +// Local check: +console.log(isValid("()")) +console.log(isValid("()[]{}")) +console.log(isValid("(]")) +console.log(isValid("([])")) +console.log(isValid("([)]")) +``` + +```md +Example 1: + + Input: s = "()" + Output: true + + Example 2: + + Input: s = "()[]{}" + Output: true + + Example 3: + + Input: s = "(]" + Output: false + + Example 4: + + Input: s = "([])" + Output: true + + Example 5: + + Input: s = "([)]" + Output: false +``` + +#leetcode diff --git a/content-ru/leetcode/String/index.md b/content-ru/leetcode/String/index.md index 034bba06a7a9f..512c781579cc8 100644 --- a/content-ru/leetcode/String/index.md +++ b/content-ru/leetcode/String/index.md @@ -1,11 +1,11 @@ --- -title: string +title: Строка --- -# String +# Строка [[leetcode/index|← LeetCode]] -- [[String/1071-greatest-common-divisor-of-strings]] +- [[String/20-valid-parentheses]] #leetcode diff --git a/content-ru/leetcode/Tree/104-maximum-depth-of-binary-tree.md b/content-ru/leetcode/Tree/104-maximum-depth-of-binary-tree.md new file mode 100644 index 0000000000000..8bf1fa4f0a43a --- /dev/null +++ b/content-ru/leetcode/Tree/104-maximum-depth-of-binary-tree.md @@ -0,0 +1,53 @@ +# 104. Максимальная глубина бинарного дерева (Easy) () + +> Дан корень бинарного дерева, верните его максимальную глубину. +> Максимальная глубина бинарного дерева — это количество узлов вдоль самого длинного пути от корневого узла до самого дальнего листового узла. +> Ограничения: - Количество узлов в дереве находится в диапазоне [0, 10^4]. +> - -100 <= Node.val <= 100 + +```ts +class TreeNode { + val: number + left: TreeNode | null + right: TreeNode | null + constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { + this.val = (val === undefined ? 0 : val) + this.left = (left === undefined ? null : left) + this.right = (right === undefined ? null : right) + } +} + +function maxDepth(root: TreeNode | null): number { + if (root === null) { + return 0 + } + + return 1 + Math.max(maxDepth(root.left), maxDepth(root.right)) +} + +// Local check: +const root = new TreeNode( + 3, + new TreeNode(9), + new TreeNode(20, new TreeNode(15), new TreeNode(7)), +) +console.log(maxDepth(root)) // 3 + +const root2 = new TreeNode(1, null, new TreeNode(2)) +console.log(maxDepth(root2)) // 2 +``` + +```md +Пример 1: + + Ввод: root = [3,9,20,null,null,15,7] + Вывод: 3 + + Пример 2: + + Ввод: root = [1,null,2] + Вывод: 2 +``` + +[[leetcode/Binary-Tree/index]] +#leetcode diff --git a/content-ru/leetcode/Tree/index.md b/content-ru/leetcode/Tree/index.md new file mode 100644 index 0000000000000..f4b280d3fa490 --- /dev/null +++ b/content-ru/leetcode/Tree/index.md @@ -0,0 +1,11 @@ +--- +title: Дерево +--- + +# Дерево + +[[leetcode/index|← LeetCode]] + +- [[Tree/104-maximum-depth-of-binary-tree]] + +#leetcode diff --git a/content-ru/leetcode/Two Pointers/125-valid-palindrome.md b/content-ru/leetcode/Two Pointers/125-valid-palindrome.md index 81c2b2e201d49..a23bbc6743f29 100644 --- a/content-ru/leetcode/Two Pointers/125-valid-palindrome.md +++ b/content-ru/leetcode/Two Pointers/125-valid-palindrome.md @@ -1,15 +1,32 @@ -# 125. Valid Palindrome (Easy) () +# 125. Валидный палиндром (Easy) () -> Фраза является палиндромом, если после приведения всех заглавных букв к строчным и удаления всех не буквенно-цифровых символов она читается одинаково слева направо и справа налево. +> Фраза является палиндромом, если после приведения всех заглавных букв к строчным и удаления всех не буквенно-цифровых символов она читается одинаково вперёд и назад. > Буквенно-цифровые символы включают буквы и цифры. -> Дана строка s, верните true, если это палиндром, иначе false. -> Ограничения: - 1 <= s.length <= 2 * 10^5 - s состоит только из печатаемых символов ASCII. +> Дана строка s, верните true, если она является палиндромом, или false в противном случае. +> Ограничения: - 1 <= s.length <= 2 * 10^5 - s состоит только из печатных символов ASCII. ```ts function isPalindrome(s: string): boolean { - const lc = s.toLocaleLowerCase().replace(/[^a-zA-Z\d]/g, "") - return lc === lc.split("").reverse().join("") + const lc = s.toLocaleLowerCase().replace(/[^a-zA-Z\d]/g, ""); + return lc === lc.split("").reverse().join(""); } + +// function isPalindrome(s: string): boolean { +// const lc = s.toLowerCase().replace(/[^a-z0-9]/g, ""); +// let i = 0, +// j = lc.length - 1; +// while (i < j) { +// if (lc[i] !== lc[j]) return false; +// i++; +// j--; +// } +// return true; +// } + +// Локальная проверка: +console.log(isPalindrome("A man, a plan, a canal: Panama")); +console.log(isPalindrome("race a car")); +console.log(isPalindrome(" ")); ``` ```md @@ -19,13 +36,13 @@ Example 1: Output: true Explanation: "amanaplanacanalpanama" is a palindrome. -Example 2: + Example 2: Input: s = "race a car" Output: false Explanation: "raceacar" is not a palindrome. -Example 3: + Example 3: Input: s = " " Output: true diff --git a/content-ru/leetcode/Two Pointers/151-reverse-words-in-a-string.md b/content-ru/leetcode/Two Pointers/151-reverse-words-in-a-string.md index 56e66b793c1d8..b0fd83149af28 100644 --- a/content-ru/leetcode/Two Pointers/151-reverse-words-in-a-string.md +++ b/content-ru/leetcode/Two Pointers/151-reverse-words-in-a-string.md @@ -1,26 +1,25 @@ # 151. Reverse Words in a String (Medium) () -> Дана входная строка s, разверните порядок слов. -> Слово определяется как последовательность непробельных символов. +> Дана входная строка s, необходимо изменить порядок слов на обратный. +> Словом называется последовательность непробельных символов. > Слова в s разделены хотя бы одним пробелом. > Верните строку из слов в обратном порядке, соединённых одним пробелом. -> Учтите, что s может содержать ведущие или замыкающие пробелы или несколько пробелов между словами. -> Возвращаемая строка должна содержать ровно один пробел между словами. -> Не добавляйте лишних пробелов. -> Ограничения: - 1 <= s.length <= 10^4 - s содержит английские буквы (заглавные и строчные), цифры и пробелы ' '. -> +> Обратите внимание, что s может содержать ведущие или завершающие пробелы, а также несколько пробелов между словами. +> В возвращённой строке слова должны быть разделены ровно одним пробелом. +> Не включайте лишние пробелы. +> Ограничения: - 1 <= s.length <= 10^4 - s содержит английские буквы (верхнего и нижнего регистра), цифры и пробелы ' '. > - В s есть хотя бы одно слово. -> Дополнительно: если тип данных строки в вашем языке изменяемый, сможете ли вы решить это на месте с O(1) дополнительной памяти? +> Дополнительный вопрос: если тип данных строки в вашем языке изменяемый, сможете ли вы решить задачу на месте с O(1) дополнительной памяти? ```ts function reverseWords(s: string): string { - return s.trim().split(/\s+/).reverse().join(" ") + return s.trim().split(/\s+/).reverse().join(" "); } // Local check: -console.log(reverseWords("the sky is blue")) -console.log(reverseWords(" hello world ")) -console.log(reverseWords("a good example")) +console.log(reverseWords("the sky is blue")); +console.log(reverseWords(" hello world ")); +console.log(reverseWords("a good example")); ``` ```md @@ -29,13 +28,13 @@ Example 1: Input: s = "the sky is blue" Output: "blue is sky the" -Example 2: + Example 2: Input: s = " hello world " Output: "world hello" Explanation: Your reversed string should not contain leading or trailing spaces. -Example 3: + Example 3: Input: s = "a good example" Output: "example good a" diff --git a/content-ru/leetcode/Two Pointers/1768-merge-strings-alternately.md b/content-ru/leetcode/Two Pointers/1768-merge-strings-alternately.md index 206bf92e19168..7ce05d6916107 100644 --- a/content-ru/leetcode/Two Pointers/1768-merge-strings-alternately.md +++ b/content-ru/leetcode/Two Pointers/1768-merge-strings-alternately.md @@ -1,51 +1,53 @@ -# 1768. Merge Strings Alternately (Easy) () +# 1768. Слияние строк через одну (Лёгкая) () > Даны две строки word1 и word2. -> Слейте строки, добавляя буквы в чередующемся порядке, начиная с word1. -> Если одна строка длиннее другой, добавьте оставшиеся буквы в конец итоговой строки. -> Верните итоговую строку. -> Ограничения: 1 <= word1.length, word2.length <= 100 word1 и word2 состоят из строчных латинских букв. +> Объедините строки, добавляя буквы в чередующемся порядке, начиная с word1. +> Если одна строка длиннее другой, добавьте оставшиеся буквы в конец объединённой строки. +> Верните объединённую строку. +> Ограничения: 1 <= word1.length, word2.length <= 100 word1 и word2 состоят из строчных английских букв. ```ts function mergeAlternately(word1: string, word2: string): string { const result: string[] = [] for (let i = 0; i < Math.max(word1.length, word2.length); i++) { - if (i < word1.length) result.push(word1[i]) - if (i < word2.length) result.push(word2[i]) + if (i < word1.length) + result.push(word1[i]) + if (i < word2.length) + result.push(word2[i]) } - return result.join("") + return result.join('') } -// Local check: -console.log(mergeAlternately("abc", "pqr")) -console.log(mergeAlternately("ab", "pqrs")) -console.log(mergeAlternately("abcd", "pq")) +// Локальная проверка: +console.log(mergeAlternately('abc', 'pqr')) +console.log(mergeAlternately('ab', 'pqrs')) +console.log(mergeAlternately('abcd', 'pq')) ``` ```md -Example 1: +Пример 1: - Input: word1 = "abc", word2 = "pqr" - Output: "apbqcr" - Explanation: The merged string will be merged as so: + Ввод: word1 = "abc", word2 = "pqr" + Вывод: "apbqcr" + Объяснение: Объединённая строка формируется так: word1: a b c word2: p q r merged: a p b q c r -Example 2: + Пример 2: - Input: word1 = "ab", word2 = "pqrs" - Output: "apbqrs" - Explanation: Notice that as word2 is longer, "rs" is appended to the end. + Ввод: word1 = "ab", word2 = "pqrs" + Вывод: "apbqrs" + Объяснение: Обратите внимание, что так как word2 длиннее, "rs" добавляется в конец. word1: a b word2: p q r s merged: a p b q r s -Example 3: + Пример 3: - Input: word1 = "abcd", word2 = "pq" - Output: "apbqcd" - Explanation: Notice that as word1 is longer, "cd" is appended to the end. + Ввод: word1 = "abcd", word2 = "pq" + Вывод: "apbqcd" + Объяснение: Обратите внимание, что так как word1 длиннее, "cd" добавляется в конец. word1: a b c d word2: p q merged: a p b q c d diff --git a/content-ru/leetcode/Two Pointers/345-reverse-vowels-of-a-string.md b/content-ru/leetcode/Two Pointers/345-reverse-vowels-of-a-string.md index 4c36e02dedaaf..eec60e4bcf59c 100644 --- a/content-ru/leetcode/Two Pointers/345-reverse-vowels-of-a-string.md +++ b/content-ru/leetcode/Two Pointers/345-reverse-vowels-of-a-string.md @@ -1,13 +1,13 @@ # 345. Reverse Vowels of a String (Easy) () -> Дана строка s, разверните только гласные в строке и верните её. -> Гласные — это 'a', 'e', 'i', 'o' и 'u', они могут встречаться и в нижнем, и в верхнем регистре, а также многократно. -> Ограничения: 1 <= s.length <= 3 * 10^5 s состоит из печатаемых символов ASCII. +> Дана строка s, нужно перевернуть в ней только гласные буквы и вернуть результат. +> Гласные — это 'a', 'e', 'i', 'o' и 'u', они могут встречаться как в нижнем, так и в верхнем регистре, и более одного раза. +> Ограничения: 1 <= s.length <= 3 * 10^5, s состоит из печатаемых ASCII-символов. ```ts function reverseVowels(s: string): string { - const chars = s.split("") - const vowels = "aeiouAEIOU" + const chars = s.split('') + const vowels = 'aeiouAEIOU' for (let left = 0, right = chars.length - 1; left < right;) { if (!vowels.includes(chars[left])) { @@ -28,26 +28,26 @@ function reverseVowels(s: string): string { right-- } - return chars.join("") + return chars.join('') } -// Local check: -console.log(reverseVowels("IceCreAm")) -console.log(reverseVowels("leetcode")) +// Локальная проверка: +console.log(reverseVowels('IceCreAm')) +console.log(reverseVowels('leetcode')) ``` ```md -Example 1: +Пример 1: - Input: s = "IceCreAm" - Output: "AceCreIm" - Explanation: The vowels in s are ['I', 'e', 'e', 'A']. On reversing the - vowels, s becomes "AceCreIm". + Вход: s = "IceCreAm" + Выход: "AceCreIm" + Объяснение: гласные в s — ['I', 'e', 'e', 'A']. После переворота + гласных s становится "AceCreIm". -Example 2: + Пример 2: - Input: s = "leetcode" - Output: "leotcede" + Вход: s = "leetcode" + Выход: "leotcede" ``` [[leetcode/Two Pointers/index|two-pointers]] diff --git a/content-ru/leetcode/Two Pointers/392-is-subsequence.md b/content-ru/leetcode/Two Pointers/392-is-subsequence.md index 44633ba99dc4b..aed5563aec099 100644 --- a/content-ru/leetcode/Two Pointers/392-is-subsequence.md +++ b/content-ru/leetcode/Two Pointers/392-is-subsequence.md @@ -1,9 +1,9 @@ -# 392. Is Subsequence (Easy) () +# 392. Является ли подпоследовательностью (Easy) () -> Даны две строки s и t, верните true, если s является подпоследовательностью t, иначе false. -> Подпоследовательность строки — это новая строка, полученная из исходной строки удалением некоторых (возможно, ни одного) символов без изменения относительного порядка оставшихся символов. -> (Например, "ace" — подпоследовательность "abcde", а "aec" — нет). -> Ограничения: - 0 <= s.length <= 100 - 0 <= t.length <= 10^4 - s и t состоят только из строчных латинских букв. +> Даны две строки s и t, верните true, если s является подпоследовательностью t, или false в противном случае. +> Подпоследовательность строки — это новая строка, образованная из исходной строки путём удаления некоторых (возможно, ни одного) символов без нарушения относительного порядка оставшихся символов. +> (то есть "ace" является подпоследовательностью "abcde", а "aec" — нет). +> Ограничения: - 0 <= s.length <= 100 - 0 <= t.length <= 10^4 - s и t состоят только из строчных английских букв. ```ts function isSubsequence(s: string, t: string): boolean { @@ -14,6 +14,7 @@ function isSubsequence(s: string, t: string): boolean { sIdx++ } } + return sIdx === s.length } @@ -24,11 +25,12 @@ console.log(isSubsequence("axc", "ahbgdc")) ```md Example 1: -Input: s = "abc", t = "ahbgdc" -Output: true -Example 2: -Input: s = "axc", t = "ahbgdc" -Output: false + Input: s = "abc", t = "ahbgdc" + Output: true + + Example 2: + Input: s = "axc", t = "ahbgdc" + Output: false ``` [[leetcode/Two Pointers/index|two-pointers]] diff --git a/content-ru/leetcode/Two Pointers/844-backspace-string-compare.md b/content-ru/leetcode/Two Pointers/844-backspace-string-compare.md index d3dead3458336..884a75324567b 100644 --- a/content-ru/leetcode/Two Pointers/844-backspace-string-compare.md +++ b/content-ru/leetcode/Two Pointers/844-backspace-string-compare.md @@ -1,10 +1,10 @@ # 844. Backspace String Compare (Easy) () -> Даны две строки s и t, верните true, если они равны при вводе в пустые текстовые редакторы. -> '#' означает символ backspace (стирание предыдущего символа). -> Учтите, что при стирании пустого текста он остаётся пустым. +> Даны две строки s и t. Верните true, если они окажутся равны при вводе в пустые текстовые редакторы. +> '#' означает символ backspace. +> Обратите внимание, что если применить backspace к пустому тексту, текст останется пустым. > Ограничения: - 1 <= s.length, t.length <= 200 - s и t содержат только строчные буквы и символы '#'. -> Дополнительно: сможете ли вы решить это за O(n) времени и O(1) памяти? +> Дополнительно: Можете ли вы решить эту задачу за O(n) времени и O(1) памяти? ```ts function backspaceCompare(s: string, t: string): boolean { @@ -12,66 +12,74 @@ function backspaceCompare(s: string, t: string): boolean { str .split("") .reduce((stack, ch) => { - ch === "#" ? stack.pop() : stack.push(ch) - return stack + ch === "#" ? stack.pop() : stack.push(ch); + return stack; }, []) - .join("") - return process(s) === process(t) + .join(""); + + return process(s) === process(t); } // interview function backspaceCompare2(s: string, t: string): boolean { - let i = s.length - 1 - let j = t.length - 1 - let skipS = 0 - let skipT = 0 + let i = s.length - 1; + let j = t.length - 1; + let skipS = 0; + let skipT = 0; while (i >= 0 || j >= 0) { while (i >= 0) { if (s[i] === "#") { - skipS++ - i-- + skipS++; + i--; } else if (skipS > 0) { - skipS-- - i-- - } else break + skipS--; + i--; + } else break; } while (j >= 0) { if (t[j] === "#") { - skipT++ - j-- + skipT++; + j--; } else if (skipT > 0) { - skipT-- - j-- - } else break + skipT--; + j--; + } else break; } - if (s[i] !== t[j]) return false - i-- - j-- + + if (s[i] !== t[j]) return false; + i--; + j--; } - return true + + return true; } // Local check: -console.log(backspaceCompare("ab#c", "ad#c")) -console.log(backspaceCompare("ab##", "c#d#")) -console.log(backspaceCompare("a#c", "b")) +console.log(backspaceCompare("ab#c", "ad#c")); +console.log(backspaceCompare("ab##", "c#d#")); +console.log(backspaceCompare("a#c", "b")); ``` ```md Example 1: -Input: s = "ab#c", t = "ad#c" -Output: true -Explanation: Both s and t become "ac". -Example 2: -Input: s = "ab##", t = "c#d#" -Output: true -Explanation: Both s and t become "". -Example 3: -Input: s = "a#c", t = "b" -Output: false -Explanation: s becomes "c" while t becomes "b". + + Input: s = "ab#c", t = "ad#c" + Output: true + Explanation: Both s and t become "ac". + + Example 2: + + Input: s = "ab##", t = "c#d#" + Output: true + Explanation: Both s and t become "". + + Example 3: + + Input: s = "a#c", t = "b" + Output: false + Explanation: s becomes "c" while t becomes "b". ``` [[leetcode/Two Pointers/index|two-pointers]] diff --git a/content-ru/leetcode/Two Pointers/index.md b/content-ru/leetcode/Two Pointers/index.md index 4bcb45aca1462..c7a411f5e1303 100644 --- a/content-ru/leetcode/Two Pointers/index.md +++ b/content-ru/leetcode/Two Pointers/index.md @@ -1,16 +1,16 @@ --- -title: two-pointers +title: два указателя --- -# Two Pointers +# Два указателя [[leetcode/index|← LeetCode]] -- [[Two-Pointers/125-valid-palindrome]] -- [[Two-Pointers/151-reverse-words-in-a-string]] -- [[Two-Pointers/1768-merge-strings-alternately]] -- [[Two-Pointers/345-reverse-vowels-of-a-string]] -- [[Two-Pointers/392-is-subsequence]] -- [[Two-Pointers/844-backspace-string-compare]] +- [[Two Pointers/125-valid-palindrome]] +- [[Two Pointers/151-reverse-words-in-a-string]] +- [[Two Pointers/1768-merge-strings-alternately]] +- [[Two Pointers/345-reverse-vowels-of-a-string]] +- [[Two Pointers/392-is-subsequence]] +- [[Two Pointers/844-backspace-string-compare]] #leetcode diff --git a/content-ru/leetcode/Untagged/125-valid-palindrome-neetcode.md b/content-ru/leetcode/Untagged/125-valid-palindrome-neetcode.md new file mode 100644 index 0000000000000..406d5000b09c9 --- /dev/null +++ b/content-ru/leetcode/Untagged/125-valid-palindrome-neetcode.md @@ -0,0 +1,49 @@ +# 125. Валидный палиндром (Easy) () + +> Фраза является палиндромом, если после преобразования всех заглавных букв в строчные и удаления всех неалфавитно-цифровых символов она читается одинаково вперёд и назад. +> Алфавитно-цифровые символы включают буквы и цифры. +> Дана строка s, верните true, если это палиндром, или false в противном случае. +> Ограничения: - 1 <= s.length <= 2 * 10^5 - s состоит только из печатаемых ASCII-символов. + +```ts +function isPalindrome(s: string): boolean { + const cleaned = s.toLowerCase().replace(/[^a-z0-9]/g, ''); + let left = 0, right = cleaned.length - 1; + + while (left < right) { + if (cleaned[left] !== cleaned[right]) return false; + left++; + right--; + } + + return true; +} + +// Локальная проверка: +console.log(isPalindrome("Was it a car or a cat I saw?")) // true +console.log(isPalindrome("tab a cat")) // false +console.log(isPalindrome(" ")) // true +console.log(isPalindrome("No lemon, no melon")) // true +``` + +```md +Пример 1: + + Ввод: s = "A man, a plan, a canal: Panama" + Вывод: true + Объяснение: "amanaplanacanalpanama" — палиндром. + + Пример 2: + + Ввод: s = "race a car" + Вывод: false + Объяснение: "raceacar" не является палиндромом. + + Пример 3: + + Ввод: s = " " + Вывод: true + Объяснение: Пустая строка является палиндромом. +``` + +#leetcode diff --git a/content-ru/leetcode/Untagged/2620-counter.md b/content-ru/leetcode/Untagged/2620-counter.md index 1339467de6c4b..52c19433307b9 100644 --- a/content-ru/leetcode/Untagged/2620-counter.md +++ b/content-ru/leetcode/Untagged/2620-counter.md @@ -1,9 +1,8 @@ # 2620. Counter (?) () - > Дано целое число n, верните функцию-счётчик. -> Эта функция-счётчик изначально возвращает n, а затем при каждом следующем вызове возвращает на 1 больше предыдущего значения (n, n + 1, n + 2 и т.д.). +> Эта функция-счётчик изначально возвращает n, а затем при каждом последующем вызове возвращает значение на 1 больше предыдущего (n, n + 1, n + 2 и т.д.). ```ts function createCounter(n: number): () => number { @@ -25,7 +24,7 @@ Example 1: counter() = 11 // Returns 1 more than the previous time. counter() = 12 // Returns 1 more than the previous time. -Example 2: + Example 2: Input: n = -2 diff --git a/content-ru/leetcode/Untagged/2622-cache-with-time-limit.md b/content-ru/leetcode/Untagged/2622-cache-with-time-limit.md index 94e223de87443..67a9624d92eaf 100644 --- a/content-ru/leetcode/Untagged/2622-cache-with-time-limit.md +++ b/content-ru/leetcode/Untagged/2622-cache-with-time-limit.md @@ -1,18 +1,18 @@ # 2622. Cache With Time Limit (Medium) () -> Напишите класс, позволяющий получать и устанавливать пары ключ-значение, при этом с каждым ключом связано время до истечения срока действия. -> У класса есть три публичных метода: set(key, value, duration): принимает целочисленный ключ key, целочисленное значение value и длительность duration в миллисекундах. -> После истечения duration ключ должен стать недоступным. -> Метод должен вернуть true, если такой же неистёкший ключ уже существует, иначе false. -> Если ключ уже существует, и значение, и длительность должны быть перезаписаны. -> get(key): если неистёкший ключ существует, метод должен вернуть связанное значение. -> Иначе он должен вернуть -1. +> Напишите класс, который позволяет получать и устанавливать пары ключ-значение, при этом с каждым ключом связано время до истечения срока действия. +> Класс имеет три публичных метода: set(key, value, duration): принимает целочисленный ключ, целочисленное значение и продолжительность в миллисекундах. +> По истечении этого времени ключ должен становиться недоступным. +> Метод должен возвращать true, если такой же неистёкший ключ уже существует, и false в противном случае. +> Если ключ уже существует, значение и продолжительность должны быть перезаписаны. +> get(key): если существует неистёкший ключ, метод должен вернуть связанное значение. +> В противном случае должно возвращаться -1. > count(): возвращает количество неистёкших ключей. -> Ограничения: - 0 <= key, value <= 10^9 - 0 <= duration <= 1000 - 1 <= actions.length <= 100 - actions.length === values.length - actions.length === timeDelays.length - 0 <= timeDelays[i] <= 1450 - actions[i] — одно из "TimeLimitedCache", "set", "get", "count" - Первое действие всегда "TimeLimitedCache" и должно выполниться немедленно +> Ограничения: - 0 <= key, value <= 10^9 - 0 <= duration <= 1000 - 1 <= actions.length <= 100 - actions.length === values.length - actions.length === timeDelays.length - 0 <= timeDelays[i] <= 1450 - actions[i] является одним из "TimeLimitedCache", "set", "get" и "count" - Первое действие всегда "TimeLimitedCache" и должно быть выполнено немедленно ```ts class TimeLimitedCache { - cache: Map }> + cache: Map }> constructor() { this.cache = new Map() @@ -40,47 +40,54 @@ class TimeLimitedCache { return this.cache.size } } + + +const timeLimitedCache = new TimeLimitedCache() +setTimeout(() => console.log(timeLimitedCache.set(1, 42, 50)), 0) // false +setTimeout(() => console.log(timeLimitedCache.set(1, 50, 100)), 40) // true +setTimeout(() => console.log(timeLimitedCache.get(1)), 50) // 50 +setTimeout(() => console.log(timeLimitedCache.get(1)), 120)// 50 +setTimeout(() => console.log(timeLimitedCache.get(1)), 200) // -1 +setTimeout(() => console.log(timeLimitedCache.count()), 250) // 0 ``` ```md -Example 1: +Пример 1: - Input: + Ввод: actions = ["TimeLimitedCache", "set", "get", "count", "get"] values = [[], [1, 42, 100], [1], [], [1]] timeDelays = [0, 0, 50, 50, 150] - Output: [null, false, 42, 1, -1] - Explanation: - At t=0, the cache is constructed. - At t=0, a key-value pair (1: 42) is added with a time limit of 100ms. - The value doesn't exist so false is returned. - At t=50, key=1 is requested and the value of 42 is returned. - At t=50, count() is called and there is one active key in the cache. - At t=100, key=1 expires. - At t=150, get(1) is called but -1 is returned because the cache is empty. + Вывод: [null, false, 42, 1, -1] + Объяснение: + В момент t=0 кэш создаётся. + В момент t=0 добавляется пара ключ-значение (1: 42) с ограничением по времени 100мс. + Значение не существует, поэтому возвращается false. + В момент t=50 запрашивается ключ=1 и возвращается значение 42. + В момент t=50 вызывается count() и в кэше есть один активный ключ. + В момент t=100 ключ=1 истекает. + В момент t=150 вызывается get(1), но возвращается -1, потому что кэш пуст. -Example 2: + Пример 2: - Input: + Ввод: actions = ["TimeLimitedCache", "set", "set", "get", "get", "get", "count"] values = [[], [1, 42, 50], [1, 50, 100], [1], [1], [1], []] timeDelays = [0, 0, 40, 50, 120, 200, 250] - Output: [null, false, true, 50, 50, -1, 0] - Explanation: - At t=0, the cache is constructed. - At t=0, a key-value pair (1: 42) is added with a time limit of 50ms. - The value doesn't exist so false is returned. - + Вывод: [null, false, true, 50, 50, -1, 0] + Объяснение: + В момент t=0 кэш создаётся. + В момент t=0 добавляется пара ключ-значение (1: 42) с ограничением по времени 50мс. + Значение не существует, поэтому возвращается false. - - At t=40, a key-value pair (1: 50) is added with a time limit of 100ms. - A non-expired value already existed so true is returned and the old value - was overwritten. - At t=50, get(1) is called which returned 50. - At t=120, get(1) is called which returned 50. - At t=140, key=1 expires. - At t=200, get(1) is called but the cache is empty so -1 is returned. - At t=250, count() returns 0 because the cache is empty. + В момент t=40 добавляется пара ключ-значение (1: 50) с ограничением по времени 100мс. + Неистёкшее значение уже существовало, поэтому возвращается true, а старое значение + было перезаписано. + В момент t=50 вызывается get(1), которое вернуло 50. + В момент t=120 вызывается get(1), которое вернуло 50. + В момент t=140 ключ=1 истекает. + В момент t=200 вызывается get(1), но кэш пуст, поэтому возвращается -1. + В момент t=250 count() возвращает 0, потому что кэш пуст. ``` #leetcode diff --git a/content-ru/leetcode/Untagged/2623-memoize.md b/content-ru/leetcode/Untagged/2623-memoize.md index 5c30ae3176759..d81932f516923 100644 --- a/content-ru/leetcode/Untagged/2623-memoize.md +++ b/content-ru/leetcode/Untagged/2623-memoize.md @@ -1,12 +1,12 @@ # 2623. Memoize (Medium) () > Дана функция fn, верните мемоизированную версию этой функции. -> Мемоизированная функция — это функция, которая никогда не вызывается дважды с одинаковыми входными данными. -> Вместо этого она возвращает закэшированное значение. +> Мемоизированная функция — это функция, которая никогда не будет вызвана дважды с одинаковыми входными данными. +> Вместо этого она будет возвращать закэшированное значение. > Можно считать, что есть 3 возможные входные функции: sum, fib и factorial. > sum принимает два целых числа a и b и возвращает a + b. -> Учтите, что если значение уже закэшировано для аргументов (b, a), где a != b, оно не может быть использовано для аргументов (a, b). -> Например, если аргументы — (3, 2) и (2, 3), должны быть сделаны два отдельных вызова. +> Предположим, что если значение уже закэшировано для аргументов (b, a), где a != b, оно не может быть использовано для аргументов (a, b). +> Например, если аргументы (3, 2) и (2, 3), должны быть сделаны два отдельных вызова. > fib принимает одно целое число n и возвращает 1, если n <= 1, иначе fib(n - 1) + fib(n - 2). > factorial принимает одно целое число n и возвращает 1, если n <= 1, иначе factorial(n - 1)n. @@ -54,15 +54,13 @@ Example 1: memoizedSum(1, 2); // "call" - returns 3. sum() was called as (1, 2) was not seen before. // "getCallCount" - total call count: 2 -Example 2: + Example 2: Input: fnName = "factorial" actions = ["call","call","call","getCallCount","call","getCallCount"] values = [[2],[3],[2],[],[3],[]] - - Output: [2,6,2,2,6,2] Explanation: const factorial = (n) => (n <= 1) ? 1 : (nfactorial(n - 1)); @@ -74,7 +72,7 @@ Example 2: memoFactorial(3); // "call" - returns 6. However factorial was not called because 3 was seen before. // "getCallCount" - total call count: 2 -Example 3: + Example 3: Input: fnName = "fib" diff --git a/content-ru/leetcode/Untagged/2626-array-reduce-transformation.md b/content-ru/leetcode/Untagged/2626-array-reduce-transformation.md index 5e7a415c5a884..aa40704dc0cc8 100644 --- a/content-ru/leetcode/Untagged/2626-array-reduce-transformation.md +++ b/content-ru/leetcode/Untagged/2626-array-reduce-transformation.md @@ -1,10 +1,10 @@ -# 2626. Array Reduce Transformation (Easy) () +# 2626. Массив: трансформация с помощью Reduce (Easy) () -> Дан целочисленный массив nums, функция-редьюсер fn и начальное значение init, верните итоговый результат, полученный последовательным выполнением функции fn на каждом элементе массива, передавая на вход возвращённое значение вычисления на предыдущем элементе. -> Результат достигается следующими операциями: val = fn(init, nums[0]), val = fn(val, nums[1]), val = fn(val, nums[2]), ... +> Дан массив целых чисел nums, функция-редьюсер fn и начальное значение init. Верните итоговый результат, полученный выполнением функции fn для каждого элемента массива последовательно, передавая при этом возвращаемое значение вычисления для предыдущего элемента. +> Этот результат достигается следующими операциями: val = fn(init, nums[0]), val = fn(val, nums[1]), val = fn(val, nums[2]), ... > пока не будут обработаны все элементы массива. > Если длина массива равна 0, функция должна вернуть init. -> Решите без использования встроенного метода Array.reduce. +> Решите задачу, не используя встроенный метод Array.reduce. > Ограничения: - 0 <= nums.length <= 1000 - 0 <= nums[i] <= 1000 - 0 <= init <= 1000 ```ts @@ -18,55 +18,53 @@ function reduce(nums: number[], fn: Fn, init: number): number { return acc } -// Local check: +// Локальная проверка: console.log(reduce([1, 2, 3, 4], (accum, curr) => accum + curr, 0)) // 10 console.log(reduce([1, 2, 3, 4], (accum, curr) => accum + curr * curr, 100)) // 130 console.log(reduce([], () => 0, 25)) // 25 ``` ```md -Example 1: +Пример 1: - Input: + Вход: nums = [1,2,3,4] fn = function sum(accum, curr) { return accum + curr; } init = 0 - Output: 10 - Explanation: - initially, the value is init=0. + Выход: 10 + Объяснение: + изначально значение init=0. (0) + nums[0] = 1 (1) + nums[1] = 3 (3) + nums[2] = 6 (6) + nums[3] = 10 - The final answer is 10. + Итоговый ответ — 10. -Example 2: + Пример 2: - Input: + Вход: nums = [1,2,3,4] fn = function sum(accum, curr) { return accum + curr * curr; } init = 100 - Output: 130 - Explanation: - initially, the value is init=100. + Выход: 130 + Объяснение: + изначально значение init=100. (100) + nums[0] * nums[0] = 101 (101) + nums[1] * nums[1] = 105 (105) + nums[2] * nums[2] = 114 (114) + nums[3] * nums[3] = 130 - + Итоговый ответ — 130. - The final answer is 130. - -Example 3: + Пример 3: - Input: + Вход: nums = [] fn = function sum(accum, curr) { return 0; } init = 25 - Output: 25 - Explanation: - For empty arrays, the answer is always init. + Выход: 25 + Объяснение: + Для пустых массивов ответ всегда равен init. ``` #leetcode diff --git a/content-ru/leetcode/Untagged/2627-debounce.md b/content-ru/leetcode/Untagged/2627-debounce.md index 34fc346533ef3..1ded38969e0a2 100644 --- a/content-ru/leetcode/Untagged/2627-debounce.md +++ b/content-ru/leetcode/Untagged/2627-debounce.md @@ -1,10 +1,10 @@ # 2627. Debounce (Medium) () -> Дана функция fn и время t в миллисекундах, верните debounce-версию этой функции. -> Debounce-функция — это функция, выполнение которой откладывается на t миллисекунд и отменяется, если она вызывается снова в течение этого окна времени. -> Debounce-функция также должна принимать переданные параметры. -> Например, если t = 50мс, и функция была вызвана в 30мс, 60мс и 100мс, первые 2 вызова функции будут отменены, а 3-й вызов выполнится в 150мс. -> Решите без использования функции _.debounce() из lodash. +> Дана функция fn и время в миллисекундах t, верните debounced-версию этой функции. +> Debounced-функция — это функция, выполнение которой откладывается на t миллисекунд, и выполнение отменяется, если она вызывается снова в течение этого временного окна. +> Debounced-функция также должна получать переданные параметры. +> Например, если t = 50ms и функция была вызвана на 30ms, 60ms и 100ms, первые 2 вызова функции будут отменены, а 3-й вызов функции выполнится на 150ms. +> Пожалуйста, решите без использования функции _.debounce() из lodash. > Ограничения: - 0 <= t <= 1000 - 1 <= calls.length <= 10 - 0 <= calls[i].t <= 1000 - 0 <= calls[i].inputs.length <= 10 ```ts @@ -23,16 +23,17 @@ function debounce(fn: F, t: number): F { } const log = debounce(console.log, 100) -log("Hello") // cancelled -console.log("1") -log("Hello") // cancelled -console.log("2") -log("Hello") // Logged at t=100ms +log('Hello') // cancelled +console.log('1') +log('Hello') // cancelled +console.log('2') +log('Hello') // Logged at t=100ms ``` ```md -Example 1: +Пример 1: + Input: t = 50 calls = [ @@ -45,7 +46,7 @@ Example 1: before 100ms. The 2nd call is delayed by 50ms and executed at 125ms. The inputs were (2). -Example 2: + Пример 2: Input: t = 20 @@ -58,9 +59,7 @@ Example 2: The 1st call is delayed until 70ms. The inputs were (1). The 2nd call is delayed until 120ms. The inputs were (2). -Example 3: - - + Пример 3: Input: t = 150 diff --git a/content-ru/leetcode/Untagged/2629-function-composition.md b/content-ru/leetcode/Untagged/2629-function-composition.md index dc76c073fba15..4505b2c1a4ca2 100644 --- a/content-ru/leetcode/Untagged/2629-function-composition.md +++ b/content-ru/leetcode/Untagged/2629-function-composition.md @@ -1,23 +1,12 @@ -# 2629. Function Composition (Easy) () +# 2629. Композиция функций (Лёгкая) () -> Дан массив функций [f1, f2, f3, ..., fn], верните новую функцию fn — композицию этого массива функций. -> Композиция [f(x), g(x), h(x)] — это fn(x) = f(g(h(x))). -> Композиция пустого списка функций — это функция-идентичность f(x) = x. -> Можно считать, что каждая функция массива принимает одно целое число на вход и возвращает одно целое число. +> Дан массив функций [f1, f2, f3, ..., fn], верните новую функцию fn, которая является композицией функций из массива. +> Композиция функций [f(x), g(x), h(x)] — это fn(x) = f(g(h(x))). +> Композиция пустого списка функций — это тождественная функция f(x) = x. +> Можно считать, что каждая функция в массиве принимает одно целое число и возвращает одно целое число. > Ограничения: - -1000 <= x <= 1000 - 0 <= functions.length <= 1000 - все функции принимают и возвращают одно целое число ```ts -function f(x) = x. - - You may assume each function in the array accepts one integer as input and - returns one integer as output. - - Constraints: - - -1000 <= x <= 1000 - - 0 <= functions.length <= 1000 - - all functions accept and return a single integer -*/ - type Fn = (x: number) => number function compose(functions: Fn[]): Fn { @@ -44,7 +33,7 @@ Example 1: 8 * 8 = 64 64 + 1 = 65 -Example 2: + Example 2: Input: functions = [x => 10 * x, x => 10 * x, x => 10 * x] @@ -53,13 +42,11 @@ Example 2: Explanation: Evaluating from right to left ... 10 * 1 = 10 - - 10 * 10 = 100 10 * 100 = 1000 -Example 3: + Example 3: Input: functions = [] diff --git a/content-ru/leetcode/Untagged/2631-group-by.md b/content-ru/leetcode/Untagged/2631-group-by.md index 607d340a2b9f1..248ace74e7460 100644 --- a/content-ru/leetcode/Untagged/2631-group-by.md +++ b/content-ru/leetcode/Untagged/2631-group-by.md @@ -1,15 +1,23 @@ # 2631. Group By (Medium) () -> Напишите код, расширяющий все массивы так, чтобы можно было вызвать метод array.groupBy(fn) на любом массиве, и он вернёт сгруппированную версию массива. -> Сгруппированный массив — это объект, где каждый ключ — результат fn(arr[i]), а каждое значение — массив, содержащий все элементы исходного массива, которые дают этот ключ. +> Напишите код, который расширяет все массивы так, чтобы можно было вызывать метод array.groupBy(fn) у любого массива, и он возвращал бы сгруппированную версию массива. +> Сгруппированный массив — это объект, где каждый ключ является результатом fn(arr[i]), а каждое значение — массив, содержащий все элементы исходного массива, которые порождают этот ключ. > Переданный колбэк fn принимает элемент массива и возвращает строковый ключ. -> Порядок элементов в каждом списке значений должен совпадать с порядком их появления в массиве. +> Порядок элементов в каждом списке значений должен соответствовать порядку их появления в массиве. > Порядок ключей может быть любым. -> Решите без использования функции _.groupBy из lodash. +> Пожалуйста, решите без использования функции _.groupBy из lodash. > Ограничения: 0 <= array.length <= 10^5 fn возвращает строку ```ts -const result: Record = {} +declare global { + interface Array { + groupBy: (fn: (item: T) => string) => Record + } +} + +// eslint-disable-next-line no-extend-native +Array.prototype.groupBy = function (this: T[], fn: (item: T) => string): Record { + const result: Record = {} for (const item of this) { const key = fn(item) @@ -25,10 +33,13 @@ const result: Record = {} return result } -// Local check: +// Локальная проверка: console.log([{ id: '1' }, { id: '1' }, { id: '2' }].groupBy(item => item.id)) console.log([[1, 2, 3], [1, 3, 5], [1, 5, 9]].groupBy(list => String(list[0]))) console.log([1, 2, 3, 4, 5, 6, 7, 8, 9, 10].groupBy(n => String(n > 5))) + + +export {} ``` ```md @@ -55,15 +66,13 @@ Example 1: the first array. There is one object with an "id" of 2. That object is put in the second array. -Example 2: + Example 2: Input: array = [ [1, 2, 3], [1, 3, 5], - - [1, 5, 9] ] fn = function (list) { @@ -78,7 +87,7 @@ Example 2: the key as being the first element in the array. All the arrays have 1 as their first element so they are grouped together. -Example 3: + Example 3: Input: array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] diff --git a/content-ru/leetcode/Untagged/2637-promise-time-limit.md b/content-ru/leetcode/Untagged/2637-promise-time-limit.md index 29c5e9dfda629..b6ca09ea0c5a1 100644 --- a/content-ru/leetcode/Untagged/2637-promise-time-limit.md +++ b/content-ru/leetcode/Untagged/2637-promise-time-limit.md @@ -2,22 +2,11 @@ > Дана асинхронная функция fn и время t в миллисекундах, верните новую версию входной функции с ограничением по времени. > fn принимает аргументы, переданные функции с ограничением по времени. -> Функция с ограничением по времени должна следовать этим правилам: - Если fn завершится в пределах лимита времени t миллисекунд, функция с ограничением по времени должна резолвиться с результатом. -> -> - Если выполнение fn превышает лимит времени, функция с ограничением по времени должна реджектиться со строкой "Time Limit Exceeded". -> Ограничения: - 0 <= inputs.length <= 10 - 0 <= t <= 1000 - fn возвращает promise +> Функция с ограничением по времени должна следовать этим правилам: - Если fn завершается в пределах лимита времени t миллисекунд, функция с ограничением по времени должна разрешиться (resolve) с результатом. +> - Если выполнение fn превышает лимит времени, функция с ограничением по времени должна отклониться (reject) со строкой "Time Limit Exceeded". +> Ограничения: - 0 <= inputs.length <= 10 - 0 <= t <= 1000 - fn возвращает promise ```ts -function should resolve with the result. - - If the execution of fn exceeds the time limit, the time limited function - should reject with the string "Time Limit Exceeded". - - Constraints: - - 0 <= inputs.length <= 10 - - 0 <= t <= 1000 - - fn returns a promise -*/ - type Fn = (...params: any[]) => Promise function timeLimit(fn: Fn, t: number): Fn { @@ -49,7 +38,7 @@ Example 1: The provided function is set to resolve after 100ms. However, the time limit is set to 50ms. It rejects at t=50ms because the time limit was reached. -Example 2: + Example 2: Input: fn = async (n) => { @@ -62,9 +51,7 @@ Example 2: Explanation: The function resolved 5 * 5 = 25 at t=100ms. The time limit is never reached. - - -Example 3: + Example 3: Input: fn = async (a, b) => { @@ -77,7 +64,7 @@ Example 3: Explanation: The function resolved 5 + 10 = 15 at t=120ms. The time limit is never reached. -Example 4: + Example 4: Input: fn = async () => { diff --git a/content-ru/leetcode/Untagged/2665-counter2.md b/content-ru/leetcode/Untagged/2665-counter2.md index 6fdcbf2ffe34d..6b91e8d104d6a 100644 --- a/content-ru/leetcode/Untagged/2665-counter2.md +++ b/content-ru/leetcode/Untagged/2665-counter2.md @@ -1,16 +1,20 @@ # 2665. Counter II (?) () - > Напишите функцию createCounter. > Она должна принимать начальное целое число init. -> Она должна вернуть объект с тремя функциями. +> Она должна возвращать объект с тремя функциями. > Эти три функции: - increment() увеличивает текущее значение на 1 и возвращает его. -> > - decrement() уменьшает текущее значение на 1 и возвращает его. -> - reset() устанавливает текущее значение в init и возвращает его. +> - reset() устанавливает текущее значение равным init и возвращает его. ```ts +interface Counter { + increment: () => number + decrement: () => number + reset: () => number +} + function createCounter(init: number): Counter { let value = init @@ -19,7 +23,7 @@ function createCounter(init: number): Counter { decrement: () => --value, reset: () => (value = init), } -} +}; ``` ```md @@ -33,7 +37,7 @@ Example 1: counter.reset(); // 5 counter.decrement(); // 4 -Example 2: + Example 2: Input: init = 0, calls = ["increment","increment","decrement","reset","reset"] Output: [1,2,1,0,0] diff --git a/content-ru/leetcode/Untagged/2666-allow-one-fn-call.md b/content-ru/leetcode/Untagged/2666-allow-one-fn-call.md index 241db3bb922ad..86633558e9f1a 100644 --- a/content-ru/leetcode/Untagged/2666-allow-one-fn-call.md +++ b/content-ru/leetcode/Untagged/2666-allow-one-fn-call.md @@ -1,9 +1,8 @@ -# 2666. Allow One Function Call (?) () +# 2666. Разрешить только один вызов функции (?) () - -> Дана функция fn, верните новую функцию, идентичную исходной, но гарантирующую, что fn будет вызвана не более одного раза. -> При первом вызове возвращённой функции она должна вернуть тот же результат, что и fn. +> Дана функция fn, верните новую функцию, идентичную исходной, за исключением того, что она гарантирует вызов fn не более одного раза. +> При первом вызове возвращённая функция должна вернуть тот же результат, что и fn. > При каждом последующем вызове она должна возвращать undefined. ```ts @@ -14,7 +13,8 @@ function once(fn: Function): OnceFn { let called = false return function (...args: JSONValue[]): JSONValue | undefined { - if (called) return undefined + if (called) + return undefined called = true return fn(...args) @@ -25,16 +25,16 @@ function once(fn: Function): OnceFn { ```md Example 1: -Input: fn = (a,b,c) => (a + b + c), calls = [[1,2,3],[2,3,6]] + Input: fn = (a,b,c) => (a + b + c), calls = [[1,2,3],[2,3,6]] Output: [{"calls":1,"value":6}] Explanation: const onceFn = once(fn); onceFn(1, 2, 3); // 6 onceFn(2, 3, 6); // undefined, fn was not called -Example 2: + Example 2: -Input: fn = (a,b,c) => (a * b * c), calls = [[5,7,4],[2,3,6],[4,6,8]] + Input: fn = (a,b,c) => (a * b * c), calls = [[5,7,4],[2,3,6],[4,6,8]] Output: [{"calls":1,"value":140}] Explanation: const onceFn = once(fn); diff --git a/content-ru/leetcode/Untagged/2677-chunk-array.md b/content-ru/leetcode/Untagged/2677-chunk-array.md index 5c581b61d3d26..25e99a330c0b1 100644 --- a/content-ru/leetcode/Untagged/2677-chunk-array.md +++ b/content-ru/leetcode/Untagged/2677-chunk-array.md @@ -1,11 +1,11 @@ # 2677. Chunk Array (Easy) () -> Дан массив arr и размер чанка size, верните массив, разбитый на чанки. -> Разбитый на чанки массив содержит исходные элементы arr, но состоит из подмассивов длиной size каждый. +> Дан массив arr и размер чанка size, верните разбитый на чанки массив. +> Разбитый на чанки массив содержит исходные элементы из arr, но состоит из подмассивов, каждый длиной size. > Длина последнего подмассива может быть меньше size, если arr.length не делится на size без остатка. -> Можно считать, что массив — результат JSON.parse. +> Можно считать, что массив является результатом JSON.parse. > Другими словами, это валидный JSON. -> Решите без использования функции _.chunk из lodash. +> Пожалуйста, решите без использования функции _.chunk из lodash. > Ограничения: arr — валидный JSON-массив 2 <= JSON.stringify(arr).length <= 10^5 1 <= size <= arr.length + 1 ```ts @@ -18,7 +18,7 @@ function chunk(arr: Obj[], size: number): Obj[][] { result.push(arr.slice(i, i + size)) } return result -} +}; // function chunk(arr: Obj[], size: number): Obj[][] { // return arr.reduce((acc, item, index) => { @@ -46,22 +46,21 @@ Example 1: Output: [[1],[2],[3],[4],[5]] Explanation: The arr has been split into subarrays each with 1 element. -Example 2: + Example 2: Input: arr = [1,9,6,3,2], size = 3 Output: [[1,9,6],[3,2]] Explanation: The arr has been split into subarrays with 3 elements. However, only two elements are left for the 2nd subarray. -Example 3: + Example 3: Input: arr = [8,5,3,2,6], size = 6 Output: [[8,5,3,2,6]] Explanation: Size is greater than arr.length thus all elements are in the first subarray. -Example 4: + Example 4: - Input: arr = [], size = 1 Output: [] Explanation: There are no elements to be chunked so an empty array is returned. diff --git a/content-ru/leetcode/Untagged/2693-call-function-with-custom-context.md b/content-ru/leetcode/Untagged/2693-call-function-with-custom-context.md index 875b222479a37..19ee2e83d66c7 100644 --- a/content-ru/leetcode/Untagged/2693-call-function-with-custom-context.md +++ b/content-ru/leetcode/Untagged/2693-call-function-with-custom-context.md @@ -1,12 +1,11 @@ -# 2693. Call Function with Custom Context (Medium) () +# 2693. Вызов функции с пользовательским контекстом (Medium) () - > Расширьте все функции методом callPolyfill. > Метод принимает объект obj в качестве первого параметра и любое количество дополнительных аргументов. > obj становится контекстом this для функции. > Дополнительные аргументы передаются в функцию, которой принадлежит метод callPolyfill. -> Решите без использования встроенного метода Function.call. +> Решите задачу без использования встроенного метода Function.call. > Ограничения: - typeof args[0] == "object" и args[0] != null - 1 <= args.length <= 100 - 2 <= JSON.stringify(args[0]).length <= 10^5 ```ts @@ -15,6 +14,26 @@ type JSONValue = null | boolean | number | string | JSONValue[] | { [key: string interface Function { callPolyfill: (context: Record, ...args: JSONValue[]) => JSONValue } + +/* Временно делаем функцию методом объекта */ +Function.prototype.callPolyfill = function (context, ...args): JSONValue { + let object = { ...context } as any + let symbol = Symbol('context') + // this здесь — это функция + object[symbol] = this + // Вызываем add как метод object + return object[symbol](...args) +} + +// Локальная проверка: +function add(this: { a: number }, b: number) { + return this.a + b +} + +console.log(add.callPolyfill({ a: 5 }, 7)) // 12 + + +export {} ``` ```md @@ -31,7 +50,7 @@ Example 1: callPolyfill sets the "this" context to { "a": 5 }. 7 is passed as an argument. -Example 2: + Example 2: Input: fn = function tax(price, taxRate) { diff --git a/content-ru/leetcode/Untagged/2703-return-length-of-arguments-passed.md b/content-ru/leetcode/Untagged/2703-return-length-of-arguments-passed.md index 0ffbe32dd32b0..8f04f2e296c9f 100644 --- a/content-ru/leetcode/Untagged/2703-return-length-of-arguments-passed.md +++ b/content-ru/leetcode/Untagged/2703-return-length-of-arguments-passed.md @@ -1,9 +1,8 @@ -# 2703. Return Length of Arguments Passed (Easy) () +# 2703. Верните количество переданных аргументов (Легко) () - -> Напишите функцию argumentsLength, возвращающую количество переданных ей аргументов. -> Ограничения: - args — валидный JSON-массив - 0 <= args.length <= 100 +> Напишите функцию argumentsLength, которая возвращает количество переданных ей аргументов. +> Ограничения: - args является валидным JSON-массивом - 0 <= args.length <= 100 ```ts type JSONValue = null | boolean | number | string | JSONValue[] | { [key: string]: JSONValue } @@ -17,27 +16,27 @@ function argumentsLength(...args: JSONValue[]): number { console.log(argumentsLength(1, 2, 3)) // 3 console.log(argumentsLength(5)) // 1 -console.log(argumentsLength({}, null, "3")) // 3 +console.log(argumentsLength({}, null, '3')) // 3 ``` ```md -Example 1: +Пример 1: - Input: args = [5] - Output: 1 - Explanation: + Ввод: args = [5] + Вывод: 1 + Объяснение: argumentsLength(5); // 1 - One value was passed to the function so it should return 1. + В функцию было передано одно значение, поэтому она должна вернуть 1. -Example 2: + Пример 2: - Input: args = [{}, null, "3"] - Output: 3 - Explanation: + Ввод: args = [{}, null, "3"] + Вывод: 3 + Объяснение: argumentsLength({}, null, "3"); // 3 - Three values were passed to the function so it should return 3. + В функцию было передано три значения, поэтому она должна вернуть 3. ``` #leetcode diff --git a/content-ru/leetcode/Untagged/271-string-encode-and-decode.md b/content-ru/leetcode/Untagged/271-string-encode-and-decode.md new file mode 100644 index 0000000000000..7120d7e366658 --- /dev/null +++ b/content-ru/leetcode/Untagged/271-string-encode-and-decode.md @@ -0,0 +1,64 @@ +# 271. Кодирование и декодирование строк (Medium) () + +> Разработайте алгоритм для кодирования списка строк в одну строку. +> Закодированная строка затем декодируется обратно в исходный список строк. +> Ограничения / Примечания: - Входные строки могут содержать любые символы. +> - Необходимо обеспечить однозначную обратимость кодирования. + +```ts +class Codec { + constructor() { + + } + + encode(strs: string[]): string { + // [length] + "#" + [data] + let encoded_string = '' + for (const word of strs) { + encoded_string += word.length + '#' + word + } + return encoded_string + } + + decode(s: string): string[] { + const decoded: string[] = [] + let idx = 0 + + while (idx < s.length) { + let length: string = '' + while (idx < s.length && s[idx] !== '#') { + length += s[idx] + idx += 1 + } + const numLength = Number(length) + decoded.push(s.slice(idx + 1, idx + numLength + 1)) + idx += numLength + 1 + } + return decoded + } +} + + +// Local check: +const codec = new Codec() + +console.log(codec.decode(codec.encode(["hello", "world"]))) +console.log(codec.decode(codec.encode(["lint", "code", "love", "you"]))) +console.log(codec.decode(codec.encode([""]))) +``` + +```md +Пример 1: + + Вход: ["hello","world"] + Выход: ["hello","world"] + Объяснение: + После кодирования и последующего декодирования мы получаем обратно исходный массив. + + Пример 2: + + Вход: ["lint","code","love","you"] + Выход: ["lint","code","love","you"] +``` + +#leetcode diff --git a/content-ru/leetcode/Untagged/2715-timeout-cancellation.md b/content-ru/leetcode/Untagged/2715-timeout-cancellation.md index a781fa7000ea3..14efb7c75dc76 100644 --- a/content-ru/leetcode/Untagged/2715-timeout-cancellation.md +++ b/content-ru/leetcode/Untagged/2715-timeout-cancellation.md @@ -1,9 +1,9 @@ -# 2715. Timeout Cancellation (Easy) () +# 2715. Отмена таймаута (Easy) () -> Дана функция fn, массив аргументов args и таймаут t в миллисекундах, верните функцию отмены cancelFn. -> После задержки в cancelTimeMs возвращённая функция отмены cancelFn будет вызвана: setTimeout(cancelFn, cancelTimeMs) Изначально выполнение fn должно быть отложено на t миллисекунд. -> Если cancelFn вызывается до истечения задержки t миллисекунд, она должна отменить отложенное выполнение fn. -> Иначе fn должна быть выполнена с args в качестве аргументов. +> Дана функция fn, массив аргументов args и таймаут t в миллисекундах, необходимо вернуть функцию отмены cancelFn. +> После задержки в cancelTimeMs миллисекунд будет вызвана возвращённая функция отмены cancelFn: setTimeout(cancelFn, cancelTimeMs) Изначально выполнение fn должно быть отложено на t миллисекунд. +> Если cancelFn будет вызвана до истечения задержки в t миллисекунд, она должна отменить отложенное выполнение fn. +> В противном случае fn должна быть вызвана с аргументами args. > Ограничения: - fn — функция - args — валидный JSON-массив - 1 <= args.length <= 10 - 20 <= t <= 1000 - 10 <= cancelTimeMs <= 1000 ```ts @@ -34,43 +34,42 @@ setTimeout(() => { ``` ```md -Example 1: +Пример 1: - Input: fn = (x) => x * 5, args = [2], t = 20 - Output: [{"time": 20, "returned": 10}] - Explanation: + Ввод: fn = (x) => x * 5, args = [2], t = 20 + Вывод: [{"time": 20, "returned": 10}] + Объяснение: const cancelTimeMs = 50; const cancelFn = cancellable((x) => x * 5, [2], 20); setTimeout(cancelFn, cancelTimeMs); - The cancellation was scheduled to occur after a delay of cancelTimeMs (50ms), - which happened after the execution of fn(2) at 20ms. + Отмена была запланирована после задержки cancelTimeMs (50 мс), + что произошло после выполнения fn(2) в момент 20 мс. -Example 2: + Пример 2: - Input: fn = (x) => x**2, args = [2], t = 100 - Output: [] - Explanation: + Ввод: fn = (x) => x**2, args = [2], t = 100 + Вывод: [] + Объяснение: const cancelTimeMs = 50; const cancelFn = cancellable((x) => x**2, [2], 100); setTimeout(cancelFn, cancelTimeMs); - The cancellation was scheduled to occur after a delay of cancelTimeMs (50ms), - which happened before the execution of fn(2) at 100ms, resulting in fn(2) never being called. + Отмена была запланирована после задержки cancelTimeMs (50 мс), + что произошло до выполнения fn(2) в момент 100 мс, в результате fn(2) так и не была вызвана. -Example 3: + Пример 3: - - Input: fn = (x1, x2) => x1 * x2, args = [2,4], t = 30 - Output: [{"time": 30, "returned": 8}] - Explanation: + Ввод: fn = (x1, x2) => x1 * x2, args = [2,4], t = 30 + Вывод: [{"time": 30, "returned": 8}] + Объяснение: const cancelTimeMs = 100; const cancelFn = cancellable((x1, x2) => x1 * x2, [2,4], 30); setTimeout(cancelFn, cancelTimeMs); - The cancellation was scheduled to occur after a delay of cancelTimeMs (100ms), - which happened after the execution of fn(2,4) at 30ms. + Отмена была запланирована после задержки cancelTimeMs (100 мс), + что произошло после выполнения fn(2,4) в момент 30 мс. ``` #leetcode diff --git a/content-ru/leetcode/Untagged/2721-execute-asynchronous-functions-in-parallel.md b/content-ru/leetcode/Untagged/2721-execute-asynchronous-functions-in-parallel.md index 43bc5b8be4e76..f6f57f9f447fd 100644 --- a/content-ru/leetcode/Untagged/2721-execute-asynchronous-functions-in-parallel.md +++ b/content-ru/leetcode/Untagged/2721-execute-asynchronous-functions-in-parallel.md @@ -1,16 +1,15 @@ -# 2721. Execute Asynchronous Functions in Parallel (Medium) () +# 2721. Выполнение асинхронных функций параллельно (Medium) () > Дан массив асинхронных функций functions, верните новый promise. -> Каждая функция массива не принимает аргументов и возвращает promise. -> Все promise должны выполняться параллельно. -> Итоговый promise резолвится: - Когда все promise, возвращённые functions, были успешно зарезолвены. -> -> - Значением резолва должен быть массив всех зарезолвленных значений в том же порядке, в котором они были в functions. -> - Он должен резолвиться, когда все асинхронные функции завершили выполнение параллельно. -> Итоговый promise реджектится: - Когда любой из promise, возвращённых functions, был реджекнут. -> - Он должен реджектиться с причиной первого реджекта. -> Решите без использования встроенной функции Promise.all. -> Ограничения: - functions — массив функций, возвращающих promise - 1 <= functions.length <= 10 +> Каждая функция в массиве не принимает аргументов и возвращает promise. +> Все promise'ы должны выполняться параллельно. +> Promise разрешается: - когда все promise'ы, возвращённые из functions, успешно разрешились. +> - Разрешённое значение должно быть массивом всех разрешённых значений в том же порядке, в каком они были в functions. +> - Он должен разрешаться, когда все асинхронные функции завершили выполнение параллельно. +> Promise отклоняется: - когда любой promise, возвращённый из functions, был отклонён. +> - Он должен отклоняться с причиной первого отклонения. +> Пожалуйста, решите без использования встроенной функции Promise.all. +> Ограничения: - functions — массив функций, возвращающих promise'ы - 1 <= functions.length <= 10 ```ts type Fn = () => Promise @@ -21,19 +20,18 @@ function promiseAll(functions: Fn[]): Promise { let completed = 0 functions.map(async (fn, i) => { - await fn() - .then((res) => { - results[i] = res - completed++ - }) - .catch((err) => { - reject(err) - }) - - if (completed === functions.length) resolve(results) + await fn().then((res) => { + results[i] = res + completed++ + }).catch((err) => { + reject(err) + }) + + if (completed === functions.length) + resolve(results) }) }) -} +}; // for (let i = 0; i < functions.length; i++) { // functions[i]() @@ -50,49 +48,47 @@ function promiseAll(functions: Fn[]): Promise { // }) // } -const promise = promiseAll([() => new Promise((res) => res(42))]) +const promise = promiseAll([() => new Promise(res => res(42))]) promise.then(console.log) ``` ```md -Example 1: +Пример 1: - Input: + Ввод: functions = [ () => new Promise(resolve => setTimeout(() => resolve(5), 200)) ] - Output: {"t": 200, "resolved": [5]} - + Вывод: {"t": 200, "resolved": [5]} - - Explanation: + Объяснение: promiseAll(functions).then(console.log) // [5] - The single function was resolved at 200ms with a value of 5. + Единственная функция разрешилась на 200мс со значением 5. -Example 2: + Пример 2: - Input: + Ввод: functions = [ () => new Promise(resolve => setTimeout(() => resolve(1), 200)), () => new Promise((resolve, reject) => setTimeout(() => reject("Error"), 100)) ] - Output: {"t": 100, "rejected": "Error"} - Explanation: - Since one of the promises rejected, the returned promise also rejected with - the same error at the same time. + Вывод: {"t": 100, "rejected": "Error"} + Объяснение: + Поскольку один из promise'ов отклонился, возвращённый promise также + отклонился с той же ошибкой в то же время. -Example 3: + Пример 3: - Input: + Ввод: functions = [ () => new Promise(resolve => setTimeout(() => resolve(4), 50)), () => new Promise(resolve => setTimeout(() => resolve(10), 150)), () => new Promise(resolve => setTimeout(() => resolve(16), 100)) ] - Output: {"t": 150, "resolved": [4, 10, 16]} - Explanation: - All promises resolved with a value. The returned promise resolved when the - last promise resolved. + Вывод: {"t": 150, "resolved": [4, 10, 16]} + Объяснение: + Все promise'ы разрешились со значением. Возвращённый promise разрешился, + когда разрешился последний promise. ``` #leetcode diff --git a/content-ru/leetcode/Untagged/2723-add-two-promises.md b/content-ru/leetcode/Untagged/2723-add-two-promises.md index 53973954063f5..83c89c6f79ec6 100644 --- a/content-ru/leetcode/Untagged/2723-add-two-promises.md +++ b/content-ru/leetcode/Untagged/2723-add-two-promises.md @@ -1,33 +1,50 @@ # 2723. Add Two Promises (Easy) () +> Даны два промиса promise1 и promise2, верните новый промис. +> promise1 и promise2 оба разрешатся числом. +> Возвращаемый промис должен разрешиться суммой двух чисел. +> Ограничения: - promise1 и promise2 — промисы, разрешающиеся числом -> Даны два promise, promise1 и promise2, верните новый promise. -> promise1 и promise2 оба резолвятся числом. -> Возвращённый promise должен резолвиться суммой двух чисел. -> Ограничения: - promise1 и promise2 — это promise, резолвящиеся числом +```ts +async function addTwoPromises( + promise1: Promise, + promise2: Promise, +): Promise { + return Promise.all([promise1, promise2]).then(([result1, result2]) => result1 + result2) +} + +addTwoPromises(Promise.resolve(2), Promise.resolve(2)) + .then(console.log) // 4 + +addTwoPromises(Promise.resolve(2), Promise.resolve(5)) + .then(console.log) // 7 + +addTwoPromises(Promise.resolve(10), Promise.resolve(-12)) + .then(console.log) // -2 +``` ```md -Example 1: +Пример 1: - Input: + Ввод: promise1 = new Promise(resolve => setTimeout(() => resolve(2), 20)), promise2 = new Promise(resolve => setTimeout(() => resolve(5), 60)) - Output: 7 - Explanation: - The two input promises resolve with the values of 2 and 5 respectively. - The returned promise should resolve with a value of 2 + 5 = 7. - The time the returned promise resolves is not judged for this problem. + Вывод: 7 + Объяснение: + Два входных промиса разрешаются значениями 2 и 5 соответственно. + Возвращаемый промис должен разрешиться значением 2 + 5 = 7. + Время, за которое возвращаемый промис разрешается, в этой задаче не оценивается. -Example 2: + Пример 2: - Input: + Ввод: promise1 = new Promise(resolve => setTimeout(() => resolve(10), 50)), promise2 = new Promise(resolve => setTimeout(() => resolve(-12), 30)) - Output: -2 - Explanation: - The two input promises resolve with the values of 10 and -12 respectively. - The returned promise should resolve with a value of 10 + -12 = -2. + Вывод: -2 + Объяснение: + Два входных промиса разрешаются значениями 10 и -12 соответственно. + Возвращаемый промис должен разрешиться значением 10 + -12 = -2. ``` #leetcode diff --git a/content-ru/leetcode/Untagged/2724-sort-by.md b/content-ru/leetcode/Untagged/2724-sort-by.md index c1f853f638c06..86eb5e06aed85 100644 --- a/content-ru/leetcode/Untagged/2724-sort-by.md +++ b/content-ru/leetcode/Untagged/2724-sort-by.md @@ -1,11 +1,10 @@ -# 2724. Sort By (Easy) () +# 2724. Сортировка по (Easy) () - > Дан массив arr и функция fn, верните отсортированный массив sortedArr. > Можно считать, что fn возвращает только числа, и эти числа определяют порядок сортировки sortedArr. -> sortedArr должен быть отсортирован по возрастанию значений fn. -> Можно считать, что fn никогда не вернёт одинаковые числа для разных элементов заданного массива. +> sortedArr должен быть отсортирован по возрастанию значений, возвращаемых fn. +> Можно считать, что fn никогда не вернёт одинаковые числа для разных элементов массива. > Ограничения: - arr — валидный JSON-массив - fn — функция, возвращающая число - 1 <= arr.length <= 5 * 10^5 ```ts @@ -18,41 +17,32 @@ function sortBy(arr: JSONValue[], fn: Fn): JSONValue[] { } // Local check: -console.log(sortBy([5, 4, 1, 2, 3], (x) => x as number)) // [1, 2, 3, 4, 5] -console.log(sortBy([{ x: 1 }, { x: 0 }, { x: -1 }], (d) => (d as { x: number }).x)) // [{ x: -1 }, { x: 0 }, { x: 1 }] -console.log( - sortBy( - [ - [3, 4], - [5, 2], - [10, 1], - ], - (x) => (x as number[])[1], - ), -) // [[10, 1], [5, 2], [3, 4]] +console.log(sortBy([5, 4, 1, 2, 3], x => x as number)) // [1, 2, 3, 4, 5] +console.log(sortBy([{ x: 1 }, { x: 0 }, { x: -1 }], d => (d as { x: number }).x)) // [{ x: -1 }, { x: 0 }, { x: 1 }] +console.log(sortBy([[3, 4], [5, 2], [10, 1]], x => (x as number[])[1])) // [[10, 1], [5, 2], [3, 4]] ``` ```md -Example 1: +Пример 1: - Input: arr = [5, 4, 1, 2, 3], fn = (x) => x - Output: [1, 2, 3, 4, 5] - Explanation: - fn simply returns the number passed to it so the array is sorted in ascending order. + Вход: arr = [5, 4, 1, 2, 3], fn = (x) => x + Выход: [1, 2, 3, 4, 5] + Объяснение: + fn просто возвращает переданное ей число, поэтому массив сортируется по возрастанию. -Example 2: + Пример 2: - Input: arr = [{"x": 1}, {"x": 0}, {"x": -1}], fn = (d) => d.x - Output: [{"x": -1}, {"x": 0}, {"x": 1}] - Explanation: - fn returns the value for the "x" key. So the array is sorted based on that value. + Вход: arr = [{"x": 1}, {"x": 0}, {"x": -1}], fn = (d) => d.x + Выход: [{"x": -1}, {"x": 0}, {"x": 1}] + Объяснение: + fn возвращает значение ключа "x". Поэтому массив сортируется по этому значению. -Example 3: + Пример 3: - Input: arr = [[3, 4], [5, 2], [10, 1]], fn = (x) => x[1] - Output: [[10, 1], [5, 2], [3, 4]] - Explanation: - arr is sorted in ascending order by number at index=1. + Вход: arr = [[3, 4], [5, 2], [10, 1]], fn = (x) => x[1] + Выход: [[10, 1], [5, 2], [3, 4]] + Объяснение: + arr сортируется по возрастанию значения по индексу=1. ``` #leetcode diff --git a/content-ru/leetcode/Untagged/2725-interval-cancellation.md b/content-ru/leetcode/Untagged/2725-interval-cancellation.md index 51e16cf0ba4dc..1e02d8f3288c9 100644 --- a/content-ru/leetcode/Untagged/2725-interval-cancellation.md +++ b/content-ru/leetcode/Untagged/2725-interval-cancellation.md @@ -1,7 +1,7 @@ -# 2725. Interval Cancellation (Easy) () +# 2725. Отмена интервала (Easy) () -> Дана функция fn, массив аргументов args и интервал t, верните функцию отмены cancelFn. -> После задержки в cancelTimeMs возвращённая функция отмены cancelFn будет вызвана: setTimeout(cancelFn, cancelTimeMs) Функция fn должна быть вызвана с args немедленно, а затем повторно вызываться каждые t миллисекунд, пока cancelFn не будет вызвана на отметке cancelTimeMs мс. +> Дана функция fn, массив аргументов args и интервал времени t, нужно вернуть функцию отмены cancelFn. +> После задержки в cancelTimeMs миллисекунд возвращённая функция отмены cancelFn будет вызвана: setTimeout(cancelFn, cancelTimeMs). Функция fn должна быть вызвана с args немедленно, а затем повторно вызываться каждые t миллисекунд, пока в момент времени cancelTimeMs мс не будет вызвана cancelFn. > Ограничения: - fn — функция - args — валидный JSON-массив - 1 <= args.length <= 10 - 30 <= t <= 100 - 10 <= cancelTimeMs <= 500 ```ts @@ -14,8 +14,8 @@ function cancellable(fn: Fn, args: JSONValue[], t: number): Function { return () => clearInterval(timeoutId) } -// Local check -const result: { time: number; returned: JSONValue }[] = [] +// Локальная проверка +const result: { time: number, returned: JSONValue }[] = [] const fn = (...values: JSONValue[]) => Number(values[0]) * 2 const args: JSONValue[] = [4] const t = 35 @@ -33,7 +33,7 @@ setTimeout(() => console.log(result), cancelTimeMs + t) ``` ```md -Example 1: +Пример 1: Input: fn = (x) => x * 2, args = [4], t = 35 Output: @@ -59,10 +59,9 @@ Example 1: 6th fn call is at 175ms. fn(4) returns 8. Cancelled at 190ms. -Example 2: + Пример 2: - Input: fn = (x1, x2) => (x1 * x2), args = [2, 5], t = 30 Output: [ @@ -87,7 +86,7 @@ Example 2: 6th fn call is at 150ms. Cancelled at 165ms. -Example 3: + Пример 3: Input: fn = (x1, x2, x3) => (x1 + x2 + x3), args = [5, 1, 3], t = 50 Output: diff --git a/content-ru/leetcode/Untagged/2726-calculator-with-method-chaining.md b/content-ru/leetcode/Untagged/2726-calculator-with-method-chaining.md index 6d729a97e4314..103b1d2201ccb 100644 --- a/content-ru/leetcode/Untagged/2726-calculator-with-method-chaining.md +++ b/content-ru/leetcode/Untagged/2726-calculator-with-method-chaining.md @@ -1,19 +1,18 @@ -# 2726. Calculator with Method Chaining (Easy) () +# 2726. Калькулятор с цепочкой методов (Easy) () -> Спроектируйте класс Calculator. -> Класс должен предоставлять математические операции сложения, вычитания, умножения, деления и возведения в степень. -> Он также должен позволять выполнять последовательные операции с помощью method chaining. +> Реализуйте класс Calculator. +> Класс должен предоставлять математические операции: сложение, вычитание, умножение, деление и возведение в степень. +> Также он должен позволять выполнять последовательные операции с помощью цепочки методов (method chaining). > Конструктор класса Calculator должен принимать число, которое служит начальным значением result. -> Ваш класс Calculator должен иметь следующие методы: - add: прибавляет переданное число value к result и возвращает обновлённый Calculator. -> -> - subtract: вычитает переданное число value из result и возвращает обновлённый Calculator. -> - multiply: умножает result на переданное число value и возвращает обновлённый Calculator. -> - divide: делит result на переданное число value и возвращает обновлённый Calculator. -> Если переданное значение равно 0, должна быть выброшена ошибка "Division by zero is not allowed". -> - power: возводит result в степень переданного числа value и возвращает обновлённый Calculator. +> Ваш класс Calculator должен иметь следующие методы: - add: добавляет заданное значение value к result и возвращает обновлённый Calculator. +> - subtract: вычитает заданное значение value из result и возвращает обновлённый Calculator. +> - multiply: умножает result на заданное значение value и возвращает обновлённый Calculator. +> - divide: делит result на заданное значение value и возвращает обновлённый Calculator. +> Если переданное значение равно 0, должна быть выброшена ошибка "Division by zero is not allowed". +> - power: возводит result в степень заданного значения value и возвращает обновлённый Calculator. > - getResult: возвращает result. -> Решения с точностью 10^-5 от настоящего результата считаются верными. -> Ограничения: - actions — валидный JSON-массив строк - values — валидный JSON-массив чисел - 2 <= actions.length <= 2 * 10^4 - 1 <= values.length <= 2 * 10^4 - 1 - actions[i] — одно из "Calculator", "add", "subtract", "multiply", "divide", "power", "getResult" - Первое действие всегда "Calculator" - Последнее действие всегда "getResult" +> Решения с точностью до 10^-5 от фактического результата считаются верными. +> Ограничения: - actions — валидный JSON-массив строк - values — валидный JSON-массив чисел - 2 <= actions.length <= 2 * 10^4 - 1 <= values.length <= 2 * 10^4 - 1 - actions[i] — одно из значений "Calculator", "add", "subtract", "multiply", "divide", "power", "getResult" - Первое действие всегда "Calculator" - Последнее действие всегда "getResult" ```ts class Calculator { @@ -39,7 +38,8 @@ class Calculator { } divide(value: number): Calculator { - if (value === 0) throw new Error("Division by zero is not allowed") + if (value === 0) + throw new Error('Division by zero is not allowed') this.value /= value return this } @@ -54,7 +54,7 @@ class Calculator { } } -// Local check: +// Локальная проверка: console.log(new Calculator(10).add(5).subtract(7).getResult()) // 8 console.log(new Calculator(2).multiply(5).power(2).getResult()) // 100 @@ -66,14 +66,12 @@ Example 1: Input: actions = ["Calculator", "add", "subtract", "getResult"], values = [10, 5, 7] - - Output: 8 Explanation: new Calculator(10).add(5).subtract(7).getResult() // 10 + 5 - 7 = 8 -Example 2: + Example 2: Input: actions = ["Calculator", "multiply", "power", "getResult"], @@ -82,7 +80,7 @@ Example 2: Explanation: new Calculator(2).multiply(5).power(2).getResult() // (2 * 5) ^ 2 = 100 -Example 3: + Example 3: Input: actions = ["Calculator", "divide", "getResult"], diff --git a/content-ru/leetcode/Untagged/index.md b/content-ru/leetcode/Untagged/index.md index 63ef4712f1514..c0c456fd28957 100644 --- a/content-ru/leetcode/Untagged/index.md +++ b/content-ru/leetcode/Untagged/index.md @@ -1,11 +1,12 @@ --- -title: untagged +title: без тегов --- -# Untagged +# Без тегов [[leetcode/index|← LeetCode]] +- [[Untagged/125-valid-palindrome-neetcode]] - [[Untagged/2620-counter]] - [[Untagged/2622-cache-with-time-limit]] - [[Untagged/2623-memoize]] @@ -19,6 +20,7 @@ title: untagged - [[Untagged/2677-chunk-array]] - [[Untagged/2693-call-function-with-custom-context]] - [[Untagged/2703-return-length-of-arguments-passed]] +- [[Untagged/271-string-encode-and-decode]] - [[Untagged/2715-timeout-cancellation]] - [[Untagged/2721-execute-asynchronous-functions-in-parallel]] - [[Untagged/2723-add-two-promises]] diff --git a/content-ru/leetcode/index.md b/content-ru/leetcode/index.md index dec11ac2b8b43..1f853c8b614ad 100644 --- a/content-ru/leetcode/index.md +++ b/content-ru/leetcode/index.md @@ -5,13 +5,14 @@ title: leetcode # LeetCode - [[leetcode/Array/index|Array]] -- [[leetcode/Binary Tree/index|Binary Tree]] -- [[leetcode/Bit Manipulation/index|Bit Manipulation]] - [[leetcode/Hash Table/index|Hash Table]] - [[leetcode/Linked List/index|Linked List]] +- [[leetcode/Math/index|Math]] - [[leetcode/Patterns/index|Patterns]] - [[leetcode/RegExp/index|RegExp]] +- [[leetcode/Stack/index|Stack]] - [[leetcode/String/index|String]] +- [[leetcode/Tree/index|Tree]] - [[leetcode/Two Pointers/index|Two Pointers]] - [[leetcode/Untagged/index|Untagged]] From 05c0f1d1a498ebfb4970547eb014c6355c889cad Mon Sep 17 00:00:00 2001 From: Faustze Date: Fri, 24 Jul 2026 13:43:47 +0300 Subject: [PATCH 2/2] style: fix prettier formatting in content-ru/leetcode CI's `npm run check` (prettier --check) was failing on PR #19 for 64 new Russian-language leetcode notes. Reformatted with prettier --write. --- content-ru/.translation-manifest.json | 10 ++-- .../Array/11-container-with-most-water.md | 24 ++++----- .../Array/128-longest-consecutive-sequence.md | 14 ++--- ...ers-are-smaller-than-the-current-number.md | 6 +-- ...ids-with-the-greatest-number-of-candies.md | 10 ++-- ...41-build-an-array-with-stack-operations.md | 36 +++++++------ .../leetcode/Array/1470-shuffle-the-array.md | 12 ++--- ...rices-with-a-special-discount-in-a-shop.md | 4 +- content-ru/leetcode/Array/15-3sum.md | 20 +++---- .../150-evaluate-reverse-polish-notation.md | 42 +++++---------- .../leetcode/Array/217-contains-duplicate.md | 18 +++---- .../Array/238-product-of-array-except-self.md | 43 ++++++--------- .../leetcode/Array/268-missing-number.md | 18 +++---- content-ru/leetcode/Array/283-move-zeroes.md | 24 ++++----- .../Array/347-top-k-frequent-elements.md | 10 ++-- content-ru/leetcode/Array/36-valid-sudoku.md | 47 +++++++--------- ...ind-all-numbers-disappeared-in-an-array.md | 2 +- .../Array/485-max-consecutive-ones.md | 8 ++- .../leetcode/Array/49-group-anagrams.md | 46 ++++++++-------- .../Array/496-next-greater-element-i.md | 25 ++++----- .../leetcode/Array/605-can-place-flowers.md | 2 +- .../Array/636-exclusive-time-of-functions.md | 41 ++++++++------ .../Array/643-maximum-average-subarray-i.md | 22 ++++---- content-ru/leetcode/Array/645-set-mismatch.md | 5 +- .../leetcode/Array/704-binary-search.md | 24 +++++---- .../leetcode/Array/735-asteroid-collision.md | 46 ++++++++-------- .../leetcode/Array/739-daily-temperatures.md | 24 ++++----- content-ru/leetcode/Array/853-car-fleet.md | 27 +++++----- .../Array/977-squares-of-a-sorted-array.md | 30 +++++------ .../Hash Table/141-linked-list-cycle.md | 51 +++++++++--------- .../leetcode/Hash Table/242-valid-anagram.md | 26 ++++----- .../Linked List/206-reverse-linked-list.md | 44 ++++++++------- .../876-middle-of-the-linked-list.md | 44 +++++++-------- ...1071-greatest-common-divisor-of-strings.md | 20 +++---- content-ru/leetcode/Math/67-add-binary.md | 11 ++-- content-ru/leetcode/Stack/155-min-stack.md | 41 +++++++------- .../leetcode/String/20-valid-parentheses.md | 18 +++---- .../Tree/104-maximum-depth-of-binary-tree.md | 15 +++--- .../Two Pointers/125-valid-palindrome.md | 14 ++--- .../151-reverse-words-in-a-string.md | 15 +++--- .../1768-merge-strings-alternately.md | 18 +++---- .../345-reverse-vowels-of-a-string.md | 12 ++--- .../Two Pointers/392-is-subsequence.md | 10 ++-- .../844-backspace-string-compare.md | 54 +++++++++---------- .../Untagged/125-valid-palindrome-neetcode.md | 17 +++--- content-ru/leetcode/Untagged/2620-counter.md | 3 +- .../Untagged/2622-cache-with-time-limit.md | 9 ++-- content-ru/leetcode/Untagged/2623-memoize.md | 6 ++- .../2626-array-reduce-transformation.md | 6 ++- content-ru/leetcode/Untagged/2627-debounce.md | 15 +++--- .../Untagged/2629-function-composition.md | 8 +-- content-ru/leetcode/Untagged/2631-group-by.md | 22 +++++--- .../Untagged/2637-promise-time-limit.md | 15 +++--- content-ru/leetcode/Untagged/2665-counter2.md | 6 ++- .../Untagged/2666-allow-one-fn-call.md | 10 ++-- .../leetcode/Untagged/2677-chunk-array.md | 9 ++-- .../2693-call-function-with-custom-context.md | 6 +-- .../2703-return-length-of-arguments-passed.md | 5 +- .../Untagged/271-string-encode-and-decode.md | 16 +++--- .../Untagged/2715-timeout-cancellation.md | 5 +- ...cute-asynchronous-functions-in-parallel.md | 36 +++++++------ .../Untagged/2723-add-two-promises.md | 12 ++--- content-ru/leetcode/Untagged/2724-sort-by.md | 20 +++++-- .../Untagged/2725-interval-cancellation.md | 7 +-- .../2726-calculator-with-method-chaining.md | 16 +++--- 65 files changed, 642 insertions(+), 640 deletions(-) diff --git a/content-ru/.translation-manifest.json b/content-ru/.translation-manifest.json index f7149b61378df..531e2093a967b 100644 --- a/content-ru/.translation-manifest.json +++ b/content-ru/.translation-manifest.json @@ -2,8 +2,8 @@ "headhunter/JavaScript-easy-level.md": "07d772fee0195708ac9b6bdf41e1f0fcd2efcf15861cc34947dbce0975d26277", "headhunter/JavaScript-middle-level.md": "46ae57febadc70bebdc4f8116a7cf2db901c525e2b573bcfa34377be7af45ac0", "headhunter/index.md": "d9888f62e5b1a3e71f67b05616d51e15e1eccb67be651c33da850f48f438afd2", - "leetcode/Array/11-container-with-most-water.md": "8a735550d14dee7e853dee42c6ba6fd04b8671a31b76958370e192972cb39d5a", "index.md": "9da5f03310750282a9d78c77d9f3d8bd547ca447608377e930b344b05465465a", + "leetcode/Array/11-container-with-most-water.md": "8a735550d14dee7e853dee42c6ba6fd04b8671a31b76958370e192972cb39d5a", "leetcode/Array/128-longest-consecutive-sequence.md": "bb86cb5975db819d2c34752f0a1ca02abb9b65eda3f7313aac2ad95c88bb480e", "leetcode/Array/1365-how-many-numbers-are-smaller-than-the-current-number.md": "f816494f32fef0b84d820be9cd1f803d78f614d9c75ec73ef64cf58775767dee", "leetcode/Array/1431-kids-with-the-greatest-number-of-candies.md": "b1fbb71ca3551f90b3d25f529c47e17d6a73383e1c36bfa04862229f749c51d0", @@ -34,8 +34,8 @@ "leetcode/Array/index.md": "41312c1aa22a2bc48942ab7db09a841e791bcf67b807d817ec2de0e21c2295cf", "leetcode/Binary Tree/104-maximum-depth-of-binary-tree.md": "7b7cf86f3dd19dab12c5bb5a80d6dc889d05c8311f736e29a7910290c383487c", "leetcode/Binary Tree/index.md": "bb041a66e32d22d4aa02c786575954937f2de9fe580c34c4c8c934ab07558992", - "leetcode/Bit Manipulation/index.md": "0b0adb3378454a911b3002ebcbb86a25d0079a9f156c4241a839a25f8f356f38", "leetcode/Bit Manipulation/67-add-binary.md": "2a126e7e39ea2ee7a1572acbcddfbe458ee82e78255ca453eaf927b828d1ae31", + "leetcode/Bit Manipulation/index.md": "0b0adb3378454a911b3002ebcbb86a25d0079a9f156c4241a839a25f8f356f38", "leetcode/Hash Table/141-linked-list-cycle.md": "d7538035f0f319e0fe14792ef58e044728747a3360020d7668647aba2d5e49c0", "leetcode/Hash Table/242-valid-anagram.md": "918da654051dfe91aa4604aa3c2014818f648abc856f2559596215418275c14c", "leetcode/Hash Table/index.md": "f3ba5f85339d830df3c1e5cad598e5bc9194bef16fab3896671aed4b6911fc06", @@ -53,8 +53,8 @@ "leetcode/RegExp/medium/index.md": "ab62ebc8a5e5519835b27ed24b5771e7b3a1b9bcf655eb33baf023b6b2a194c2", "leetcode/Stack/155-min-stack.md": "25a7eccf2f43411ac98bcc103412154c85a147ba2b0760e3ab12e22120873163", "leetcode/Stack/index.md": "586159d36c4e8c6f765e6658a515d14a87903a5f356149298340e0109fb9c1a9", - "leetcode/String/20-valid-parentheses.md": "1c25f418d9dd3a4eaf6998878a8ad3109e3674c0f79a170386103f7d6dfc0ebd", "leetcode/String/1071-greatest-common-divisor-of-strings.md": "9161f7f16739eb7e040db86053a57a58e8f211743ab24ecaf7aa0bc79ba97273", + "leetcode/String/20-valid-parentheses.md": "1c25f418d9dd3a4eaf6998878a8ad3109e3674c0f79a170386103f7d6dfc0ebd", "leetcode/String/index.md": "a204d9fa53134117067547db045dbada54118559e84e339c3be8ab72684ee954", "leetcode/Tree/104-maximum-depth-of-binary-tree.md": "00268c53d961183aa465e7551190cbb69009cf7f5a03747a450679904e8ef3a2", "leetcode/Tree/index.md": "132df40193bfba429b2405b2ac7923e051bb229e2df90bf3d4f2d8daf29bee2b", @@ -81,12 +81,12 @@ "leetcode/Untagged/2703-return-length-of-arguments-passed.md": "b2669367406b49cfa4904a7643b07cb608c3631274126eb9f8490b5d6a874193", "leetcode/Untagged/271-string-encode-and-decode.md": "f4f01a023c843c15a56b8c1f6bac420a362064096e9b657a4643eacc2857db75", "leetcode/Untagged/2715-timeout-cancellation.md": "170a0dca15023327a42ec820beddce08fade08e4267ca13a554c370babe52b8f", - "leetcode/Untagged/2723-add-two-promises.md": "411a4daef6100ecece7bccd87525cb725541de931b6dcba40ab2614aae029248", "leetcode/Untagged/2721-execute-asynchronous-functions-in-parallel.md": "70387ecd0e5134a6c989bfafc41daac9df31147d6469e87d0b46538f4375a648", + "leetcode/Untagged/2723-add-two-promises.md": "411a4daef6100ecece7bccd87525cb725541de931b6dcba40ab2614aae029248", "leetcode/Untagged/2724-sort-by.md": "1feb454ea55531d52e47950aa416cc23702f76d6560319c37f80dbc1118f687c", "leetcode/Untagged/2725-interval-cancellation.md": "d245e0d1ec13403fa51b8349d2524332507c9b0cb3ff7c71ac99becbb8ff0eb9", - "leetcode/Untagged/index.md": "988a5773fd5f501cd92b5b3223500966941b19d5f2d21448da391cdc4895f064", "leetcode/Untagged/2726-calculator-with-method-chaining.md": "249ec94bdb2fa52ded25c266daf411ed4e208d966f0041939aabe4d647d99c7f", + "leetcode/Untagged/index.md": "988a5773fd5f501cd92b5b3223500966941b19d5f2d21448da391cdc4895f064", "leetcode/index.md": "88c151c7c5564227dea91e47d96076632d854dd7fc1eddfa45440093be401dc3", "vue/Internals/Compiler.md": "c46b3dd12912b11bc4f0a34b2abba574baff9626f42df410eab279ae77b99e90", "vue/Internals/Reactivity.md": "9b502f513195b4512f4d8188f1ac30746030e1c5a52a6a626d51c80c15752d24", diff --git a/content-ru/leetcode/Array/11-container-with-most-water.md b/content-ru/leetcode/Array/11-container-with-most-water.md index f62c837715ec1..d5e0c99236cb3 100644 --- a/content-ru/leetcode/Array/11-container-with-most-water.md +++ b/content-ru/leetcode/Array/11-container-with-most-water.md @@ -10,29 +10,29 @@ ```ts function maxArea(height: number[]): number { let left = 0, - right = height.length - 1; - let area = 0; + right = height.length - 1 + let area = 0 while (left < right) { const leftValue = height[left], - rightValue = height[right]; - area = Math.max(area, Math.min(leftValue, rightValue) * (right - left)); + rightValue = height[right] + area = Math.max(area, Math.min(leftValue, rightValue) * (right - left)) if (leftValue < rightValue) { - left++; + left++ } else { - right--; + right-- } } - return area; + return area } // Локальная проверка: -console.log(maxArea([1, 8, 6, 2, 5, 4, 8, 3, 7])); // 49 -console.log(maxArea([1, 7, 2, 5, 4, 7, 3, 6])); // 36 -console.log(maxArea([1, 1])); // 1 -console.log(maxArea([2, 2, 2])); // 4 +console.log(maxArea([1, 8, 6, 2, 5, 4, 8, 3, 7])) // 49 +console.log(maxArea([1, 7, 2, 5, 4, 7, 3, 6])) // 36 +console.log(maxArea([1, 1])) // 1 +console.log(maxArea([2, 2, 2])) // 4 ``` ```md @@ -43,7 +43,7 @@ console.log(maxArea([2, 2, 2])); // 4 Объяснение: Вышеуказанные вертикальные линии представлены массивом [1,8,6,2,5,4,8,3,7]. В этом случае максимальная площадь воды (синяя область), которую может удержать контейнер, равна 49. - Пример 2: +Пример 2: Ввод: height = [1,1] Вывод: 1 diff --git a/content-ru/leetcode/Array/128-longest-consecutive-sequence.md b/content-ru/leetcode/Array/128-longest-consecutive-sequence.md index ae6b4be019517..77248902e8269 100644 --- a/content-ru/leetcode/Array/128-longest-consecutive-sequence.md +++ b/content-ru/leetcode/Array/128-longest-consecutive-sequence.md @@ -1,12 +1,14 @@ # 128. Longest Consecutive Sequence (?) () > 128. +> > Longest Consecutive Sequence (https://leetcode.com/problems/longest-consecutive-sequence/) Дан неотсортированный массив целых чисел nums, верните длину самой длинной последовательности идущих подряд элементов. > Необходимо написать алгоритм, работающий за O(n). ```ts function longestConsecutive(nums: number[]): number { - let maxCnt = 0, cnt = 1 + let maxCnt = 0, + cnt = 1 const st = new Set(nums) for (let i = 0; i < nums.length; i++) { @@ -23,7 +25,7 @@ function longestConsecutive(nums: number[]): number { cnt = 1 } return maxCnt -}; +} // O(n^2) brute force // function longestConsecutive(nums: number[]): number { @@ -56,14 +58,14 @@ Example 1: Output: 4 Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4. - Example 2: +Example 2: Input: nums = [0,3,7,2,5,8,4,6,0,1] Output: 9 - Example 3: - Input: nums = [1,0,1,2] - Output: 3 +Example 3: +Input: nums = [1,0,1,2] +Output: 3 ``` #leetcode diff --git a/content-ru/leetcode/Array/1365-how-many-numbers-are-smaller-than-the-current-number.md b/content-ru/leetcode/Array/1365-how-many-numbers-are-smaller-than-the-current-number.md index 38c723eefda81..1022b75750a4f 100644 --- a/content-ru/leetcode/Array/1365-how-many-numbers-are-smaller-than-the-current-number.md +++ b/content-ru/leetcode/Array/1365-how-many-numbers-are-smaller-than-the-current-number.md @@ -16,7 +16,7 @@ function smallerNumbersThanCurrent(nums: number[]): number[] { } } - return nums.map(n => firstIndex.get(n)!) + return nums.map((n) => firstIndex.get(n)!) } // Локальная проверка: @@ -37,12 +37,12 @@ console.log(smallerNumbersThanCurrent([7, 7, 7, 7])) Для nums[3]=2 существует одно число меньше него (1). Для nums[4]=3 существует три числа меньше него (1, 2 и 2). - Пример 2: +Пример 2: Вход: nums = [6,5,4,8] Выход: [2,1,0,3] - Пример 3: +Пример 3: Вход: nums = [7,7,7,7] Выход: [0,0,0,0] diff --git a/content-ru/leetcode/Array/1431-kids-with-the-greatest-number-of-candies.md b/content-ru/leetcode/Array/1431-kids-with-the-greatest-number-of-candies.md index d33e3885b52a0..7d09dbfc36c44 100644 --- a/content-ru/leetcode/Array/1431-kids-with-the-greatest-number-of-candies.md +++ b/content-ru/leetcode/Array/1431-kids-with-the-greatest-number-of-candies.md @@ -9,8 +9,8 @@ ```ts function kidsWithCandies(candies: number[], extraCandies: number): boolean[] { const max = Math.max(...candies) - return candies.map(candy => candy + extraCandies >= max) -}; + return candies.map((candy) => candy + extraCandies >= max) +} // function kidsWithCandies(candies: number[], extraCandies: number): boolean[] { // const sortedCandies = [...candies].sort((a, b) => a - b) @@ -46,16 +46,18 @@ console.log(kidsWithCandies([1, 10, 10, 3], 1)) Ребёнку 4, у него будет 1 + 3 = 4 конфеты, что не является наибольшим числом среди детей. Ребёнку 5, у него будет 3 + 3 = 6 конфет, что является наибольшим числом среди детей. - Пример 2: +Пример 2: Вход: candies = [4,2,1,1,2], extraCandies = 1 Выход: [true,false,false,false,false] + + Объяснение: Есть только 1 дополнительная конфета. У ребёнка 1 всегда будет наибольшее количество конфет, даже если дополнительную конфету отдать другому ребёнку. - Пример 3: +Пример 3: Вход: candies = [12,1,12], extraCandies = 10 Выход: [true,false,true] diff --git a/content-ru/leetcode/Array/1441-build-an-array-with-stack-operations.md b/content-ru/leetcode/Array/1441-build-an-array-with-stack-operations.md index 971103399c885..3a2574e0deb00 100644 --- a/content-ru/leetcode/Array/1441-build-an-array-with-stack-operations.md +++ b/content-ru/leetcode/Array/1441-build-an-array-with-stack-operations.md @@ -2,40 +2,41 @@ > Вам дан целочисленный массив target и целое число n. > У вас есть пустой стек с двумя следующими операциями: - "Push": добавляет целое число на вершину стека. +> > - "Pop": удаляет целое число с вершины стека. -> Также у вас есть поток целых чисел в диапазоне [1, n]. -> Используйте эти две операции со стеком, чтобы числа в стеке (от дна до вершины) стали равны target. -> Вы должны следовать следующим правилам: - Если поток целых чисел не пуст, возьмите следующее целое число из потока и добавьте его на вершину стека. +> Также у вас есть поток целых чисел в диапазоне [1, n]. +> Используйте эти две операции со стеком, чтобы числа в стеке (от дна до вершины) стали равны target. +> Вы должны следовать следующим правилам: - Если поток целых чисел не пуст, возьмите следующее целое число из потока и добавьте его на вершину стека. > - Если стек не пуст, удалите целое число с вершины стека. > - Если в любой момент элементы в стеке (от дна до вершины) равны target, прекратите чтение новых чисел из потока и не выполняйте больше операций со стеком. -> Верните операции со стеком, необходимые для построения target по указанным правилам. -> Если существует несколько допустимых ответов, верните любой из них. -> Ограничения: - 1 <= target.length <= 100 - 1 <= n <= 100 - 1 <= target[i] <= n - target строго возрастающий. +> Верните операции со стеком, необходимые для построения target по указанным правилам. +> Если существует несколько допустимых ответов, верните любой из них. +> Ограничения: - 1 <= target.length <= 100 - 1 <= n <= 100 - 1 <= target[i] <= n - target строго возрастающий. ```ts function buildArray(target: number[], n: number): string[] { - const operations: string[] = []; + const operations: string[] = [] const stack = { items: [] as number[], push(value: number) { - operations.push("Push") - this.items.push(value); + operations.push("Push") + this.items.push(value) }, pop(): number | undefined { operations.push("Pop") - return this.items.pop(); - } + return this.items.pop() + }, } - let currentTargetIndex = 0; + let currentTargetIndex = 0 for (let i = 0; i < n; i++) { if (currentTargetIndex === target.length) { - break; + break } stack.push(i + 1) if (target[currentTargetIndex] !== stack.items[currentTargetIndex]) { - stack.pop(); + stack.pop() } else { currentTargetIndex += 1 } @@ -48,10 +49,11 @@ function buildArray(target: number[], n: number): string[] { console.log(buildArray([1, 3], 3)) console.log(buildArray([1, 2, 3], 3)) console.log(buildArray([1, 2], 4)) -console.log(buildArray([1,2,3], 3)) +console.log(buildArray([1, 2, 3], 3)) ``` + ```md Example 1: @@ -63,7 +65,7 @@ Example 1: Pop the integer on the top of the stack. s = [1]. Read 3 from the stream and push it to the stack. s = [1,3]. - Example 2: +Example 2: Input: target = [1,2,3], n = 3 Output: ["Push","Push","Push"] @@ -72,7 +74,7 @@ Example 1: Read 2 from the stream and push it to the stack. s = [1,2]. Read 3 from the stream and push it to the stack. s = [1,2,3]. - Example 3: +Example 3: Input: target = [1,2], n = 4 Output: ["Push","Push"] diff --git a/content-ru/leetcode/Array/1470-shuffle-the-array.md b/content-ru/leetcode/Array/1470-shuffle-the-array.md index 67c217ae13d8a..07fc8e842f978 100644 --- a/content-ru/leetcode/Array/1470-shuffle-the-array.md +++ b/content-ru/leetcode/Array/1470-shuffle-the-array.md @@ -6,12 +6,12 @@ ```ts function shuffle(nums: number[], n: number): number[] { - const result = new Array(n * 2); + const result = new Array(n * 2) for (let i = 0; i < n; i++) { - result[i * 2] = nums[i]; - result[i * 2 + 1] = nums[i + n]; + result[i * 2] = nums[i] + result[i * 2 + 1] = nums[i + n] } - return result; + return result } // Local check: @@ -27,12 +27,12 @@ Example 1: 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 2: +Example 2: Input: nums = [1,2,3,4,4,3,2,1], n = 4 Output: [1,4,2,3,3,2,4,1] - Example 3: +Example 3: Input: nums = [1,1,2,2], n = 2 Output: [1,2,1,2] diff --git a/content-ru/leetcode/Array/1475-final-prices-with-a-special-discount-in-a-shop.md b/content-ru/leetcode/Array/1475-final-prices-with-a-special-discount-in-a-shop.md index a44ac11f01ec0..6df7918371911 100644 --- a/content-ru/leetcode/Array/1475-final-prices-with-a-special-discount-in-a-shop.md +++ b/content-ru/leetcode/Array/1475-final-prices-with-a-special-discount-in-a-shop.md @@ -64,13 +64,13 @@ Example 1: therefore, the final price you will pay is 6 - 2 = 4. For items 3 and 4 you will not receive any discount at all. - Example 2: +Example 2: Input: prices = [1,2,3,4,5] Output: [1,2,3,4,5] Explanation: In this case, for all items, you will not receive any discount at all. - Example 3: +Example 3: Input: prices = [10,1,1,6] Output: [9,0,1,6] diff --git a/content-ru/leetcode/Array/15-3sum.md b/content-ru/leetcode/Array/15-3sum.md index ade85d48f7c28..80038873925b9 100644 --- a/content-ru/leetcode/Array/15-3sum.md +++ b/content-ru/leetcode/Array/15-3sum.md @@ -8,10 +8,11 @@ ```ts function threeSum(nums: number[]): number[][] { const triplets: number[][] = [] - nums.sort((a, b) => a - b); + nums.sort((a, b) => a - b) for (let i = 0; i < nums.length; i++) { - let leftIdx = i + 1, rightIdx = nums.length - 1; + let leftIdx = i + 1, + rightIdx = nums.length - 1 if (i > 0 && nums[i] === nums[i - 1]) continue while (leftIdx < rightIdx) { @@ -24,21 +25,14 @@ function threeSum(nums: number[]): number[][] { rightIdx-- // пропускаем одинаковые left значения - while ( - leftIdx < rightIdx && - nums[leftIdx] === nums[leftIdx - 1] - ) { + while (leftIdx < rightIdx && nums[leftIdx] === nums[leftIdx - 1]) { leftIdx++ } // пропускаем одинаковые right значения - while ( - leftIdx < rightIdx && - nums[rightIdx] === nums[rightIdx + 1] - ) { + while (leftIdx < rightIdx && nums[rightIdx] === nums[rightIdx + 1]) { rightIdx-- } - } else if (sm > 0) { rightIdx-- } else { @@ -62,12 +56,12 @@ console.log(threeSum([0, 0, 0])) Вход: nums = [-1,0,1,2,-1,-4] Выход: [[-1,-1,2],[-1,0,1]] - Пример 2: +Пример 2: Вход: nums = [0,1,1] Выход: [] - Пример 3: +Пример 3: Вход: nums = [0,0,0] Выход: [[0,0,0]] diff --git a/content-ru/leetcode/Array/150-evaluate-reverse-polish-notation.md b/content-ru/leetcode/Array/150-evaluate-reverse-polish-notation.md index a22419b7aae03..636cf206249d8 100644 --- a/content-ru/leetcode/Array/150-evaluate-reverse-polish-notation.md +++ b/content-ru/leetcode/Array/150-evaluate-reverse-polish-notation.md @@ -16,44 +16,28 @@ const ops: Record number> = { "-": (a, b) => a - b, "*": (a, b) => a * b, "/": (a, b) => Math.trunc(a / b), -}; +} function evalRPN(tokens: string[]): number { - const stack: number[] = []; + const stack: number[] = [] for (const token of tokens) { if (token in ops) { - const right = stack.pop()!; - const left = stack.pop()!; - stack.push(ops[token](left, right)); + const right = stack.pop()! + const left = stack.pop()! + stack.push(ops[token](left, right)) } else { - stack.push(Number(token)); + stack.push(Number(token)) } } - return stack[0]; + return stack[0] } // Local check: -console.log(evalRPN(["1", "2", "+", "3", "*", "4", "-"])); // 5 -console.log(evalRPN(["2", "1", "+", "3", "*"])); // 9 -console.log(evalRPN(["4", "13", "5", "/", "+"])); // 6 -console.log( - evalRPN([ - "10", - "6", - "9", - "3", - "+", - "-11", - "*", - "/", - "*", - "17", - "+", - "5", - "+", - ]), -); // 22 +console.log(evalRPN(["1", "2", "+", "3", "*", "4", "-"])) // 5 +console.log(evalRPN(["2", "1", "+", "3", "*"])) // 9 +console.log(evalRPN(["4", "13", "5", "/", "+"])) // 6 +console.log(evalRPN(["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"])) // 22 ``` ```md @@ -63,13 +47,13 @@ Example 1: Output: 9 Explanation: ((2 + 1) * 3) = 9 - Example 2: +Example 2: Input: tokens = ["4","13","5","/","+"] Output: 6 Explanation: (4 + (13 / 5)) = 6 - Example 3: +Example 3: Input: tokens = ["10","6","9","3","+","-11","*","/","*","17","+","5","+"] Output: 22 diff --git a/content-ru/leetcode/Array/217-contains-duplicate.md b/content-ru/leetcode/Array/217-contains-duplicate.md index 85742f446c22c..37e3979c57b31 100644 --- a/content-ru/leetcode/Array/217-contains-duplicate.md +++ b/content-ru/leetcode/Array/217-contains-duplicate.md @@ -5,14 +5,14 @@ ```ts function containsDuplicate(nums: number[]): boolean { - const st = new Set() - for (const num of nums) { - if (st.has(num)) { - return true - } - st.add(num) + const st = new Set() + for (const num of nums) { + if (st.has(num)) { + return true } - return false + st.add(num) + } + return false } // Локальная проверка: @@ -28,13 +28,13 @@ Example 1: Output: true Explanation: The element 1 occurs at the indices 0 and 3. - Example 2: +Example 2: Input: nums = [1,2,3,4] Output: false Explanation: All elements are distinct. - Example 3: +Example 3: Input: nums = [1,1,1,3,3,4,3,2,4,2] Output: true diff --git a/content-ru/leetcode/Array/238-product-of-array-except-self.md b/content-ru/leetcode/Array/238-product-of-array-except-self.md index 10ac1f83e6a62..9d7ab925457f2 100644 --- a/content-ru/leetcode/Array/238-product-of-array-except-self.md +++ b/content-ru/leetcode/Array/238-product-of-array-except-self.md @@ -9,46 +9,37 @@ ```ts function productExceptSelf(nums: number[]): number[] { let leftProduct = 1, - rightProduct = 1; - const answer: number[] = []; + rightProduct = 1 + const answer: number[] = [] for (let i = 0; i < nums.length; i++) { - answer.push(leftProduct); - leftProduct *= nums[i]; + answer.push(leftProduct) + leftProduct *= nums[i] } for (let i = nums.length - 1; i > -1; i--) { - answer[i] *= rightProduct; - rightProduct *= nums[i]; + answer[i] *= rightProduct + rightProduct *= nums[i] } - return answer; + return answer } // Local check: -console.log(productExceptSelf([1, 2, 3, 4])); // [24, 12, 8, 6] -console.log(productExceptSelf([-1, 1, 0, -3, 3])); // [0, 0, 9, 0, 0] +console.log(productExceptSelf([1, 2, 3, 4])) // [24, 12, 8, 6] +console.log(productExceptSelf([-1, 1, 0, -3, 3])) // [0, 0, 9, 0, 0] ``` ```md Example 1: - Input: nums = [1,2,3,4] - Output: [24,12,8,6] - Explanation: - - answer[0] = 2 * 3 * 4 = 24 - - answer[1] = 1 * 3 * 4 = 12 - - answer[2] = 1 * 2 * 4 = 8 - - answer[3] = 1 * 2 * 3 = 6 - - Example 2: - Input: nums = [-1,1,0,-3,3] - Output: [0,0,9,0,0] - Explanation: - - answer[0] = 1 * 0 * -3 * 3 = 0 - - answer[1] = -1 * 0 * -3 * 3 = 0 - - answer[2] = -1 * 1 * -3 * 3 = 9 - - answer[3] = -1 * 1 * 0 * 3 = 0 - - answer[4] = -1 * 1 * 0 * -3 = 0 +Input: nums = [1,2,3,4] +Output: [24,12,8,6] +Explanation: - answer[0] = 2 * 3 * 4 = 24 - answer[1] = 1 * 3 * 4 = 12 - answer[2] = 1 * 2 * 4 = 8 - answer[3] = 1 * 2 * 3 = 6 + +Example 2: +Input: nums = [-1,1,0,-3,3] +Output: [0,0,9,0,0] +Explanation: - answer[0] = 1 * 0 * -3 * 3 = 0 - answer[1] = -1 * 0 * -3 * 3 = 0 - answer[2] = -1 * 1 * -3 * 3 = 9 - answer[3] = -1 * 1 * 0 * 3 = 0 - answer[4] = -1 * 1 * 0 * -3 = 0 ``` #leetcode diff --git a/content-ru/leetcode/Array/268-missing-number.md b/content-ru/leetcode/Array/268-missing-number.md index 052d395e796e2..ff9b87feaeff5 100644 --- a/content-ru/leetcode/Array/268-missing-number.md +++ b/content-ru/leetcode/Array/268-missing-number.md @@ -6,16 +6,16 @@ ```ts function missingNumber(nums: number[]): number { - const n = nums.length; - const expectedSum = (n * (n + 1)) / 2; - const actualSum = nums.reduce((acc, num) => acc + num, 0); - return expectedSum - actualSum; + const n = nums.length + const expectedSum = (n * (n + 1)) / 2 + const actualSum = nums.reduce((acc, num) => acc + num, 0) + return expectedSum - actualSum } // Local check: -console.log(missingNumber([3, 0, 1])); -console.log(missingNumber([0, 1])); -console.log(missingNumber([9, 6, 4, 2, 3, 5, 7, 0, 1])); +console.log(missingNumber([3, 0, 1])) +console.log(missingNumber([0, 1])) +console.log(missingNumber([9, 6, 4, 2, 3, 5, 7, 0, 1])) ``` ```md @@ -26,14 +26,14 @@ Example 1: 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 2: +Example 2: Input: nums = [0,1] 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 3: +Example 3: Input: nums = [9,6,4,2,3,5,7,0,1] Output: 8 diff --git a/content-ru/leetcode/Array/283-move-zeroes.md b/content-ru/leetcode/Array/283-move-zeroes.md index 271b1724039dd..c593765c49749 100644 --- a/content-ru/leetcode/Array/283-move-zeroes.md +++ b/content-ru/leetcode/Array/283-move-zeroes.md @@ -6,27 +6,27 @@ ```ts function moveZeroes(nums: number[]): void { - let left = 0; - let right = left; + let left = 0 + let right = left while (right !== nums.length) { if (nums[right] !== 0) { if (right !== left) { - const temp = nums[left]; - nums[left] = nums[right]; - nums[right] = temp; + const temp = nums[left] + nums[left] = nums[right] + nums[right] = temp } - right++; - left++; + right++ + left++ } else { - right++; + right++ } } } // Local check: -console.log(moveZeroes([0, 1, 0, 3, 12])); -console.log(moveZeroes([0])); -console.log(moveZeroes([0, 1, 2, 3, 0])); +console.log(moveZeroes([0, 1, 0, 3, 12])) +console.log(moveZeroes([0])) +console.log(moveZeroes([0, 1, 2, 3, 0])) ``` ```md @@ -35,7 +35,7 @@ Example 1: Input: nums = [0,1,0,3,12] Output: [1,3,12,0,0] - Example 2: +Example 2: Input: nums = [0] Output: [0] diff --git a/content-ru/leetcode/Array/347-top-k-frequent-elements.md b/content-ru/leetcode/Array/347-top-k-frequent-elements.md index 303ea6716d9ea..21ae53d8f056a 100644 --- a/content-ru/leetcode/Array/347-top-k-frequent-elements.md +++ b/content-ru/leetcode/Array/347-top-k-frequent-elements.md @@ -19,10 +19,10 @@ function topKFrequent(nums: number[], k: number): number[] { } // Local check: -console.log(topKFrequent([1,1,1,2,2,3], 2)) -console.log(topKFrequent([7,7], 1)) +console.log(topKFrequent([1, 1, 1, 2, 2, 3], 2)) +console.log(topKFrequent([7, 7], 1)) console.log(topKFrequent([1], 1)) -console.log(topKFrequent([1,2,1,2,1,2,3,1,3,2], 2)) +console.log(topKFrequent([1, 2, 1, 2, 1, 2, 3, 1, 3, 2], 2)) ``` ```md @@ -32,12 +32,12 @@ Example 1: Output: [1,2] Explanation: The values 1 and 2 appear most frequently. - Example 2: +Example 2: Input: nums = [1], k = 1 Output: [1] - Example 3: +Example 3: Input: nums = [1,2,1,2,1,2,3,1,3,2], k = 2 Output: [1,2] diff --git a/content-ru/leetcode/Array/36-valid-sudoku.md b/content-ru/leetcode/Array/36-valid-sudoku.md index 4da6f8dd46e5c..5473994bba1f5 100644 --- a/content-ru/leetcode/Array/36-valid-sudoku.md +++ b/content-ru/leetcode/Array/36-valid-sudoku.md @@ -2,44 +2,37 @@ > Определите, является ли доска 9 x 9 для судоку допустимой. > Проверять нужно только заполненные ячейки согласно следующим правилам: 1. -> Каждая строка должна содержать цифры 1-9 без повторений. -> 2. -> Каждый столбец должен содержать цифры 1-9 без повторений. -> 3. +> Каждая строка должна содержать цифры 1-9 без повторений. 2. +> Каждый столбец должен содержать цифры 1-9 без повторений. 3. > Каждый из девяти квадратов 3 x 3 сетки должен содержать цифры 1-9 без повторений. > Примечание: - Доска судоку (частично заполненная) может быть допустимой, но не обязательно разрешимой. +> > - Проверять по указанным правилам нужно только заполненные ячейки. -> Ограничения: - board.length == 9 - board[i].length == 9 - board[i][j] это цифра 1-9 или '.'. +> Ограничения: - board.length == 9 - board[i].length == 9 - board[i][j] это цифра 1-9 или '.'. ```ts function isValidSudoku(board: string[][]): boolean { - const rowSet = new Set(); - const colSets: Set[] = Array.from( - { length: 9 }, - () => new Set(), - ); - const squareSets: Set[] = Array.from( - { length: 9 }, - () => new Set(), - ); + const rowSet = new Set() + const colSets: Set[] = Array.from({ length: 9 }, () => new Set()) + const squareSets: Set[] = Array.from({ length: 9 }, () => new Set()) for (let i = 0; i < board.length; i++) { for (let j = 0; j < board[i].length; j++) { - if (board[i][j] === ".") continue; + if (board[i][j] === ".") continue // column - if (colSets[j].has(board[i][j])) return false; - colSets[j].add(board[i][j]); + if (colSets[j].has(board[i][j])) return false + colSets[j].add(board[i][j]) // row - if (rowSet.has(board[i][j])) return false; - rowSet.add(board[i][j]); + if (rowSet.has(board[i][j])) return false + rowSet.add(board[i][j]) // square - const squareIndex = Math.floor(i / 3) * 3 + Math.floor(j / 3); - if (squareSets[squareIndex].has(board[i][j])) return false; - squareSets[squareIndex].add(board[i][j]); + const squareIndex = Math.floor(i / 3) * 3 + Math.floor(j / 3) + if (squareSets[squareIndex].has(board[i][j])) return false + squareSets[squareIndex].add(board[i][j]) } - rowSet.clear(); + rowSet.clear() } - return true; + return true } // Локальная проверка: @@ -55,7 +48,7 @@ console.log( [".", ".", ".", "4", "1", "9", ".", ".", "5"], [".", ".", ".", ".", "8", ".", ".", "7", "9"], ]), -); // true +) // true console.log( isValidSudoku([ @@ -69,7 +62,7 @@ console.log( [".", ".", ".", "4", "1", "9", ".", ".", "5"], [".", ".", ".", ".", "8", ".", ".", "7", "9"], ]), -); // false +) // false ``` ```md @@ -78,7 +71,7 @@ console.log( Ввод: board = [["5","3",".",".","7",".",".",".","."],["6",".",".","1","9","5",".",".","."],[".","9","8",".",".",".",".","6","."],["8",".",".",".","6",".",".",".","3"],["4",".",".","8",".","3",".",".","1"],["7",".",".",".","2",".",".",".","6"],[".","6",".",".",".",".","2","8","."],[".",".",".","4","1","9",".",".","5"],[".",".",".",".","8",".",".","7","9"]] Вывод: true - Пример 2: +Пример 2: Ввод: board = [["8","3",".",".","7",".",".",".","."],["6",".",".","1","9","5",".",".","."],[".","9","8",".",".",".",".","6","."],["8",".",".",".","6",".",".",".","3"],["4",".",".","8",".","3",".",".","1"],["7",".",".",".","2",".",".",".","6"],[".","6",".",".",".",".","2","8","."],[".",".",".","4","1","9",".",".","5"],[".",".",".",".","8",".",".","7","9"]] Вывод: false diff --git a/content-ru/leetcode/Array/448-find-all-numbers-disappeared-in-an-array.md b/content-ru/leetcode/Array/448-find-all-numbers-disappeared-in-an-array.md index 44f48952160dd..00eaa826e1114 100644 --- a/content-ru/leetcode/Array/448-find-all-numbers-disappeared-in-an-array.md +++ b/content-ru/leetcode/Array/448-find-all-numbers-disappeared-in-an-array.md @@ -36,7 +36,7 @@ console.log(findDisappearedNumbers([1, 1])) Ввод: nums = [4,3,2,7,8,2,3,1] Вывод: [5,6] - Пример 2: +Пример 2: Ввод: nums = [1,1] Вывод: [2] diff --git a/content-ru/leetcode/Array/485-max-consecutive-ones.md b/content-ru/leetcode/Array/485-max-consecutive-ones.md index 23cf55f0906f1..2184c97430928 100644 --- a/content-ru/leetcode/Array/485-max-consecutive-ones.md +++ b/content-ru/leetcode/Array/485-max-consecutive-ones.md @@ -10,10 +10,8 @@ function findMaxConsecutiveOnes(nums: number[]): number { for (const n of nums) { if (n === 1) { cnt += 1 - if (cnt > maxCnt) - maxCnt = cnt - } - else { + if (cnt > maxCnt) maxCnt = cnt + } else { cnt = 0 } } @@ -33,7 +31,7 @@ Example 1: Explanation: The first two digits or the last three digits are consecutive 1s. The maximum number of consecutive 1s is 3. - Example 2: +Example 2: Input: nums = [1,0,1,1,0,1] Output: 2 diff --git a/content-ru/leetcode/Array/49-group-anagrams.md b/content-ru/leetcode/Array/49-group-anagrams.md index b529531949f6b..e6f188735fe08 100644 --- a/content-ru/leetcode/Array/49-group-anagrams.md +++ b/content-ru/leetcode/Array/49-group-anagrams.md @@ -6,21 +6,21 @@ ```ts function groupAnagrams(strs: string[]): string[][] { - if (strs.length === 1) return [strs] + if (strs.length === 1) return [strs] - const group = new Map() + const group = new Map() - for (const ch of strs) { - const curr = ch.split('').sort().join('') - const currVal: string[] | undefined = group.get(curr) - if (currVal === undefined) { - group.set(curr, [ch]) - } else { - currVal.push(ch) - group.set(curr, currVal) - } + for (const ch of strs) { + const curr = ch.split("").sort().join("") + const currVal: string[] | undefined = group.get(curr) + if (currVal === undefined) { + group.set(curr, [ch]) + } else { + currVal.push(ch) + group.set(curr, currVal) } - return Array.from(group.values()) + } + return Array.from(group.values()) } // by charCode [O(n)] @@ -48,9 +48,9 @@ function groupAnagrams(strs: string[]): string[][] { // } // Local check: -console.log(groupAnagrams(['eat','tea','tan','ate','nat','bat'])); -console.log(groupAnagrams([''])); -console.log(groupAnagrams(['a'])); +console.log(groupAnagrams(["eat", "tea", "tan", "ate", "nat", "bat"])) +console.log(groupAnagrams([""])) +console.log(groupAnagrams(["a"])) ``` ```md @@ -59,15 +59,15 @@ Example 1: Output: [['bat'],['nat','tan'],['eat','tea','ate']] Explanation: ... - Example 2: - Input: [''] - Output: [['']] - Explanation: ... +Example 2: +Input: [''] +Output: [['']] +Explanation: ... - Example 3: - Input: ['a'] - Output: [['a']] - Explanation: ... +Example 3: +Input: ['a'] +Output: [['a']] +Explanation: ... ``` [[leetcode/Array/index|array]] diff --git a/content-ru/leetcode/Array/496-next-greater-element-i.md b/content-ru/leetcode/Array/496-next-greater-element-i.md index e9798b51cc716..c474519916205 100644 --- a/content-ru/leetcode/Array/496-next-greater-element-i.md +++ b/content-ru/leetcode/Array/496-next-greater-element-i.md @@ -6,36 +6,37 @@ > Если следующего большего элемента нет, ответом для этого запроса будет -1. > Верните массив длины nums1.length такой, что ans[i] — это следующий больший элемент, как описано выше. > Ограничения: - 1 <= nums1.length <= nums2.length <= 1000 - 0 <= nums1[i], nums2[i] <= 10^4 - Все целые числа в nums1 и nums2 уникальны. +> > - Все целые числа из nums1 также присутствуют в nums2. -> Дополнительный вопрос: Сможете ли вы найти решение с O(nums1.length + nums2.length)? +> Дополнительный вопрос: Сможете ли вы найти решение с O(nums1.length + nums2.length)? ```ts function nextGreaterElement(nums1: number[], nums2: number[]): number[] { - const stack: number[] = []; // LIFO; хранит числа, ещё не нашедшие next greater - const nextGreaters: Record = {}; // где ключ — число из nums2, значение — его next greater element + const stack: number[] = [] // LIFO; хранит числа, ещё не нашедшие next greater + const nextGreaters: Record = {} // где ключ — число из nums2, значение — его next greater element for (let i = 0; i < nums2.length; i++) { - const curr = nums2[i]; + const curr = nums2[i] // При новом числе — пока оно больше вершины стека, выталкивай вершину и записывай в map map[вершина] = новое_число while (curr > stack[stack.length - 1] && stack.length > 0) { - nextGreaters[stack.pop()!] = curr; + nextGreaters[stack.pop()!] = curr } - stack.push(curr); + stack.push(curr) } - const result = []; + const result = [] for (let i = 0; i < nums1.length; i++) { - result.push(nextGreaters[nums1[i]] ?? -1); + result.push(nextGreaters[nums1[i]] ?? -1) } - return result; + return result } // Local check: -console.log(nextGreaterElement([4, 1, 2], [1, 3, 4, 2])); // [-1,3,-1] -console.log(nextGreaterElement([2, 4], [1, 2, 3, 4])); // [3,-1] +console.log(nextGreaterElement([4, 1, 2], [1, 3, 4, 2])) // [-1,3,-1] +console.log(nextGreaterElement([2, 4], [1, 2, 3, 4])) // [3,-1] ``` ```md @@ -48,7 +49,7 @@ Example 1: 1 is in nums2 = [1,3,4,2]. The next greater element is 3. 2 is in nums2 = [1,3,4,2]. There is no next greater element, so the answer is -1. - Example 2: +Example 2: Input: nums1 = [2,4], nums2 = [1,2,3,4] Output: [3,-1] diff --git a/content-ru/leetcode/Array/605-can-place-flowers.md b/content-ru/leetcode/Array/605-can-place-flowers.md index b785a44d46c90..e9a5d353def33 100644 --- a/content-ru/leetcode/Array/605-can-place-flowers.md +++ b/content-ru/leetcode/Array/605-can-place-flowers.md @@ -38,7 +38,7 @@ Example 1: Input: flowerbed = [1,0,0,0,1], n = 1 Output: true - Example 2: +Example 2: Input: flowerbed = [1,0,0,0,1], n = 2 Output: false diff --git a/content-ru/leetcode/Array/636-exclusive-time-of-functions.md b/content-ru/leetcode/Array/636-exclusive-time-of-functions.md index 984e296516505..c361a3410b8af 100644 --- a/content-ru/leetcode/Array/636-exclusive-time-of-functions.md +++ b/content-ru/leetcode/Array/636-exclusive-time-of-functions.md @@ -12,6 +12,7 @@ > Например, если функция вызвана дважды, и один вызов выполнялся 2 единицы времени, а другой — 1 единицу, то эксклюзивное время равно 2 + 1 = 3. > Верните эксклюзивное время каждой функции в виде массива, где значение по индексу i представляет эксклюзивное время функции с ID i. > Ограничения: - 1 <= n <= 100 - 2 <= logs.length <= 500 - 0 <= function_id < n - 0 <= timestamp <= 10^9 - Никакие два события "start" не происходят в один и тот же момент времени. +> > - Никакие два события "end" не происходят в один и тот же момент времени. > - Для каждого "start" лога есть соответствующий "end" лог. @@ -31,11 +32,11 @@ function exclusiveTime(n: number, logs: string[]): number[] { for (let i = 0; i < logs.length; i++) { // Парсим лог: "function_id:start_or_end:timestamp" - const [idStr, op, tsStr] = logs[i].split(':') + const [idStr, op, tsStr] = logs[i].split(":") const id = Number(idStr) const ts = Number(tsStr) - if (op === 'start') { + if (op === "start") { // Новая функция стартует → старая функция (на вершине стека) ЗАМИРАЕТ. // Время от prevTs до ts принадлежит замороженной функции. if (stack.length > 0) { @@ -45,8 +46,7 @@ function exclusiveTime(n: number, logs: string[]): number[] { stack.push(id) // Запоминаем timestamp этого события для следующей итерации. prevTs = ts - } - else { + } else { // Функция завершается. Она работала от prevTs до ts ВКЛЮЧИТЕЛЬНО. // +1 потому что "end:5" означает конец единицы 5 (единица 5 полностью отработана). result[id] += ts - prevTs + 1 @@ -63,12 +63,16 @@ function exclusiveTime(n: number, logs: string[]): number[] { } // Local check: -console.log(exclusiveTime(2, ['0:start:0', '1:start:2', '1:end:5', '0:end:6'])) -console.log(exclusiveTime(1, ['0:start:0', '0:start:2', '0:end:5', '0:start:6', '0:end:6', '0:end:7'])) -console.log(exclusiveTime(2, ['0:start:0', '0:start:2', '0:end:5', '1:start:6', '1:end:6', '0:end:7'])) +console.log(exclusiveTime(2, ["0:start:0", "1:start:2", "1:end:5", "0:end:6"])) +console.log( + exclusiveTime(1, ["0:start:0", "0:start:2", "0:end:5", "0:start:6", "0:end:6", "0:end:7"]), +) +console.log( + exclusiveTime(2, ["0:start:0", "0:start:2", "0:end:5", "1:start:6", "1:end:6", "0:end:7"]), +) // Альтернативное решение -type Status = 'start' | 'end' +type Status = "start" | "end" interface Log { id: number @@ -90,7 +94,7 @@ function exclusiveTime2(n: number, logs: string[]): number[] { const log = parseLog(logs[i]!) const call = calls.at(-1) - if (call && call.id === log.id && log.status === 'end') { + if (call && call.id === log.id && log.status === "end") { const totalDuration = log.timestamp - call.start + 1 const selfDuration = totalDuration - call.childrenDuration @@ -102,8 +106,7 @@ function exclusiveTime2(n: number, logs: string[]): number[] { durations[log.id]! += selfDuration calls.pop() - } - else { + } else { calls.push({ id: log.id, start: log.timestamp, @@ -116,7 +119,7 @@ function exclusiveTime2(n: number, logs: string[]): number[] { } function parseLog(log: string): Log { - const logData = log.split(':') as [string, string, string] + const logData = log.split(":") as [string, string, string] const id = Number(logData[0]) const status = logData[1] as Status const timestamp = Number(logData[2]) @@ -124,9 +127,13 @@ function parseLog(log: string): Log { return { id, status, timestamp } } -console.log(exclusiveTime2(2, ['0:start:0', '1:start:2', '1:end:5', '0:end:6'])) -console.log(exclusiveTime2(1, ['0:start:0', '0:start:2', '0:end:5', '0:start:6', '0:end:6', '0:end:7'])) -console.log(exclusiveTime2(2, ['0:start:0', '0:start:2', '0:end:5', '1:start:6', '1:end:6', '0:end:7'])) +console.log(exclusiveTime2(2, ["0:start:0", "1:start:2", "1:end:5", "0:end:6"])) +console.log( + exclusiveTime2(1, ["0:start:0", "0:start:2", "0:end:5", "0:start:6", "0:end:6", "0:end:7"]), +) +console.log( + exclusiveTime2(2, ["0:start:0", "0:start:2", "0:end:5", "1:start:6", "1:end:6", "0:end:7"]), +) ``` ```md @@ -143,7 +150,7 @@ console.log(exclusiveTime2(2, ['0:start:0', '0:start:2', '0:end:5', '1:start:6', Таким образом, функция 0 суммарно тратит на выполнение 2 + 1 = 3 единицы времени, а функция 1 — 4 единицы времени. - Пример 2: +Пример 2: Вход: n = 1, logs = ["0:start:0","0:start:2","0:end:5","0:start:6","0:end:6","0:end:7"] Выход: [8] @@ -156,7 +163,7 @@ console.log(exclusiveTime2(2, ['0:start:0', '0:start:2', '0:end:5', '1:start:6', Функция 0 (исходный вызов) возобновляет выполнение в начале времени 7 и выполняется 1 единицу времени. Таким образом, функция 0 суммарно тратит на выполнение 2 + 4 + 1 + 1 = 8 единиц времени. - Пример 3: +Пример 3: Вход: n = 2, logs = ["0:start:0","0:start:2","0:end:5","1:start:6","1:end:6","0:end:7"] Выход: [7,1] diff --git a/content-ru/leetcode/Array/643-maximum-average-subarray-i.md b/content-ru/leetcode/Array/643-maximum-average-subarray-i.md index 0de957418fad1..335a14a87ce33 100644 --- a/content-ru/leetcode/Array/643-maximum-average-subarray-i.md +++ b/content-ru/leetcode/Array/643-maximum-average-subarray-i.md @@ -7,30 +7,30 @@ ```ts function findMaxAverage(nums: number[], k: number): number { - let maxSum = nums.slice(0, k).reduce((acc, cur) => acc + cur, 0); - let curSum = maxSum; + let maxSum = nums.slice(0, k).reduce((acc, cur) => acc + cur, 0) + let curSum = maxSum for (let i = 0; i < nums.length - k; i++) { curSum = curSum - nums[i] + nums[i + k] maxSum = curSum > maxSum ? curSum : maxSum } - return maxSum / k; + return maxSum / k } -console.log(findMaxAverage([1, 12, -5, -6, 50, 3], 4)); // 12.75 -console.log(findMaxAverage([5], 1)); // 5.0 +console.log(findMaxAverage([1, 12, -5, -6, 50, 3], 4)) // 12.75 +console.log(findMaxAverage([5], 1)) // 5.0 ``` ```md Пример 1: - Ввод: nums = [1,12,-5,-6,50,3], k = 4 - Вывод: 12.75 - Объяснение: Максимальное среднее равно (12 - 5 - 6 + 50) / 4 = 51 / 4 = 12.75 +Ввод: nums = [1,12,-5,-6,50,3], k = 4 +Вывод: 12.75 +Объяснение: Максимальное среднее равно (12 - 5 - 6 + 50) / 4 = 51 / 4 = 12.75 - Пример 2: - Ввод: nums = [5], k = 1 - Вывод: 5.00000 +Пример 2: +Ввод: nums = [5], k = 1 +Вывод: 5.00000 ``` [[leetcode/Array/index|array]] diff --git a/content-ru/leetcode/Array/645-set-mismatch.md b/content-ru/leetcode/Array/645-set-mismatch.md index 4c86fdadc67d5..b242bbc1e07c3 100644 --- a/content-ru/leetcode/Array/645-set-mismatch.md +++ b/content-ru/leetcode/Array/645-set-mismatch.md @@ -15,8 +15,7 @@ function findErrorNums(nums: number[]): number[] { const seen = new Set() for (const n of nums) { - if (seen.has(n)) - dupSum = n + if (seen.has(n)) dupSum = n seen.add(n) actualSum += n } @@ -37,7 +36,7 @@ Example 1: Output: [2,3] Explanation: The number 2 appears twice and the number 3 is missing. - Example 2: +Example 2: Input: nums = [1,1] Output: [1,2] diff --git a/content-ru/leetcode/Array/704-binary-search.md b/content-ru/leetcode/Array/704-binary-search.md index 845f2eeee818e..537e37a88ea4f 100644 --- a/content-ru/leetcode/Array/704-binary-search.md +++ b/content-ru/leetcode/Array/704-binary-search.md @@ -5,32 +5,33 @@ > В противном случае верните -1. > Вы должны написать алгоритм со сложностью выполнения O(log n). > Ограничения: - 1 <= nums.length <= 10^4 - -10^4 < nums[i], target < 10^4 - Все целые числа в nums уникальны. +> > - nums отсортирован по возрастанию. ```ts function search(nums: number[], target: number): number { let left = 0, - right = nums.length - 1; - let middle = Math.floor((left + right) / 2); + right = nums.length - 1 + let middle = Math.floor((left + right) / 2) while (right >= left) { if (target > nums[middle]) { - left = middle + 1; + left = middle + 1 } else if (target < nums[middle]) { - right = middle - 1; + right = middle - 1 } else { - return middle; + return middle } - middle = Math.floor((left + right) / 2); + middle = Math.floor((left + right) / 2) } - return -1; + return -1 } // Локальная проверка: -console.log(search([-1, 0, 3, 5, 9, 12], 9)); // 4 -console.log(search([-1, 0, 3, 5, 9, 12], 2)); // -1 -console.log(search([-1, 0, 3, 5, 9, 12], 12)); // 5 +console.log(search([-1, 0, 3, 5, 9, 12], 9)) // 4 +console.log(search([-1, 0, 3, 5, 9, 12], 2)) // -1 +console.log(search([-1, 0, 3, 5, 9, 12], 12)) // 5 ``` ```md @@ -40,10 +41,11 @@ console.log(search([-1, 0, 3, 5, 9, 12], 12)); // 5 Вывод: 4 Объяснение: 9 существует в nums и его индекс равен 4 - Пример 2: +Пример 2: Ввод: nums = [-1,0,3,5,9,12], target = 2 Вывод: -1 Объяснение: 2 не существует в nums, поэтому возвращаем -1 ``` + #leetcode diff --git a/content-ru/leetcode/Array/735-asteroid-collision.md b/content-ru/leetcode/Array/735-asteroid-collision.md index 2351ecf336cc7..21d24c11241ee 100644 --- a/content-ru/leetcode/Array/735-asteroid-collision.md +++ b/content-ru/leetcode/Array/735-asteroid-collision.md @@ -12,48 +12,48 @@ ```ts function asteroidCollision(asteroids: number[]): number[] { - const stack: number[] = []; + const stack: number[] = [] for (let i = 0; i < asteroids.length; i++) { - const curr = asteroids[i]; + const curr = asteroids[i] if (stack.length === 0 || (stack.at(-1)! > 0 && curr > 0)) { - stack.push(curr); - continue; + stack.push(curr) + continue } if (stack.at(-1)! < 0 && curr > 0) { - stack.push(curr); - continue; + stack.push(curr) + continue } - let currAlive = true; + let currAlive = true while (stack.at(-1)! > 0 && curr < 0) { if (Math.abs(curr) > Math.abs(stack.at(-1)!)) { - stack.pop(); + stack.pop() } else if (Math.abs(curr) < Math.abs(stack.at(-1)!)) { - currAlive = false; - break; + currAlive = false + break } else { - currAlive = false; - stack.pop(); - break; + currAlive = false + stack.pop() + break } } if (currAlive) { - stack.push(curr); + stack.push(curr) } } - return stack; + return stack } // Локальная проверка: -console.log(asteroidCollision([10, -2])); -console.log(asteroidCollision([5, 10, -5])); -console.log(asteroidCollision([8, -8])); -console.log(asteroidCollision([10, 2, -5])); -console.log(asteroidCollision([3, 5, -6, 2, -1, 4])); +console.log(asteroidCollision([10, -2])) +console.log(asteroidCollision([5, 10, -5])) +console.log(asteroidCollision([8, -8])) +console.log(asteroidCollision([10, 2, -5])) +console.log(asteroidCollision([3, 5, -6, 2, -1, 4])) ``` ```md @@ -63,19 +63,19 @@ console.log(asteroidCollision([3, 5, -6, 2, -1, 4])); Выход: [5,10] Объяснение: 10 и -5 сталкиваются, в результате остаётся 10. 5 и 10 никогда не сталкиваются. - Пример 2: +Пример 2: Вход: asteroids = [8,-8] Выход: [] Объяснение: 8 и -8 сталкиваются, взрывая друг друга. - Пример 3: +Пример 3: Вход: asteroids = [10,2,-5] Выход: [10] Объяснение: 2 и -5 сталкиваются, в результате остаётся -5. 10 и -5 сталкиваются, в результате остаётся 10. - Пример 4: +Пример 4: Вход: asteroids = [3,5,-6,2,-1,4] Выход: [-6,2,4] diff --git a/content-ru/leetcode/Array/739-daily-temperatures.md b/content-ru/leetcode/Array/739-daily-temperatures.md index 17c2a67634501..51cca57f450a6 100644 --- a/content-ru/leetcode/Array/739-daily-temperatures.md +++ b/content-ru/leetcode/Array/739-daily-temperatures.md @@ -6,26 +6,26 @@ ```ts function dailyTemperatures(temperatures: number[]): number[] { - const n = temperatures.length; - const answer: number[] = new Array(n).fill(0); // по умолчанию 0 - const stack: number[] = []; // храним ИНДЕКСЫ + const n = temperatures.length + const answer: number[] = new Array(n).fill(0) // по умолчанию 0 + const stack: number[] = [] // храним ИНДЕКСЫ for (let i = 0; i < n; i++) { // Пока стек не пуст И текущая температура ВЫШЕ температуры на верхушке while (stack.length > 0 && temperatures[i] > temperatures[stack.at(-1)!]) { - const topIdx = stack.pop()!; - answer[topIdx] = i - topIdx; // расстояние между индексами + const topIdx = stack.pop()! + answer[topIdx] = i - topIdx // расстояние между индексами } - stack.push(i); + stack.push(i) } - return answer; + return answer } // Local check: -console.log(dailyTemperatures([73, 74, 75, 71, 69, 72, 76, 73])); // [1,1,4,2,1,1,0,0] -console.log(dailyTemperatures([30, 40, 50, 60])); // [1,1,1,0] -console.log(dailyTemperatures([30, 60, 90])); // [1,1,0] +console.log(dailyTemperatures([73, 74, 75, 71, 69, 72, 76, 73])) // [1,1,4,2,1,1,0,0] +console.log(dailyTemperatures([30, 40, 50, 60])) // [1,1,1,0] +console.log(dailyTemperatures([30, 60, 90])) // [1,1,0] // function dailyTemperatures(temperatures: number[]): number[] { // const answer: number[] = []; @@ -61,12 +61,12 @@ Example 1: Day 6 (76): no warmer day -> 0 Day 7 (73): no warmer day -> 0 - Example 2: +Example 2: Input: temperatures = [30,40,50,60] Output: [1,1,1,0] - Example 3: +Example 3: Input: temperatures = [30,60,90] Output: [1,1,0] diff --git a/content-ru/leetcode/Array/853-car-fleet.md b/content-ru/leetcode/Array/853-car-fleet.md index ed1ef1fcb41c6..3fb5d636103e9 100644 --- a/content-ru/leetcode/Array/853-car-fleet.md +++ b/content-ru/leetcode/Array/853-car-fleet.md @@ -8,28 +8,29 @@ > Если машина догоняет автопарк ровно на отметке target, она всё равно считается частью этого автопарка. > Верните количество автопарков, которые прибудут к месту назначения. > Ограничения: - n == position.length == speed.length - 1 <= n <= 10^5 - 0 < target <= 10^6 - 0 <= position[i] < target - Все значения position уникальны. +> > - 0 < speed[i] <= 10^6 ```ts function carFleet(target: number, position: number[], speed: number[]): number { - let time = 0; - let fleets = 0; - const cars = position.map((p, i) => [p, speed[i]]); - cars.sort((a, b) => b[0] - a[0]); + let time = 0 + let fleets = 0 + const cars = position.map((p, i) => [p, speed[i]]) + cars.sort((a, b) => b[0] - a[0]) for (let i = 0; i < cars.length; i++) { - const currentTime = (target - cars[i][0]) / cars[i][1]; + const currentTime = (target - cars[i][0]) / cars[i][1] if (currentTime > time) { - fleets += 1; - time = currentTime; + fleets += 1 + time = currentTime } } - return fleets; + return fleets } // Local check: -console.log(carFleet(12, [10, 8, 0, 5, 3], [2, 4, 1, 1, 3])); // 3 -console.log(carFleet(10, [3], [3])); // 1 -console.log(carFleet(100, [0, 2, 4], [4, 2, 1])); // 1 +console.log(carFleet(12, [10, 8, 0, 5, 3], [2, 4, 1, 1, 3])) // 3 +console.log(carFleet(10, [3], [3])) // 1 +console.log(carFleet(100, [0, 2, 4], [4, 2, 1])) // 1 ``` ```md @@ -46,13 +47,13 @@ console.log(carFleet(100, [0, 2, 4], [4, 2, 1])); // 1 встречаясь друг с другом на отметке 6. Автопарк движется со скоростью 1, пока не достигнет target. - Пример 2: +Пример 2: Ввод: target = 10, position = [3], speed = [3] Вывод: 1 Объяснение: Есть только одна машина, следовательно, есть только один автопарк. - Пример 3: +Пример 3: Ввод: target = 100, position = [0,2,4], speed = [4,2,1] Вывод: 1 diff --git a/content-ru/leetcode/Array/977-squares-of-a-sorted-array.md b/content-ru/leetcode/Array/977-squares-of-a-sorted-array.md index e003729b192a4..c9de3c160eb92 100644 --- a/content-ru/leetcode/Array/977-squares-of-a-sorted-array.md +++ b/content-ru/leetcode/Array/977-squares-of-a-sorted-array.md @@ -6,30 +6,30 @@ ```ts function sortedSquares(nums: number[]): number[] { - const result: number[] = new Array(nums.length); - let left = 0; - let right = nums.length - 1; - let idx = nums.length - 1; + const result: number[] = new Array(nums.length) + let left = 0 + let right = nums.length - 1 + let idx = nums.length - 1 while (left <= right) { - const squaredLeft = nums[left] * nums[left]; - const squaredRight = nums[right] * nums[right]; + const squaredLeft = nums[left] * nums[left] + const squaredRight = nums[right] * nums[right] if (squaredLeft > squaredRight) { - result[idx] = squaredLeft; - left++; + result[idx] = squaredLeft + left++ } else { - result[idx] = squaredRight; - right--; + result[idx] = squaredRight + right-- } - idx--; + idx-- } - return result; + return result } // Local check: -console.log(sortedSquares([-4, -1, 0, 3, 10])); -console.log(sortedSquares([-7, -3, 2, 3, 11])); +console.log(sortedSquares([-4, -1, 0, 3, 10])) +console.log(sortedSquares([-7, -3, 2, 3, 11])) ``` ```md @@ -40,7 +40,7 @@ Example 1: Explanation: After squaring, the array becomes [16,1,0,9,100]. After sorting, it becomes [0,1,9,16,100]. - Example 2: +Example 2: Input: nums = [-7,-3,2,3,11] Output: [4,9,9,49,121] diff --git a/content-ru/leetcode/Hash Table/141-linked-list-cycle.md b/content-ru/leetcode/Hash Table/141-linked-list-cycle.md index e7d2624c25b1d..6772b334c1446 100644 --- a/content-ru/leetcode/Hash Table/141-linked-list-cycle.md +++ b/content-ru/leetcode/Hash Table/141-linked-list-cycle.md @@ -7,53 +7,54 @@ > Верните true, если в связном списке есть цикл. > В противном случае верните false. > Ограничения: - Количество узлов в списке находится в диапазоне [0, 10^4]. +> > - -10^5 <= Node.val <= 10^5 - pos равен -1 или является допустимым индексом в связном списке. -> Дополнительное задание: Сможете ли вы решить эту задачу, используя O(1) (то есть -> константную) память? +> Дополнительное задание: Сможете ли вы решить эту задачу, используя O(1) (то есть +> константную) память? ```ts class ListNode { - val: number; - next: ListNode | null; + val: number + next: ListNode | null constructor(val?: number, next?: ListNode | null) { - this.val = val === undefined ? 0 : val; - this.next = next === undefined ? null : next; + this.val = val === undefined ? 0 : val + this.next = next === undefined ? null : next } } function hasCycle(head: ListNode | null): boolean { // Floyd's Cycle Detection - let slow: ListNode | null = head; - let fast: ListNode | null = head; + let slow: ListNode | null = head + let fast: ListNode | null = head while (fast !== null && fast.next !== null) { - slow = slow!.next; - fast = fast.next.next; - if (fast === slow) return true; + slow = slow!.next + fast = fast.next.next + if (fast === slow) return true } - return false; + return false } function toList(arr: number[], pos: number): ListNode | null { - if (arr.length === 0) return null; - const nodes = arr.map((v) => new ListNode(v)); + if (arr.length === 0) return null + const nodes = arr.map((v) => new ListNode(v)) for (let i = 0; i < nodes.length - 1; i++) { - nodes[i].next = nodes[i + 1]; + nodes[i].next = nodes[i + 1] } if (pos >= 0 && pos < nodes.length) { - nodes[nodes.length - 1].next = nodes[pos]; + nodes[nodes.length - 1].next = nodes[pos] } - return nodes[0]; + return nodes[0] } // Локальная проверка: -console.log(hasCycle(toList([3, 2, 0, -4], 1))); // true -console.log(hasCycle(toList([1, 2], 0))); // true -console.log(hasCycle(toList([1], -1))); // false -console.log(hasCycle(toList([], -1))); // false -console.log(hasCycle(toList([1, 2, 3, 4, 5], -1))); // false -console.log(hasCycle(toList([1, 2, 3, 4, 5], 4))); // true (tail → last node itself) +console.log(hasCycle(toList([3, 2, 0, -4], 1))) // true +console.log(hasCycle(toList([1, 2], 0))) // true +console.log(hasCycle(toList([1], -1))) // false +console.log(hasCycle(toList([], -1))) // false +console.log(hasCycle(toList([1, 2, 3, 4, 5], -1))) // false +console.log(hasCycle(toList([1, 2, 3, 4, 5], 4))) // true (tail → last node itself) ``` ```md @@ -63,13 +64,13 @@ console.log(hasCycle(toList([1, 2, 3, 4, 5], 4))); // true (tail → last node i Выход: true Объяснение: В связном списке есть цикл, где хвост соединяется с 1-м узлом (индексация с 0). - Пример 2: +Пример 2: Вход: head = [1,2], pos = 0 Выход: true Объяснение: В связном списке есть цикл, где хвост соединяется с 0-м узлом. - Пример 3: +Пример 3: Вход: head = [1], pos = -1 Выход: false diff --git a/content-ru/leetcode/Hash Table/242-valid-anagram.md b/content-ru/leetcode/Hash Table/242-valid-anagram.md index 38bb83d04e9d1..2b6e8d8a07ba7 100644 --- a/content-ru/leetcode/Hash Table/242-valid-anagram.md +++ b/content-ru/leetcode/Hash Table/242-valid-anagram.md @@ -6,22 +6,22 @@ ```ts function isAnagram(s: string, t: string): boolean { - if (s.length !== t.length) return false + if (s.length !== t.length) return false - const mp: Map = new Map(); + const mp: Map = new Map() - for (const ch of s) { - mp.set(ch, (mp.get(ch) || 0) + 1) - } + for (const ch of s) { + mp.set(ch, (mp.get(ch) || 0) + 1) + } - for (const ch of t) { - const curr = mp.get(ch) - if (!curr) return false - if (curr === 1) mp.delete(ch) - else mp.set(ch, curr - 1) - } + for (const ch of t) { + const curr = mp.get(ch) + if (!curr) return false + if (curr === 1) mp.delete(ch) + else mp.set(ch, curr - 1) + } - return true + return true } // Local check: @@ -36,7 +36,7 @@ Example 1: Output: true Explanation: "nagaram" is an anagram of "anagram". - Example 2: +Example 2: Input: s = "rat", t = "car" Output: false diff --git a/content-ru/leetcode/Linked List/206-reverse-linked-list.md b/content-ru/leetcode/Linked List/206-reverse-linked-list.md index 169f150ccaef5..a608444a5ba80 100644 --- a/content-ru/leetcode/Linked List/206-reverse-linked-list.md +++ b/content-ru/leetcode/Linked List/206-reverse-linked-list.md @@ -2,46 +2,44 @@ > Given the head of a singly linked list, reverse the list, and return the reversed list. > Constraints: - The number of nodes in the list is in the range [0, 5000]. +> > - -5000 <= Node.val <= 5000 Follow up: A linked list can be reversed either iteratively or recursively. -> Could you implement both? +> Could you implement both? ```ts class ListNode { - val: number; - next: ListNode | null; + val: number + next: ListNode | null constructor(val?: number, next?: ListNode | null) { - this.val = val === undefined ? 0 : val; - this.next = next === undefined ? null : next; + this.val = val === undefined ? 0 : val + this.next = next === undefined ? null : next } } function reverseList(head: ListNode | null): ListNode | null { - if (head === null) return null; + if (head === null) return null - let prev: ListNode | null = null; - let current: ListNode | null = head; + let prev: ListNode | null = null + let current: ListNode | null = head while (current !== null) { - const next: ListNode | null = current.next; // запоминаем следующий узел - current.next = prev; // разворачиваем ссылку - prev = current; // двигаем prev - current = next; // переходим дальше + const next: ListNode | null = current.next // запоминаем следующий узел + current.next = prev // разворачиваем ссылку + prev = current // двигаем prev + current = next // переходим дальше } - return prev; + return prev } // Local check: -const list1 = new ListNode( - 1, - new ListNode(2, new ListNode(3, new ListNode(4, new ListNode(5)))), -); -console.log(reverseList(list1)); // [5,4,3,2,1] +const list1 = new ListNode(1, new ListNode(2, new ListNode(3, new ListNode(4, new ListNode(5))))) +console.log(reverseList(list1)) // [5,4,3,2,1] -const list2 = new ListNode(1, new ListNode(2)); -console.log(reverseList(list2)); // [2,1] +const list2 = new ListNode(1, new ListNode(2)) +console.log(reverseList(list2)) // [2,1] -console.log(reverseList(null)); // [] +console.log(reverseList(null)) // [] ``` ```md @@ -50,12 +48,12 @@ Example 1: Input: head = [1,2,3,4,5] Output: [5,4,3,2,1] - Example 2: +Example 2: Input: head = [1,2] Output: [2,1] - Example 3: +Example 3: Input: head = [] Output: [] diff --git a/content-ru/leetcode/Linked List/876-middle-of-the-linked-list.md b/content-ru/leetcode/Linked List/876-middle-of-the-linked-list.md index ecefccf48fc4d..15762263b9624 100644 --- a/content-ru/leetcode/Linked List/876-middle-of-the-linked-list.md +++ b/content-ru/leetcode/Linked List/876-middle-of-the-linked-list.md @@ -5,50 +5,50 @@ ```ts class ListNode { - val: number; - next: ListNode | null; + val: number + next: ListNode | null constructor(val?: number, next?: ListNode | null) { - this.val = val === undefined ? 0 : val; - this.next = next === undefined ? null : next; + this.val = val === undefined ? 0 : val + this.next = next === undefined ? null : next } } function middleNode(head: ListNode | null): ListNode | null { // Floyd's slow/fast pointers - let slow = head; - let fast = head; + let slow = head + let fast = head while (fast !== null && fast.next !== null) { - slow = slow!.next; - fast = fast.next.next; + slow = slow!.next + fast = fast.next.next } - return slow; + return slow } // Local check: function toList(arr: number[]): ListNode | null { - if (arr.length === 0) return null; - const head = new ListNode(arr[0]); - let cur = head; + if (arr.length === 0) return null + const head = new ListNode(arr[0]) + let cur = head for (let i = 1; i < arr.length; i++) { - cur.next = new ListNode(arr[i]); - cur = cur.next; + cur.next = new ListNode(arr[i]) + cur = cur.next } - return head; + return head } function toArray(node: ListNode | null): number[] { - const out: number[] = []; + const out: number[] = [] while (node !== null) { - out.push(node.val); - node = node.next; + out.push(node.val) + node = node.next } - return out; + return out } -console.log(toArray(middleNode(toList([1, 2, 3, 4, 5])))); -console.log(toArray(middleNode(toList([1, 2, 3, 4, 5, 6])))); +console.log(toArray(middleNode(toList([1, 2, 3, 4, 5])))) +console.log(toArray(middleNode(toList([1, 2, 3, 4, 5, 6])))) ``` ```md @@ -58,7 +58,7 @@ Example 1: Output: [3,4,5] Explanation: The middle node of the list is node 3. - Example 2: +Example 2: Input: head = [1,2,3,4,5,6] Output: [4,5,6] diff --git a/content-ru/leetcode/Math/1071-greatest-common-divisor-of-strings.md b/content-ru/leetcode/Math/1071-greatest-common-divisor-of-strings.md index d276ddbbc9a46..fb6147aecd0d6 100644 --- a/content-ru/leetcode/Math/1071-greatest-common-divisor-of-strings.md +++ b/content-ru/leetcode/Math/1071-greatest-common-divisor-of-strings.md @@ -1,14 +1,14 @@ # 1071. Наибольший общий делитель строк (Easy) () > Для двух строк s и t говорят, что "t делит s" тогда и только тогда, когда s = t + t + ... -> + t (то есть t конкатенируется сама с собой один или более раз). -> Даны две строки str1 и str2, верните наибольшую строку x такую, что x делит и str1, и str2. -> Ограничения: 1 <= str1.length, str2.length <= 1000 str1 и str2 состоят из заглавных букв английского алфавита. +> +> - t (то есть t конкатенируется сама с собой один или более раз). +> Даны две строки str1 и str2, верните наибольшую строку x такую, что x делит и str1, и str2. +> Ограничения: 1 <= str1.length, str2.length <= 1000 str1 и str2 состоят из заглавных букв английского алфавита. ```ts function gcdOfStrings(str1: string, str2: string): string { - if (str1 + str2 !== str2 + str1) - return '' + if (str1 + str2 !== str2 + str1) return "" return str1.slice(0, gcd(str1.length, str2.length)) } @@ -21,9 +21,9 @@ function gcd(a: number, b: number) { } // Local check: -console.log(gcdOfStrings('ABCABC', 'ABC')) -console.log(gcdOfStrings('ABABAB', 'ABAB')) -console.log(gcdOfStrings('LEET', 'CODE')) +console.log(gcdOfStrings("ABCABC", "ABC")) +console.log(gcdOfStrings("ABABAB", "ABAB")) +console.log(gcdOfStrings("LEET", "CODE")) ``` ```md @@ -32,12 +32,12 @@ Example 1: Input: str1 = "ABCABC", str2 = "ABC" Output: "ABC" - Example 2: +Example 2: Input: str1 = "ABABAB", str2 = "ABAB" Output: "AB" - Example 3: +Example 3: Input: str1 = "LEET", str2 = "CODE" Output: "" diff --git a/content-ru/leetcode/Math/67-add-binary.md b/content-ru/leetcode/Math/67-add-binary.md index cd2d8ce203bc8..96953edc78aa0 100644 --- a/content-ru/leetcode/Math/67-add-binary.md +++ b/content-ru/leetcode/Math/67-add-binary.md @@ -2,17 +2,18 @@ > Даны две двоичные строки a и b, нужно вернуть их сумму в виде двоичной строки. > Ограничения: - 1 <= a.length, b.length <= 10^4 - a и b состоят только из символов '0' или '1'. +> > - Каждая строка не содержит ведущих нулей, кроме самого нуля. ```ts function addBinary(a: string, b: string): string { - const sum = BigInt("0b" + a) + BigInt("0b" + b); - return sum.toString(2); + const sum = BigInt("0b" + a) + BigInt("0b" + b) + return sum.toString(2) } // Local check: -console.log(addBinary("11", "1")); // "100" -console.log(addBinary("1010", "1011")); // "10101" +console.log(addBinary("11", "1")) // "100" +console.log(addBinary("1010", "1011")) // "10101" // function addBinary(a: string, b: string): string { // let i = a.length - 1; @@ -44,7 +45,7 @@ Example 1: Output: "100" Explanation: 11 (binary) = 3, 1 (binary) = 1, 3 + 1 = 4 = 100 (binary) - Example 2: +Example 2: Input: a = "1010", b = "1011" Output: "10101" diff --git a/content-ru/leetcode/Stack/155-min-stack.md b/content-ru/leetcode/Stack/155-min-stack.md index 057227fbeeda8..0e740e576bc72 100644 --- a/content-ru/leetcode/Stack/155-min-stack.md +++ b/content-ru/leetcode/Stack/155-min-stack.md @@ -2,52 +2,51 @@ > Спроектируйте стек, который поддерживает push, pop, top и получение минимального элемента за константное время. > Реализуйте класс MinStack: - MinStack() инициализирует объект стека. +> > - void push(int value) добавляет элемент value на вершину стека. > - void pop() удаляет элемент с вершины стека. > - int top() возвращает элемент на вершине стека. > - int getMin() возвращает минимальный элемент в стеке. -> Ограничения: - -2^31 <= val <= 2^31 - 1 - Операции pop, top и getMin всегда будут вызываться на непустых стеках. +> Ограничения: - -2^31 <= val <= 2^31 - 1 - Операции pop, top и getMin всегда будут вызываться на непустых стеках. > - Будет сделано не более 3 * 10^4 вызовов push, pop, top и getMin. -> Вы должны реализовать решение с временной сложностью O(1) для каждой функции. +> Вы должны реализовать решение с временной сложностью O(1) для каждой функции. ```ts class MinStack { - private stack: number[] = []; - private minStack: number[] = []; + private stack: number[] = [] + private minStack: number[] = [] constructor() {} push(val: number): void { - this.stack.push(val); - const currentMin = - this.minStack.length === 0 ? Infinity : this.minStack.at(-1)!; - this.minStack.push(Math.min(val, currentMin)); + this.stack.push(val) + const currentMin = this.minStack.length === 0 ? Infinity : this.minStack.at(-1)! + this.minStack.push(Math.min(val, currentMin)) } pop(): void { - this.stack.pop(); - this.minStack.pop(); + this.stack.pop() + this.minStack.pop() } top(): number { - return this.stack.at(-1); + return this.stack.at(-1) } getMin(): number { - return this.minStack.at(-1); + return this.minStack.at(-1) } } - // Локальная проверка: -const minStack = new MinStack(); -minStack.push(1); -minStack.push(2); -minStack.push(0); -console.log(minStack.getMin()); -minStack.pop(); -console.log(minStack.top()); -console.log(minStack.getMin()); +const minStack = new MinStack() +minStack.push(1) +minStack.push(2) +minStack.push(0) +console.log(minStack.getMin()) +minStack.pop() +console.log(minStack.top()) +console.log(minStack.getMin()) ``` ```md diff --git a/content-ru/leetcode/String/20-valid-parentheses.md b/content-ru/leetcode/String/20-valid-parentheses.md index d1814d0e27d7a..bd7e7ab36206d 100644 --- a/content-ru/leetcode/String/20-valid-parentheses.md +++ b/content-ru/leetcode/String/20-valid-parentheses.md @@ -2,17 +2,13 @@ > Дана строка s, содержащая только символы '(', ')', '{', '}', '[' и ']', определите, является ли входная строка допустимой. > Входная строка допустима, если: 1. -> Открывающие скобки должны закрываться скобками того же типа. -> 2. -> Открывающие скобки должны закрываться в правильном порядке. -> 3. +> Открывающие скобки должны закрываться скобками того же типа. 2. +> Открывающие скобки должны закрываться в правильном порядке. 3. > Каждой закрывающей скобке соответствует открывающая скобка того же типа. > Ограничения: - 1 <= s.length <= 10^4 - s состоит только из скобок '()[]{}'. ```ts -function isValid(s: string): boolean { - -} +function isValid(s: string): boolean {} // Local check: console.log(isValid("()")) @@ -28,22 +24,22 @@ Example 1: Input: s = "()" Output: true - Example 2: +Example 2: Input: s = "()[]{}" Output: true - Example 3: +Example 3: Input: s = "(]" Output: false - Example 4: +Example 4: Input: s = "([])" Output: true - Example 5: +Example 5: Input: s = "([)]" Output: false diff --git a/content-ru/leetcode/Tree/104-maximum-depth-of-binary-tree.md b/content-ru/leetcode/Tree/104-maximum-depth-of-binary-tree.md index 8bf1fa4f0a43a..20fadfdb9f312 100644 --- a/content-ru/leetcode/Tree/104-maximum-depth-of-binary-tree.md +++ b/content-ru/leetcode/Tree/104-maximum-depth-of-binary-tree.md @@ -3,6 +3,7 @@ > Дан корень бинарного дерева, верните его максимальную глубину. > Максимальная глубина бинарного дерева — это количество узлов вдоль самого длинного пути от корневого узла до самого дальнего листового узла. > Ограничения: - Количество узлов в дереве находится в диапазоне [0, 10^4]. +> > - -100 <= Node.val <= 100 ```ts @@ -11,9 +12,9 @@ class TreeNode { left: TreeNode | null right: TreeNode | null constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { - this.val = (val === undefined ? 0 : val) - this.left = (left === undefined ? null : left) - this.right = (right === undefined ? null : right) + this.val = val === undefined ? 0 : val + this.left = left === undefined ? null : left + this.right = right === undefined ? null : right } } @@ -26,11 +27,7 @@ function maxDepth(root: TreeNode | null): number { } // Local check: -const root = new TreeNode( - 3, - new TreeNode(9), - new TreeNode(20, new TreeNode(15), new TreeNode(7)), -) +const root = new TreeNode(3, new TreeNode(9), new TreeNode(20, new TreeNode(15), new TreeNode(7))) console.log(maxDepth(root)) // 3 const root2 = new TreeNode(1, null, new TreeNode(2)) @@ -43,7 +40,7 @@ console.log(maxDepth(root2)) // 2 Ввод: root = [3,9,20,null,null,15,7] Вывод: 3 - Пример 2: +Пример 2: Ввод: root = [1,null,2] Вывод: 2 diff --git a/content-ru/leetcode/Two Pointers/125-valid-palindrome.md b/content-ru/leetcode/Two Pointers/125-valid-palindrome.md index a23bbc6743f29..2cbea8f664cc5 100644 --- a/content-ru/leetcode/Two Pointers/125-valid-palindrome.md +++ b/content-ru/leetcode/Two Pointers/125-valid-palindrome.md @@ -7,8 +7,8 @@ ```ts function isPalindrome(s: string): boolean { - const lc = s.toLocaleLowerCase().replace(/[^a-zA-Z\d]/g, ""); - return lc === lc.split("").reverse().join(""); + const lc = s.toLocaleLowerCase().replace(/[^a-zA-Z\d]/g, "") + return lc === lc.split("").reverse().join("") } // function isPalindrome(s: string): boolean { @@ -24,9 +24,9 @@ function isPalindrome(s: string): boolean { // } // Локальная проверка: -console.log(isPalindrome("A man, a plan, a canal: Panama")); -console.log(isPalindrome("race a car")); -console.log(isPalindrome(" ")); +console.log(isPalindrome("A man, a plan, a canal: Panama")) +console.log(isPalindrome("race a car")) +console.log(isPalindrome(" ")) ``` ```md @@ -36,13 +36,13 @@ Example 1: Output: true Explanation: "amanaplanacanalpanama" is a palindrome. - Example 2: +Example 2: Input: s = "race a car" Output: false Explanation: "raceacar" is not a palindrome. - Example 3: +Example 3: Input: s = " " Output: true diff --git a/content-ru/leetcode/Two Pointers/151-reverse-words-in-a-string.md b/content-ru/leetcode/Two Pointers/151-reverse-words-in-a-string.md index b0fd83149af28..3b04118338b02 100644 --- a/content-ru/leetcode/Two Pointers/151-reverse-words-in-a-string.md +++ b/content-ru/leetcode/Two Pointers/151-reverse-words-in-a-string.md @@ -8,18 +8,19 @@ > В возвращённой строке слова должны быть разделены ровно одним пробелом. > Не включайте лишние пробелы. > Ограничения: - 1 <= s.length <= 10^4 - s содержит английские буквы (верхнего и нижнего регистра), цифры и пробелы ' '. +> > - В s есть хотя бы одно слово. -> Дополнительный вопрос: если тип данных строки в вашем языке изменяемый, сможете ли вы решить задачу на месте с O(1) дополнительной памяти? +> Дополнительный вопрос: если тип данных строки в вашем языке изменяемый, сможете ли вы решить задачу на месте с O(1) дополнительной памяти? ```ts function reverseWords(s: string): string { - return s.trim().split(/\s+/).reverse().join(" "); + return s.trim().split(/\s+/).reverse().join(" ") } // Local check: -console.log(reverseWords("the sky is blue")); -console.log(reverseWords(" hello world ")); -console.log(reverseWords("a good example")); +console.log(reverseWords("the sky is blue")) +console.log(reverseWords(" hello world ")) +console.log(reverseWords("a good example")) ``` ```md @@ -28,13 +29,13 @@ Example 1: Input: s = "the sky is blue" Output: "blue is sky the" - Example 2: +Example 2: Input: s = " hello world " Output: "world hello" Explanation: Your reversed string should not contain leading or trailing spaces. - Example 3: +Example 3: Input: s = "a good example" Output: "example good a" diff --git a/content-ru/leetcode/Two Pointers/1768-merge-strings-alternately.md b/content-ru/leetcode/Two Pointers/1768-merge-strings-alternately.md index 7ce05d6916107..4b2bd2c83e76e 100644 --- a/content-ru/leetcode/Two Pointers/1768-merge-strings-alternately.md +++ b/content-ru/leetcode/Two Pointers/1768-merge-strings-alternately.md @@ -10,18 +10,16 @@ function mergeAlternately(word1: string, word2: string): string { const result: string[] = [] for (let i = 0; i < Math.max(word1.length, word2.length); i++) { - if (i < word1.length) - result.push(word1[i]) - if (i < word2.length) - result.push(word2[i]) + if (i < word1.length) result.push(word1[i]) + if (i < word2.length) result.push(word2[i]) } - return result.join('') + return result.join("") } // Локальная проверка: -console.log(mergeAlternately('abc', 'pqr')) -console.log(mergeAlternately('ab', 'pqrs')) -console.log(mergeAlternately('abcd', 'pq')) +console.log(mergeAlternately("abc", "pqr")) +console.log(mergeAlternately("ab", "pqrs")) +console.log(mergeAlternately("abcd", "pq")) ``` ```md @@ -34,7 +32,7 @@ console.log(mergeAlternately('abcd', 'pq')) word2: p q r merged: a p b q c r - Пример 2: +Пример 2: Ввод: word1 = "ab", word2 = "pqrs" Вывод: "apbqrs" @@ -43,7 +41,7 @@ console.log(mergeAlternately('abcd', 'pq')) word2: p q r s merged: a p b q r s - Пример 3: +Пример 3: Ввод: word1 = "abcd", word2 = "pq" Вывод: "apbqcd" diff --git a/content-ru/leetcode/Two Pointers/345-reverse-vowels-of-a-string.md b/content-ru/leetcode/Two Pointers/345-reverse-vowels-of-a-string.md index eec60e4bcf59c..2859f303d099f 100644 --- a/content-ru/leetcode/Two Pointers/345-reverse-vowels-of-a-string.md +++ b/content-ru/leetcode/Two Pointers/345-reverse-vowels-of-a-string.md @@ -6,8 +6,8 @@ ```ts function reverseVowels(s: string): string { - const chars = s.split('') - const vowels = 'aeiouAEIOU' + const chars = s.split("") + const vowels = "aeiouAEIOU" for (let left = 0, right = chars.length - 1; left < right;) { if (!vowels.includes(chars[left])) { @@ -28,12 +28,12 @@ function reverseVowels(s: string): string { right-- } - return chars.join('') + return chars.join("") } // Локальная проверка: -console.log(reverseVowels('IceCreAm')) -console.log(reverseVowels('leetcode')) +console.log(reverseVowels("IceCreAm")) +console.log(reverseVowels("leetcode")) ``` ```md @@ -44,7 +44,7 @@ console.log(reverseVowels('leetcode')) Объяснение: гласные в s — ['I', 'e', 'e', 'A']. После переворота гласных s становится "AceCreIm". - Пример 2: +Пример 2: Вход: s = "leetcode" Выход: "leotcede" diff --git a/content-ru/leetcode/Two Pointers/392-is-subsequence.md b/content-ru/leetcode/Two Pointers/392-is-subsequence.md index aed5563aec099..dbe5de5e583d5 100644 --- a/content-ru/leetcode/Two Pointers/392-is-subsequence.md +++ b/content-ru/leetcode/Two Pointers/392-is-subsequence.md @@ -25,12 +25,12 @@ console.log(isSubsequence("axc", "ahbgdc")) ```md Example 1: - Input: s = "abc", t = "ahbgdc" - Output: true +Input: s = "abc", t = "ahbgdc" +Output: true - Example 2: - Input: s = "axc", t = "ahbgdc" - Output: false +Example 2: +Input: s = "axc", t = "ahbgdc" +Output: false ``` [[leetcode/Two Pointers/index|two-pointers]] diff --git a/content-ru/leetcode/Two Pointers/844-backspace-string-compare.md b/content-ru/leetcode/Two Pointers/844-backspace-string-compare.md index 884a75324567b..27993532de09a 100644 --- a/content-ru/leetcode/Two Pointers/844-backspace-string-compare.md +++ b/content-ru/leetcode/Two Pointers/844-backspace-string-compare.md @@ -12,54 +12,54 @@ function backspaceCompare(s: string, t: string): boolean { str .split("") .reduce((stack, ch) => { - ch === "#" ? stack.pop() : stack.push(ch); - return stack; + ch === "#" ? stack.pop() : stack.push(ch) + return stack }, []) - .join(""); + .join("") - return process(s) === process(t); + return process(s) === process(t) } // interview function backspaceCompare2(s: string, t: string): boolean { - let i = s.length - 1; - let j = t.length - 1; - let skipS = 0; - let skipT = 0; + let i = s.length - 1 + let j = t.length - 1 + let skipS = 0 + let skipT = 0 while (i >= 0 || j >= 0) { while (i >= 0) { if (s[i] === "#") { - skipS++; - i--; + skipS++ + i-- } else if (skipS > 0) { - skipS--; - i--; - } else break; + skipS-- + i-- + } else break } while (j >= 0) { if (t[j] === "#") { - skipT++; - j--; + skipT++ + j-- } else if (skipT > 0) { - skipT--; - j--; - } else break; + skipT-- + j-- + } else break } - if (s[i] !== t[j]) return false; - i--; - j--; + if (s[i] !== t[j]) return false + i-- + j-- } - return true; + return true } // Local check: -console.log(backspaceCompare("ab#c", "ad#c")); -console.log(backspaceCompare("ab##", "c#d#")); -console.log(backspaceCompare("a#c", "b")); +console.log(backspaceCompare("ab#c", "ad#c")) +console.log(backspaceCompare("ab##", "c#d#")) +console.log(backspaceCompare("a#c", "b")) ``` ```md @@ -69,13 +69,13 @@ Example 1: Output: true Explanation: Both s and t become "ac". - Example 2: +Example 2: Input: s = "ab##", t = "c#d#" Output: true Explanation: Both s and t become "". - Example 3: +Example 3: Input: s = "a#c", t = "b" Output: false diff --git a/content-ru/leetcode/Untagged/125-valid-palindrome-neetcode.md b/content-ru/leetcode/Untagged/125-valid-palindrome-neetcode.md index 406d5000b09c9..47a93ec21308c 100644 --- a/content-ru/leetcode/Untagged/125-valid-palindrome-neetcode.md +++ b/content-ru/leetcode/Untagged/125-valid-palindrome-neetcode.md @@ -7,16 +7,17 @@ ```ts function isPalindrome(s: string): boolean { - const cleaned = s.toLowerCase().replace(/[^a-z0-9]/g, ''); - let left = 0, right = cleaned.length - 1; + const cleaned = s.toLowerCase().replace(/[^a-z0-9]/g, "") + let left = 0, + right = cleaned.length - 1 while (left < right) { - if (cleaned[left] !== cleaned[right]) return false; - left++; - right--; + if (cleaned[left] !== cleaned[right]) return false + left++ + right-- } - return true; + return true } // Локальная проверка: @@ -33,13 +34,13 @@ console.log(isPalindrome("No lemon, no melon")) // true Вывод: true Объяснение: "amanaplanacanalpanama" — палиндром. - Пример 2: +Пример 2: Ввод: s = "race a car" Вывод: false Объяснение: "raceacar" не является палиндромом. - Пример 3: +Пример 3: Ввод: s = " " Вывод: true diff --git a/content-ru/leetcode/Untagged/2620-counter.md b/content-ru/leetcode/Untagged/2620-counter.md index 52c19433307b9..149d4f839bfbc 100644 --- a/content-ru/leetcode/Untagged/2620-counter.md +++ b/content-ru/leetcode/Untagged/2620-counter.md @@ -1,6 +1,7 @@ # 2620. Counter (?) () + > Дано целое число n, верните функцию-счётчик. > Эта функция-счётчик изначально возвращает n, а затем при каждом последующем вызове возвращает значение на 1 больше предыдущего (n, n + 1, n + 2 и т.д.). @@ -24,7 +25,7 @@ Example 1: counter() = 11 // Returns 1 more than the previous time. counter() = 12 // Returns 1 more than the previous time. - Example 2: +Example 2: Input: n = -2 diff --git a/content-ru/leetcode/Untagged/2622-cache-with-time-limit.md b/content-ru/leetcode/Untagged/2622-cache-with-time-limit.md index 67a9624d92eaf..27c937e901696 100644 --- a/content-ru/leetcode/Untagged/2622-cache-with-time-limit.md +++ b/content-ru/leetcode/Untagged/2622-cache-with-time-limit.md @@ -12,7 +12,7 @@ ```ts class TimeLimitedCache { - cache: Map }> + cache: Map }> constructor() { this.cache = new Map() @@ -41,12 +41,11 @@ class TimeLimitedCache { } } - const timeLimitedCache = new TimeLimitedCache() setTimeout(() => console.log(timeLimitedCache.set(1, 42, 50)), 0) // false setTimeout(() => console.log(timeLimitedCache.set(1, 50, 100)), 40) // true setTimeout(() => console.log(timeLimitedCache.get(1)), 50) // 50 -setTimeout(() => console.log(timeLimitedCache.get(1)), 120)// 50 +setTimeout(() => console.log(timeLimitedCache.get(1)), 120) // 50 setTimeout(() => console.log(timeLimitedCache.get(1)), 200) // -1 setTimeout(() => console.log(timeLimitedCache.count()), 250) // 0 ``` @@ -68,7 +67,7 @@ setTimeout(() => console.log(timeLimitedCache.count()), 250) // 0 В момент t=100 ключ=1 истекает. В момент t=150 вызывается get(1), но возвращается -1, потому что кэш пуст. - Пример 2: +Пример 2: Ввод: actions = ["TimeLimitedCache", "set", "set", "get", "get", "get", "count"] @@ -79,7 +78,9 @@ setTimeout(() => console.log(timeLimitedCache.count()), 250) // 0 В момент t=0 кэш создаётся. В момент t=0 добавляется пара ключ-значение (1: 42) с ограничением по времени 50мс. Значение не существует, поэтому возвращается false. + + В момент t=40 добавляется пара ключ-значение (1: 50) с ограничением по времени 100мс. Неистёкшее значение уже существовало, поэтому возвращается true, а старое значение было перезаписано. diff --git a/content-ru/leetcode/Untagged/2623-memoize.md b/content-ru/leetcode/Untagged/2623-memoize.md index d81932f516923..918bfa6b01e9b 100644 --- a/content-ru/leetcode/Untagged/2623-memoize.md +++ b/content-ru/leetcode/Untagged/2623-memoize.md @@ -54,13 +54,15 @@ Example 1: memoizedSum(1, 2); // "call" - returns 3. sum() was called as (1, 2) was not seen before. // "getCallCount" - total call count: 2 - Example 2: +Example 2: Input: fnName = "factorial" actions = ["call","call","call","getCallCount","call","getCallCount"] values = [[2],[3],[2],[],[3],[]] + + Output: [2,6,2,2,6,2] Explanation: const factorial = (n) => (n <= 1) ? 1 : (nfactorial(n - 1)); @@ -72,7 +74,7 @@ Example 1: memoFactorial(3); // "call" - returns 6. However factorial was not called because 3 was seen before. // "getCallCount" - total call count: 2 - Example 3: +Example 3: Input: fnName = "fib" diff --git a/content-ru/leetcode/Untagged/2626-array-reduce-transformation.md b/content-ru/leetcode/Untagged/2626-array-reduce-transformation.md index aa40704dc0cc8..fa4599d8d2b88 100644 --- a/content-ru/leetcode/Untagged/2626-array-reduce-transformation.md +++ b/content-ru/leetcode/Untagged/2626-array-reduce-transformation.md @@ -40,7 +40,7 @@ console.log(reduce([], () => 0, 25)) // 25 (6) + nums[3] = 10 Итоговый ответ — 10. - Пример 2: +Пример 2: Вход: nums = [1,2,3,4] @@ -53,10 +53,12 @@ console.log(reduce([], () => 0, 25)) // 25 (101) + nums[1] * nums[1] = 105 (105) + nums[2] * nums[2] = 114 (114) + nums[3] * nums[3] = 130 + + Итоговый ответ — 130. - Пример 3: +Пример 3: Вход: nums = [] diff --git a/content-ru/leetcode/Untagged/2627-debounce.md b/content-ru/leetcode/Untagged/2627-debounce.md index 1ded38969e0a2..5dc74c13535bb 100644 --- a/content-ru/leetcode/Untagged/2627-debounce.md +++ b/content-ru/leetcode/Untagged/2627-debounce.md @@ -23,17 +23,18 @@ function debounce(fn: F, t: number): F { } const log = debounce(console.log, 100) -log('Hello') // cancelled -console.log('1') -log('Hello') // cancelled -console.log('2') -log('Hello') // Logged at t=100ms +log("Hello") // cancelled +console.log("1") +log("Hello") // cancelled +console.log("2") +log("Hello") // Logged at t=100ms ``` ```md Пример 1: + Input: t = 50 calls = [ @@ -46,7 +47,7 @@ log('Hello') // Logged at t=100ms before 100ms. The 2nd call is delayed by 50ms and executed at 125ms. The inputs were (2). - Пример 2: +Пример 2: Input: t = 20 @@ -59,7 +60,7 @@ log('Hello') // Logged at t=100ms The 1st call is delayed until 70ms. The inputs were (1). The 2nd call is delayed until 120ms. The inputs were (2). - Пример 3: +Пример 3: Input: t = 150 diff --git a/content-ru/leetcode/Untagged/2629-function-composition.md b/content-ru/leetcode/Untagged/2629-function-composition.md index 4505b2c1a4ca2..8a68df8decb0d 100644 --- a/content-ru/leetcode/Untagged/2629-function-composition.md +++ b/content-ru/leetcode/Untagged/2629-function-composition.md @@ -15,7 +15,7 @@ function compose(functions: Fn[]): Fn { } } -const fn = compose([x => x + 1, x => 2 * x]) +const fn = compose([(x) => x + 1, (x) => 2 * x]) console.log(fn(4)) // 9 ``` @@ -33,7 +33,7 @@ Example 1: 8 * 8 = 64 64 + 1 = 65 - Example 2: +Example 2: Input: functions = [x => 10 * x, x => 10 * x, x => 10 * x] @@ -42,11 +42,13 @@ Example 1: Explanation: Evaluating from right to left ... 10 * 1 = 10 + + 10 * 10 = 100 10 * 100 = 1000 - Example 3: +Example 3: Input: functions = [] diff --git a/content-ru/leetcode/Untagged/2631-group-by.md b/content-ru/leetcode/Untagged/2631-group-by.md index 248ace74e7460..68574c40fe623 100644 --- a/content-ru/leetcode/Untagged/2631-group-by.md +++ b/content-ru/leetcode/Untagged/2631-group-by.md @@ -24,8 +24,7 @@ Array.prototype.groupBy = function (this: T[], fn: (item: T) => string): Reco if (key in result) { result[key].push(item) - } - else { + } else { result[key] = [item] } } @@ -34,10 +33,15 @@ Array.prototype.groupBy = function (this: T[], fn: (item: T) => string): Reco } // Локальная проверка: -console.log([{ id: '1' }, { id: '1' }, { id: '2' }].groupBy(item => item.id)) -console.log([[1, 2, 3], [1, 3, 5], [1, 5, 9]].groupBy(list => String(list[0]))) -console.log([1, 2, 3, 4, 5, 6, 7, 8, 9, 10].groupBy(n => String(n > 5))) - +console.log([{ id: "1" }, { id: "1" }, { id: "2" }].groupBy((item) => item.id)) +console.log( + [ + [1, 2, 3], + [1, 3, 5], + [1, 5, 9], + ].groupBy((list) => String(list[0])), +) +console.log([1, 2, 3, 4, 5, 6, 7, 8, 9, 10].groupBy((n) => String(n > 5))) export {} ``` @@ -66,13 +70,15 @@ Example 1: the first array. There is one object with an "id" of 2. That object is put in the second array. - Example 2: +Example 2: Input: array = [ [1, 2, 3], [1, 3, 5], + + [1, 5, 9] ] fn = function (list) { @@ -87,7 +93,7 @@ Example 1: the key as being the first element in the array. All the arrays have 1 as their first element so they are grouped together. - Example 3: +Example 3: Input: array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] diff --git a/content-ru/leetcode/Untagged/2637-promise-time-limit.md b/content-ru/leetcode/Untagged/2637-promise-time-limit.md index b6ca09ea0c5a1..2fc9c19f7d858 100644 --- a/content-ru/leetcode/Untagged/2637-promise-time-limit.md +++ b/content-ru/leetcode/Untagged/2637-promise-time-limit.md @@ -3,8 +3,9 @@ > Дана асинхронная функция fn и время t в миллисекундах, верните новую версию входной функции с ограничением по времени. > fn принимает аргументы, переданные функции с ограничением по времени. > Функция с ограничением по времени должна следовать этим правилам: - Если fn завершается в пределах лимита времени t миллисекунд, функция с ограничением по времени должна разрешиться (resolve) с результатом. +> > - Если выполнение fn превышает лимит времени, функция с ограничением по времени должна отклониться (reject) со строкой "Time Limit Exceeded". -> Ограничения: - 0 <= inputs.length <= 10 - 0 <= t <= 1000 - fn возвращает promise +> Ограничения: - 0 <= inputs.length <= 10 - 0 <= t <= 1000 - fn возвращает promise ```ts type Fn = (...params: any[]) => Promise @@ -14,12 +15,12 @@ function timeLimit(fn: Fn, t: number): Fn { return Promise.race([ fn(...args), // eslint-disable-next-line prefer-promise-reject-errors - new Promise((_, reject) => setTimeout(() => reject('Time Limit Exceeded'), t)), + new Promise((_, reject) => setTimeout(() => reject("Time Limit Exceeded"), t)), ]) } -}; +} -const limited = timeLimit(t => new Promise(res => setTimeout(res, t)), 100) +const limited = timeLimit((t) => new Promise((res) => setTimeout(res, t)), 100) limited(150).catch(console.log) // "Time Limit Exceeded" at t=100ms ``` @@ -38,7 +39,7 @@ Example 1: The provided function is set to resolve after 100ms. However, the time limit is set to 50ms. It rejects at t=50ms because the time limit was reached. - Example 2: +Example 2: Input: fn = async (n) => { @@ -51,7 +52,7 @@ Example 1: Explanation: The function resolved 5 * 5 = 25 at t=100ms. The time limit is never reached. - Example 3: +Example 3: Input: fn = async (a, b) => { @@ -64,7 +65,7 @@ Example 1: Explanation: The function resolved 5 + 10 = 15 at t=120ms. The time limit is never reached. - Example 4: +Example 4: Input: fn = async () => { diff --git a/content-ru/leetcode/Untagged/2665-counter2.md b/content-ru/leetcode/Untagged/2665-counter2.md index 6b91e8d104d6a..4311d2e7e14c2 100644 --- a/content-ru/leetcode/Untagged/2665-counter2.md +++ b/content-ru/leetcode/Untagged/2665-counter2.md @@ -1,10 +1,12 @@ # 2665. Counter II (?) () + > Напишите функцию createCounter. > Она должна принимать начальное целое число init. > Она должна возвращать объект с тремя функциями. > Эти три функции: - increment() увеличивает текущее значение на 1 и возвращает его. +> > - decrement() уменьшает текущее значение на 1 и возвращает его. > - reset() устанавливает текущее значение равным init и возвращает его. @@ -23,7 +25,7 @@ function createCounter(init: number): Counter { decrement: () => --value, reset: () => (value = init), } -}; +} ``` ```md @@ -37,7 +39,7 @@ Example 1: counter.reset(); // 5 counter.decrement(); // 4 - Example 2: +Example 2: Input: init = 0, calls = ["increment","increment","decrement","reset","reset"] Output: [1,2,1,0,0] diff --git a/content-ru/leetcode/Untagged/2666-allow-one-fn-call.md b/content-ru/leetcode/Untagged/2666-allow-one-fn-call.md index 86633558e9f1a..5370e28f7e4e9 100644 --- a/content-ru/leetcode/Untagged/2666-allow-one-fn-call.md +++ b/content-ru/leetcode/Untagged/2666-allow-one-fn-call.md @@ -1,6 +1,7 @@ # 2666. Разрешить только один вызов функции (?) () + > Дана функция fn, верните новую функцию, идентичную исходной, за исключением того, что она гарантирует вызов fn не более одного раза. > При первом вызове возвращённая функция должна вернуть тот же результат, что и fn. > При каждом последующем вызове она должна возвращать undefined. @@ -13,8 +14,7 @@ function once(fn: Function): OnceFn { let called = false return function (...args: JSONValue[]): JSONValue | undefined { - if (called) - return undefined + if (called) return undefined called = true return fn(...args) @@ -25,16 +25,16 @@ function once(fn: Function): OnceFn { ```md Example 1: - Input: fn = (a,b,c) => (a + b + c), calls = [[1,2,3],[2,3,6]] +Input: fn = (a,b,c) => (a + b + c), calls = [[1,2,3],[2,3,6]] Output: [{"calls":1,"value":6}] Explanation: const onceFn = once(fn); onceFn(1, 2, 3); // 6 onceFn(2, 3, 6); // undefined, fn was not called - Example 2: +Example 2: - Input: fn = (a,b,c) => (a * b * c), calls = [[5,7,4],[2,3,6],[4,6,8]] +Input: fn = (a,b,c) => (a * b * c), calls = [[5,7,4],[2,3,6],[4,6,8]] Output: [{"calls":1,"value":140}] Explanation: const onceFn = once(fn); diff --git a/content-ru/leetcode/Untagged/2677-chunk-array.md b/content-ru/leetcode/Untagged/2677-chunk-array.md index 25e99a330c0b1..4ea5befc05e92 100644 --- a/content-ru/leetcode/Untagged/2677-chunk-array.md +++ b/content-ru/leetcode/Untagged/2677-chunk-array.md @@ -18,7 +18,7 @@ function chunk(arr: Obj[], size: number): Obj[][] { result.push(arr.slice(i, i + size)) } return result -}; +} // function chunk(arr: Obj[], size: number): Obj[][] { // return arr.reduce((acc, item, index) => { @@ -46,21 +46,22 @@ Example 1: Output: [[1],[2],[3],[4],[5]] Explanation: The arr has been split into subarrays each with 1 element. - Example 2: +Example 2: Input: arr = [1,9,6,3,2], size = 3 Output: [[1,9,6],[3,2]] Explanation: The arr has been split into subarrays with 3 elements. However, only two elements are left for the 2nd subarray. - Example 3: +Example 3: Input: arr = [8,5,3,2,6], size = 6 Output: [[8,5,3,2,6]] Explanation: Size is greater than arr.length thus all elements are in the first subarray. - Example 4: +Example 4: + Input: arr = [], size = 1 Output: [] Explanation: There are no elements to be chunked so an empty array is returned. diff --git a/content-ru/leetcode/Untagged/2693-call-function-with-custom-context.md b/content-ru/leetcode/Untagged/2693-call-function-with-custom-context.md index 19ee2e83d66c7..104d2b281f7a7 100644 --- a/content-ru/leetcode/Untagged/2693-call-function-with-custom-context.md +++ b/content-ru/leetcode/Untagged/2693-call-function-with-custom-context.md @@ -1,6 +1,7 @@ # 2693. Вызов функции с пользовательским контекстом (Medium) () + > Расширьте все функции методом callPolyfill. > Метод принимает объект obj в качестве первого параметра и любое количество дополнительных аргументов. > obj становится контекстом this для функции. @@ -18,7 +19,7 @@ interface Function { /* Временно делаем функцию методом объекта */ Function.prototype.callPolyfill = function (context, ...args): JSONValue { let object = { ...context } as any - let symbol = Symbol('context') + let symbol = Symbol("context") // this здесь — это функция object[symbol] = this // Вызываем add как метод object @@ -32,7 +33,6 @@ function add(this: { a: number }, b: number) { console.log(add.callPolyfill({ a: 5 }, 7)) // 12 - export {} ``` @@ -50,7 +50,7 @@ Example 1: callPolyfill sets the "this" context to { "a": 5 }. 7 is passed as an argument. - Example 2: +Example 2: Input: fn = function tax(price, taxRate) { diff --git a/content-ru/leetcode/Untagged/2703-return-length-of-arguments-passed.md b/content-ru/leetcode/Untagged/2703-return-length-of-arguments-passed.md index 8f04f2e296c9f..bb7327b8b9307 100644 --- a/content-ru/leetcode/Untagged/2703-return-length-of-arguments-passed.md +++ b/content-ru/leetcode/Untagged/2703-return-length-of-arguments-passed.md @@ -1,6 +1,7 @@ # 2703. Верните количество переданных аргументов (Легко) () + > Напишите функцию argumentsLength, которая возвращает количество переданных ей аргументов. > Ограничения: - args является валидным JSON-массивом - 0 <= args.length <= 100 @@ -16,7 +17,7 @@ function argumentsLength(...args: JSONValue[]): number { console.log(argumentsLength(1, 2, 3)) // 3 console.log(argumentsLength(5)) // 1 -console.log(argumentsLength({}, null, '3')) // 3 +console.log(argumentsLength({}, null, "3")) // 3 ``` ```md @@ -29,7 +30,7 @@ console.log(argumentsLength({}, null, '3')) // 3 В функцию было передано одно значение, поэтому она должна вернуть 1. - Пример 2: +Пример 2: Ввод: args = [{}, null, "3"] Вывод: 3 diff --git a/content-ru/leetcode/Untagged/271-string-encode-and-decode.md b/content-ru/leetcode/Untagged/271-string-encode-and-decode.md index 7120d7e366658..025bd0faf7550 100644 --- a/content-ru/leetcode/Untagged/271-string-encode-and-decode.md +++ b/content-ru/leetcode/Untagged/271-string-encode-and-decode.md @@ -3,19 +3,18 @@ > Разработайте алгоритм для кодирования списка строк в одну строку. > Закодированная строка затем декодируется обратно в исходный список строк. > Ограничения / Примечания: - Входные строки могут содержать любые символы. +> > - Необходимо обеспечить однозначную обратимость кодирования. ```ts class Codec { - constructor() { - - } + constructor() {} encode(strs: string[]): string { // [length] + "#" + [data] - let encoded_string = '' + let encoded_string = "" for (const word of strs) { - encoded_string += word.length + '#' + word + encoded_string += word.length + "#" + word } return encoded_string } @@ -25,8 +24,8 @@ class Codec { let idx = 0 while (idx < s.length) { - let length: string = '' - while (idx < s.length && s[idx] !== '#') { + let length: string = "" + while (idx < s.length && s[idx] !== "#") { length += s[idx] idx += 1 } @@ -38,7 +37,6 @@ class Codec { } } - // Local check: const codec = new Codec() @@ -55,7 +53,7 @@ console.log(codec.decode(codec.encode([""]))) Объяснение: После кодирования и последующего декодирования мы получаем обратно исходный массив. - Пример 2: +Пример 2: Вход: ["lint","code","love","you"] Выход: ["lint","code","love","you"] diff --git a/content-ru/leetcode/Untagged/2715-timeout-cancellation.md b/content-ru/leetcode/Untagged/2715-timeout-cancellation.md index 14efb7c75dc76..56a95660370eb 100644 --- a/content-ru/leetcode/Untagged/2715-timeout-cancellation.md +++ b/content-ru/leetcode/Untagged/2715-timeout-cancellation.md @@ -46,7 +46,7 @@ setTimeout(() => { Отмена была запланирована после задержки cancelTimeMs (50 мс), что произошло после выполнения fn(2) в момент 20 мс. - Пример 2: +Пример 2: Ввод: fn = (x) => x**2, args = [2], t = 100 Вывод: [] @@ -58,9 +58,10 @@ setTimeout(() => { Отмена была запланирована после задержки cancelTimeMs (50 мс), что произошло до выполнения fn(2) в момент 100 мс, в результате fn(2) так и не была вызвана. - Пример 3: +Пример 3: + Ввод: fn = (x1, x2) => x1 * x2, args = [2,4], t = 30 Вывод: [{"time": 30, "returned": 8}] Объяснение: diff --git a/content-ru/leetcode/Untagged/2721-execute-asynchronous-functions-in-parallel.md b/content-ru/leetcode/Untagged/2721-execute-asynchronous-functions-in-parallel.md index f6f57f9f447fd..8ba177c64d60d 100644 --- a/content-ru/leetcode/Untagged/2721-execute-asynchronous-functions-in-parallel.md +++ b/content-ru/leetcode/Untagged/2721-execute-asynchronous-functions-in-parallel.md @@ -4,12 +4,13 @@ > Каждая функция в массиве не принимает аргументов и возвращает promise. > Все promise'ы должны выполняться параллельно. > Promise разрешается: - когда все promise'ы, возвращённые из functions, успешно разрешились. +> > - Разрешённое значение должно быть массивом всех разрешённых значений в том же порядке, в каком они были в functions. > - Он должен разрешаться, когда все асинхронные функции завершили выполнение параллельно. -> Promise отклоняется: - когда любой promise, возвращённый из functions, был отклонён. +> Promise отклоняется: - когда любой promise, возвращённый из functions, был отклонён. > - Он должен отклоняться с причиной первого отклонения. -> Пожалуйста, решите без использования встроенной функции Promise.all. -> Ограничения: - functions — массив функций, возвращающих promise'ы - 1 <= functions.length <= 10 +> Пожалуйста, решите без использования встроенной функции Promise.all. +> Ограничения: - functions — массив функций, возвращающих promise'ы - 1 <= functions.length <= 10 ```ts type Fn = () => Promise @@ -20,18 +21,19 @@ function promiseAll(functions: Fn[]): Promise { let completed = 0 functions.map(async (fn, i) => { - await fn().then((res) => { - results[i] = res - completed++ - }).catch((err) => { - reject(err) - }) - - if (completed === functions.length) - resolve(results) + await fn() + .then((res) => { + results[i] = res + completed++ + }) + .catch((err) => { + reject(err) + }) + + if (completed === functions.length) resolve(results) }) }) -}; +} // for (let i = 0; i < functions.length; i++) { // functions[i]() @@ -48,7 +50,7 @@ function promiseAll(functions: Fn[]): Promise { // }) // } -const promise = promiseAll([() => new Promise(res => res(42))]) +const promise = promiseAll([() => new Promise((res) => res(42))]) promise.then(console.log) ``` @@ -60,12 +62,14 @@ promise.then(console.log) () => new Promise(resolve => setTimeout(() => resolve(5), 200)) ] Вывод: {"t": 200, "resolved": [5]} + + Объяснение: promiseAll(functions).then(console.log) // [5] Единственная функция разрешилась на 200мс со значением 5. - Пример 2: +Пример 2: Ввод: functions = [ @@ -77,7 +81,7 @@ promise.then(console.log) Поскольку один из promise'ов отклонился, возвращённый promise также отклонился с той же ошибкой в то же время. - Пример 3: +Пример 3: Ввод: functions = [ diff --git a/content-ru/leetcode/Untagged/2723-add-two-promises.md b/content-ru/leetcode/Untagged/2723-add-two-promises.md index 83c89c6f79ec6..81ce8580e3c41 100644 --- a/content-ru/leetcode/Untagged/2723-add-two-promises.md +++ b/content-ru/leetcode/Untagged/2723-add-two-promises.md @@ -1,6 +1,7 @@ # 2723. Add Two Promises (Easy) () + > Даны два промиса promise1 и promise2, верните новый промис. > promise1 и promise2 оба разрешатся числом. > Возвращаемый промис должен разрешиться суммой двух чисел. @@ -14,14 +15,11 @@ async function addTwoPromises( return Promise.all([promise1, promise2]).then(([result1, result2]) => result1 + result2) } -addTwoPromises(Promise.resolve(2), Promise.resolve(2)) - .then(console.log) // 4 +addTwoPromises(Promise.resolve(2), Promise.resolve(2)).then(console.log) // 4 -addTwoPromises(Promise.resolve(2), Promise.resolve(5)) - .then(console.log) // 7 +addTwoPromises(Promise.resolve(2), Promise.resolve(5)).then(console.log) // 7 -addTwoPromises(Promise.resolve(10), Promise.resolve(-12)) - .then(console.log) // -2 +addTwoPromises(Promise.resolve(10), Promise.resolve(-12)).then(console.log) // -2 ``` ```md @@ -36,7 +34,7 @@ addTwoPromises(Promise.resolve(10), Promise.resolve(-12)) Возвращаемый промис должен разрешиться значением 2 + 5 = 7. Время, за которое возвращаемый промис разрешается, в этой задаче не оценивается. - Пример 2: +Пример 2: Ввод: promise1 = new Promise(resolve => setTimeout(() => resolve(10), 50)), diff --git a/content-ru/leetcode/Untagged/2724-sort-by.md b/content-ru/leetcode/Untagged/2724-sort-by.md index 86eb5e06aed85..565c617520476 100644 --- a/content-ru/leetcode/Untagged/2724-sort-by.md +++ b/content-ru/leetcode/Untagged/2724-sort-by.md @@ -1,6 +1,7 @@ # 2724. Сортировка по (Easy) () + > Дан массив arr и функция fn, верните отсортированный массив sortedArr. > Можно считать, что fn возвращает только числа, и эти числа определяют порядок сортировки sortedArr. > sortedArr должен быть отсортирован по возрастанию значений, возвращаемых fn. @@ -17,9 +18,18 @@ function sortBy(arr: JSONValue[], fn: Fn): JSONValue[] { } // Local check: -console.log(sortBy([5, 4, 1, 2, 3], x => x as number)) // [1, 2, 3, 4, 5] -console.log(sortBy([{ x: 1 }, { x: 0 }, { x: -1 }], d => (d as { x: number }).x)) // [{ x: -1 }, { x: 0 }, { x: 1 }] -console.log(sortBy([[3, 4], [5, 2], [10, 1]], x => (x as number[])[1])) // [[10, 1], [5, 2], [3, 4]] +console.log(sortBy([5, 4, 1, 2, 3], (x) => x as number)) // [1, 2, 3, 4, 5] +console.log(sortBy([{ x: 1 }, { x: 0 }, { x: -1 }], (d) => (d as { x: number }).x)) // [{ x: -1 }, { x: 0 }, { x: 1 }] +console.log( + sortBy( + [ + [3, 4], + [5, 2], + [10, 1], + ], + (x) => (x as number[])[1], + ), +) // [[10, 1], [5, 2], [3, 4]] ``` ```md @@ -30,14 +40,14 @@ console.log(sortBy([[3, 4], [5, 2], [10, 1]], x => (x as number[])[1])) // [[10, Объяснение: fn просто возвращает переданное ей число, поэтому массив сортируется по возрастанию. - Пример 2: +Пример 2: Вход: arr = [{"x": 1}, {"x": 0}, {"x": -1}], fn = (d) => d.x Выход: [{"x": -1}, {"x": 0}, {"x": 1}] Объяснение: fn возвращает значение ключа "x". Поэтому массив сортируется по этому значению. - Пример 3: +Пример 3: Вход: arr = [[3, 4], [5, 2], [10, 1]], fn = (x) => x[1] Выход: [[10, 1], [5, 2], [3, 4]] diff --git a/content-ru/leetcode/Untagged/2725-interval-cancellation.md b/content-ru/leetcode/Untagged/2725-interval-cancellation.md index 1e02d8f3288c9..08e77f5121d01 100644 --- a/content-ru/leetcode/Untagged/2725-interval-cancellation.md +++ b/content-ru/leetcode/Untagged/2725-interval-cancellation.md @@ -15,7 +15,7 @@ function cancellable(fn: Fn, args: JSONValue[], t: number): Function { } // Локальная проверка -const result: { time: number, returned: JSONValue }[] = [] +const result: { time: number; returned: JSONValue }[] = [] const fn = (...values: JSONValue[]) => Number(values[0]) * 2 const args: JSONValue[] = [4] const t = 35 @@ -59,9 +59,10 @@ setTimeout(() => console.log(result), cancelTimeMs + t) 6th fn call is at 175ms. fn(4) returns 8. Cancelled at 190ms. - Пример 2: +Пример 2: + Input: fn = (x1, x2) => (x1 * x2), args = [2, 5], t = 30 Output: [ @@ -86,7 +87,7 @@ setTimeout(() => console.log(result), cancelTimeMs + t) 6th fn call is at 150ms. Cancelled at 165ms. - Пример 3: +Пример 3: Input: fn = (x1, x2, x3) => (x1 + x2 + x3), args = [5, 1, 3], t = 50 Output: diff --git a/content-ru/leetcode/Untagged/2726-calculator-with-method-chaining.md b/content-ru/leetcode/Untagged/2726-calculator-with-method-chaining.md index 103b1d2201ccb..8aed35c4c2f11 100644 --- a/content-ru/leetcode/Untagged/2726-calculator-with-method-chaining.md +++ b/content-ru/leetcode/Untagged/2726-calculator-with-method-chaining.md @@ -5,14 +5,15 @@ > Также он должен позволять выполнять последовательные операции с помощью цепочки методов (method chaining). > Конструктор класса Calculator должен принимать число, которое служит начальным значением result. > Ваш класс Calculator должен иметь следующие методы: - add: добавляет заданное значение value к result и возвращает обновлённый Calculator. +> > - subtract: вычитает заданное значение value из result и возвращает обновлённый Calculator. > - multiply: умножает result на заданное значение value и возвращает обновлённый Calculator. > - divide: делит result на заданное значение value и возвращает обновлённый Calculator. -> Если переданное значение равно 0, должна быть выброшена ошибка "Division by zero is not allowed". +> Если переданное значение равно 0, должна быть выброшена ошибка "Division by zero is not allowed". > - power: возводит result в степень заданного значения value и возвращает обновлённый Calculator. > - getResult: возвращает result. -> Решения с точностью до 10^-5 от фактического результата считаются верными. -> Ограничения: - actions — валидный JSON-массив строк - values — валидный JSON-массив чисел - 2 <= actions.length <= 2 * 10^4 - 1 <= values.length <= 2 * 10^4 - 1 - actions[i] — одно из значений "Calculator", "add", "subtract", "multiply", "divide", "power", "getResult" - Первое действие всегда "Calculator" - Последнее действие всегда "getResult" +> Решения с точностью до 10^-5 от фактического результата считаются верными. +> Ограничения: - actions — валидный JSON-массив строк - values — валидный JSON-массив чисел - 2 <= actions.length <= 2 * 10^4 - 1 <= values.length <= 2 * 10^4 - 1 - actions[i] — одно из значений "Calculator", "add", "subtract", "multiply", "divide", "power", "getResult" - Первое действие всегда "Calculator" - Последнее действие всегда "getResult" ```ts class Calculator { @@ -38,8 +39,7 @@ class Calculator { } divide(value: number): Calculator { - if (value === 0) - throw new Error('Division by zero is not allowed') + if (value === 0) throw new Error("Division by zero is not allowed") this.value /= value return this } @@ -66,12 +66,14 @@ Example 1: Input: actions = ["Calculator", "add", "subtract", "getResult"], values = [10, 5, 7] + + Output: 8 Explanation: new Calculator(10).add(5).subtract(7).getResult() // 10 + 5 - 7 = 8 - Example 2: +Example 2: Input: actions = ["Calculator", "multiply", "power", "getResult"], @@ -80,7 +82,7 @@ Example 1: Explanation: new Calculator(2).multiply(5).power(2).getResult() // (2 * 5) ^ 2 = 100 - Example 3: +Example 3: Input: actions = ["Calculator", "divide", "getResult"],